diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 426878bc4..2e6c64a5f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,6 +82,13 @@ jobs: scripts/fuzz-seed-frames.sh || true - name: Fuzz smoke run: make fuzz-smoke + - name: Nested select differential fuzz (serial and parallel) + run: | + # Start each mode from committed seeds. Replaying the growing cache + # can exhaust the short run before it reaches any mutations. + corpus_root=$(mktemp -d "$RUNNER_TEMP/select-merge.XXXXXX") + make fuzz-select_merge FUZZ_RUNTIME=60 FUZZ_CORPUS_ROOT="$corpus_root/serial" + RAY_FUZZ_CORES=4 make fuzz-select_merge FUZZ_RUNTIME=60 FUZZ_CORPUS_ROOT="$corpus_root/parallel" - name: Upload crash artifacts if: failure() uses: actions/upload-artifact@v4 @@ -108,7 +115,7 @@ jobs: - uses: actions/checkout@v4 - name: TSan concurrency suites run: | - for f in pool heap parallel stress; do + for f in pool heap parallel stress store/parted_concurrent_mounts; do echo "::group::tsan -f $f" make tsan-test TSAN_FILTER=$f || exit 1 echo "::endgroup::" diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 5a54d6c63..3fce7ea02 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -51,7 +51,10 @@ jobs: strategy: fail-fast: false matrix: - target: [parse, numparse, de, eval, csv, journal] + target: [parse, numparse, de, eval, csv, journal, select_merge] + include: + - target: select_merge + cores: 4 steps: - uses: actions/checkout@v4 with: { ref: dev } @@ -67,6 +70,8 @@ jobs: scripts/fuzz-seed-parse.sh || true scripts/fuzz-seed-frames.sh || true - name: Fuzz ${{ matrix.target }} (15 min) + env: + RAY_FUZZ_CORES: ${{ matrix.cores || 0 }} run: make fuzz-${{ matrix.target }} FUZZ_RUNTIME=900 - name: Upload crash artifacts if: failure() diff --git a/Makefile b/Makefile index 34bc67986..2fbaff3ae 100644 --- a/Makefile +++ b/Makefile @@ -376,8 +376,9 @@ compdb: # The system toolchain on macOS does not ship the fuzzer runtime, so # these targets are Linux-only by design; CI gates them to ubuntu. FUZZ_RUNTIME ?= 60 +FUZZ_CORPUS_ROOT ?= fuzz/corpus FUZZ_OPTS = -rss_limit_mb=4096 -timeout=10 -max_len=65536 -print_final_stats=1 -FUZZ_TARGETS = parse numparse de eval csv journal parquet +FUZZ_TARGETS = parse numparse de eval csv journal parquet select_merge # 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. @@ -406,14 +407,14 @@ build_fuzz/fuzz_%: fuzz/fuzz_%.c $(FUZZ_LIB_OBJ) .PRECIOUS: build_fuzz/fuzz_% fuzz-%: build_fuzz/fuzz_% - @mkdir -p fuzz/corpus/$* + @mkdir -p "$(FUZZ_CORPUS_ROOT)/$*" @dict=$(DICT_$*); \ dictopt=$${dict:+-dict=fuzz/dict/$$dict.dict}; \ 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 \ + ./build_fuzz/fuzz_$* "$(FUZZ_CORPUS_ROOT)/$*" $$seeds \ $$dictopt $(FUZZ_OPTS) -max_total_time=$(FUZZ_RUNTIME) # Short smoke pass for PR CI — a healthy corpus finds nothing new in a diff --git a/bench/concat_fallback.rfl b/bench/concat_fallback.rfl new file mode 100644 index 000000000..f0601e74f --- /dev/null +++ b/bench/concat_fallback.rfl @@ -0,0 +1,17 @@ +;; PR #744 concat helper / per-group fallback. Release build, -c 8. +;; Two million rows, one million two-row groups; first timing is warmup. +(set n 2000000) +(set i (til n)) +(set T (table [x k s t] (list i (% i 1000000) (take ['ab 'cd] n) (take ["a" "b"] n)))) +(set sfx (fn [v] (concat v "!"))) +(println "str-helper-projection") +(map (fn [_] (println (timeit (select {v: (sfx t) from: T})))) (til 4)) +(println "computed-text-group-fallback") +(map (fn [_] (println (timeit (select {n: (+ (count (concat (upper s) "!")) (count (distinct x))) by: k from: T})))) (til 4)) +;; Small inputs expose planning overhead. Timings cover 10,000 queries. +(set i (til 10)) +(set T (table [x k s] (list i (% i 3) (take ['a 'b] 10)))) +(set sfq (fn [v] (concat v "?"))) +(println "tiny-two-helper-group-fallback-10000") +(map (fn [_] (println (timeit (times 10000 (select {n: (+ (+ (count (sfx s)) (count (sfq s))) (count (distinct x))) by: k from: T}))))) (til 6)) +(exit 0) diff --git a/bench/concat_update_fallback.rfl b/bench/concat_update_fallback.rfl new file mode 100644 index 000000000..ea19af900 --- /dev/null +++ b/bench/concat_update_fallback.rfl @@ -0,0 +1,11 @@ +(set n 2000000) +(set i (til n)) +(set T (table [x k s] (list i (% i 1000000) (take ['ab 'cd] n)))) +(set sfx (fn [v] (concat v "!"))) +(println "no-concat") +(map (fn [_] (println (timeit (update {n: (+ (count s) (count (distinct x))) by: k from: T})))) (til 4)) +(println "computed-text") +(map (fn [_] (println (timeit (update {n: (+ (count (concat (upper s) "!")) (count (distinct x))) by: k from: T})))) (til 4)) +(println "helper") +(map (fn [_] (println (timeit (update {n: (+ (count (sfx s)) (count (distinct x))) by: k from: T})))) (til 4)) +(exit 0) diff --git a/bench/membership_fallback.rfl b/bench/membership_fallback.rfl new file mode 100644 index 000000000..d525fafcd --- /dev/null +++ b/bench/membership_fallback.rfl @@ -0,0 +1,16 @@ +;; PR #744 evaluator membership regression. Release build, -c 8. +;; Twenty million rows; milliseconds, first iteration is warmup. +(set n 20000000) +(set x (% (til n) 10)) +(set vocab (as 'SYM (as 'STR (til 10)))) +(set T (table [x s] (list x (at vocab x)))) +(println "symbol-inline-probe") +(map (fn [_] (println (timeit (select {from: T where: (in s (as 'SYM (list "1" "5" "7")))})))) (til 7)) +(println "integer-inline-probe") +(map (fn [_] (println (timeit (select {from: T where: (in x (distinct [1 5 7]))})))) (til 7)) +(println "symbol-planned-probe") +(set probe (as 'SYM (list "1" "5" "7"))) +(map (fn [_] (println (timeit (select {from: T where: (in s probe)})))) (til 7)) +(println "integer-planned-probe") +(map (fn [_] (println (timeit (select {from: T where: (in x [1 5 7])})))) (til 7)) +(exit 0) diff --git a/bench/nested_select.py b/bench/nested_select.py new file mode 100644 index 000000000..7c95b7ce6 --- /dev/null +++ b/bench/nested_select.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Issue #752: compare literal nesting, do-materialization and hand composition. + +Build: make release +Run: python3 bench/nested_select.py --binary ./rayforce --rows 5000000 +Sparse: add --a-period 1000 --widths 4 --rows 20000000 +The baseline uses `do` to keep the inner select materialized, without a runtime +optimizer flag. Every available variant must serialize identically before timing. +""" +import argparse +import os +import re +from pathlib import Path +import statistics +import subprocess +import tempfile + + +def materialized(expr): + """Wrap every literal from/select boundary, including three-layer cases.""" + insertions = [] + for match in re.finditer(r"from:\s*(?=\(select)", expr): + start = match.end() + depth = 0 + for end in range(start, len(expr)): + depth += (expr[end] == "(") - (expr[end] == ")") + if depth == 0: + insertions.extend(((start, "(do "), (end + 1, ")"))) + break + for pos, text in sorted(insertions, reverse=True): + expr = expr[:pos] + text + expr[pos:] + return expr + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", default="./rayforce") + parser.add_argument("--rows", type=int, default=5_000_000) + parser.add_argument("--runs", type=int, default=7) + parser.add_argument("--cores", type=int, default=4) + parser.add_argument("--a-period", type=int, default=3, + help="inner equality selectivity is 1 / a-period") + parser.add_argument("--widths", type=int, nargs="+", choices=(4, 40), default=(4, 40)) + args = parser.parse_args() + if args.rows < 1 or args.runs < 1 or args.a_period < 2: + parser.error("rows/runs must be positive and a-period must be at least 2") + lines = [f"(set I (til {args.rows}))"] + cases = [] + check_count = 0 + for width in args.widths: + cols = ["a", "b", "k", "p"] + [f"c{i}" for i in range(width - 4)] + vals = [f"(% I {args.a_period})", "(% I 5)", "(% I 100)", "(as 'F64 I)"] + [f"(+ I {i})" for i in range(width - 4)] + lines.append(f"(set T (table [{' '.join(cols)}] (list {' '.join(vals)})))") + identity = " ".join(f"{c}:{c}" for c in cols) + shapes = [ + ("from:T where:(== a 1)", "where:(== b 1) total:(sum p)", + "from:T where:(and (== a 1) (== b 1)) total:(sum p)"), + (f"from:T where:(== a 1) {identity} q:(* p 2)", "by:k total:(sum q)", + "from:T where:(== a 1) by:k total:(sum (* p 2))"), + ("from:T where:(== a 1)", "take:10", "from:T where:(== a 1) take:10"), + (f"from:T {identity}", "where:(== a 1) total:(sum p)", + "from:T where:(== a 1) total:(sum p)"), + # Review regressions: single predicate, rare/late and absent matches. + ("from:T where:(== b 1)", "total:(sum p)", + "from:T where:(== b 1) total:(sum p)"), + ("from:T where:(> b 3)", "total:(count a)", + "from:T where:(> b 3) total:(count a)"), + (f"from:T where:(> p {max(0, args.rows - 10)}.0)", "total:(sum p)", None), + (f"from:T where:(== p {args.rows * 3 // 4}.0)", "total:(sum p)", None), + (f"from:T where:(> p {max(0, args.rows - 10)}.0)", "by:k total:(sum p)", None), + (f"from:T where:(> p {args.rows}.0)", "total:(sum p)", None), + (f"from:T where:(> p {args.rows}.0)", "by:k total:(sum p)", None), + ("from:T q0:(* p 1.0001) q1:(+ q0 q0) q2:(+ q1 q1) q3:(+ q2 q2) q4:(+ q3 q3) q5:(+ q4 q4)", + "where:(> q5 1) v:q5", None), + (f"from:(select {{from:T where:(> p {max(0, args.rows - 10)}.0)}}) by:k total:(sum p)", + "total:total", None), + # Vary --a-period to compare selective and dense inner filters. + ("from:T where:(< a 10)", "where:(== b 1) total:(sum p)", None), + ("from:T where:(== a 1) q:p", "where:(> q 5) total:(avg q)", None), + (f"from:T where:(< a {max(1, args.a_period * 4 // 5)})", + "where:(== b 1) total:(sum p)", None), + ("from:T where:(== a 1)", "where:(== b 1) p:p", None), + ] + for number, (inner, outer, flat) in enumerate(shapes, 1): + tag = f"{width}/S{number}" + nested = f"(select {{from:(select {{{inner}}}) {outer}}})" + variants = {"materialized": materialized(nested), "nested": nested} + if flat is not None: + variants["manual"] = f"(select {{{flat}}})" + for name, expr in variants.items(): + lines.append(f"(set B_{name} (ser {expr}))") + for name in list(variants)[1:]: + check_count += 1 + lines.append(f'(println "CHECK {tag} {name} %" (if (== (count B_materialized) (count B_{name})) (all (== B_materialized B_{name})) false))') + for expr in variants.values(): + lines.append(f"(timeit {expr})") + for run in range(args.runs): + names = list(variants) if run % 2 == 0 else list(reversed(variants)) + for name in names: + lines.append(f'(println "TIME {tag} {name} %" (timeit {variants[name]}))') + cases.append(tag) + lines.append("(exit 0)") + with tempfile.TemporaryDirectory(prefix="ray-nested-select-") as tmp: + script = Path(tmp) / "bench.rfl" + # Keep the expanded matrix below the parser's top-level expression limit. + script.write_text("\n".join( + "(do\n" + "\n".join(lines[i:i + 64]) + "\n)" + for i in range(0, len(lines), 64)) + "\n") + result = subprocess.run([str(Path(args.binary).resolve()), str(script)], + env={**os.environ, "RAYFORCE_CORES": str(args.cores)}, + capture_output=True, text=True) + if result.returncode: + raise RuntimeError(f"benchmark failed:\n{result.stdout}\n{result.stderr}") + checks = [line for line in result.stdout.splitlines() if line.startswith("CHECK ")] + if len(checks) != check_count or any(not line.endswith("true") for line in checks): + raise RuntimeError(f"serialized results differ or benchmark failed:\n{result.stdout}\n{result.stderr}") + times = {} + for line in result.stdout.splitlines(): + if line.startswith("TIME "): + _, case, variant, ms = line.split() + times.setdefault((case, variant), []).append(float(ms)) + print(f"{args.rows:,} rows, {args.cores} workers, a-period {args.a_period}, median of {args.runs} interleaved runs; all serialized results equal.") + print("| Columns/shape | Materialized ms | Nested ms | Manual ms | Speedup |") + print("|---|---:|---:|---:|---:|") + for case in cases: + values = [times[(case, name)] for name in ("materialized", "nested")] + if any(len(v) != args.runs for v in values): + raise RuntimeError("incomplete timing output") + old, new = map(statistics.median, values) + manual = f"{statistics.median(times[(case, 'manual')]):.4f}" if (case, "manual") in times else "—" + print(f"| {case} | {old:.4f} | {new:.4f} | {manual} | {old / new:.2f}x |") + + +if __name__ == "__main__": + main() diff --git a/bench/sym_ordered_query.rfl b/bench/sym_ordered_query.rfl new file mode 100644 index 000000000..4e2d21fdf --- /dev/null +++ b/bench/sym_ordered_query.rfl @@ -0,0 +1,47 @@ +;; Regression benchmark for #738 / PR #743. Run a release build with: +;; ./rayforce -c 8 bench/sym_ordered_query.rfl +;; Timings are milliseconds; the first of five runs warms each query. +;; Vocabulary padding is outside the timed regions. Peak memory exceeds 1 GiB. + +(set Tiny (table [s] (list (as 'SYM ["zz" "mm" "" "aa" "mm"])))) +(println "tiny-small-vocabulary") +(map (fn [_] (println (timeit (select {from: Tiny where: (< s 'mm)})))) (til 5)) +(set pad (as 'SYM (as 'STR (+ 10000000 (til 1000000))))) +(set pad null) +(println "tiny-1m-vocabulary") +(map (fn [_] (println (timeit (select {from: Tiny where: (< s 'mm)})))) (til 5)) +(set vocabulary (as 'SYM (as 'STR (til 1000)))) +(set ids (% (til 20000000) 1000)) +(set T (table [a b n] (list (at vocabulary ids) (at vocabulary (% (+ ids 337) 1000)) ids))) +(println "column-column-20m-1m-vocabulary") +(map (fn [_] (println (timeit (select {v: (< a b) from: T})))) (til 5)) +(println "literal-projection-20m-1m-vocabulary") +(map (fn [_] (println (timeit (select {v: (< a "500") from: T})))) (til 5)) +(println "count-20m-1m-vocabulary") +(map (fn [_] (println (timeit (count (select {from: T where: (< a "500")}))))) (til 5)) +(println "group-20m-1m-vocabulary") +(map (fn [_] (println (timeit (select {v: (count a) from: T where: (< a "500") by: n})))) (til 5)) +(set T null) +(set ids null) +(set B (table [s] (list (as 'SYM (at ["zz" "mm" "" "aa" "mm"] (% (til 2000000) 5)))))) +(println "literal-2m-1m-vocabulary") +(map (fn [_] (println (timeit (select {v: (< s 'mm) from: B})))) (til 5)) +(set pad (as 'SYM (as 'STR (+ 11000000 (til 3000000))))) +(set pad null) +(println "tiny-4m-vocabulary") +(map (fn [_] (println (timeit (select {from: Tiny where: (< s 'mm)})))) (til 5)) +(set pad (as 'SYM (as 'STR (+ 14000000 (til 300000))))) +(set pad null) +(println "literal-2m-above-cutoff") +(map (fn [_] (println (timeit (select {v: (< s 'mm) from: B})))) (til 5)) +;; Warm metric keys and query syntax before measuring literal pollution. +(set LL "warmup") +(set literal_probe (fn [i] (do (set LL (format "unseen-743-%" i)) (count (select {from: Tiny where: (< s LL)}))))) +(set probes (til 10000)) +(literal_probe -1) +(.sys.mem) +(set before (at (.sys.mem) 'sym-count)) +(map literal_probe probes) +(println "runtime-symbol-growth-for-10000-string-literals") +(println (- (at (.sys.mem) 'sym-count) before)) +(exit 0) diff --git a/docs/docs/guides/memory.md b/docs/docs/guides/memory.md index b160e38cb..45cffe4df 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** (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`). +- **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=` — less a quarter of it, at least 3 GiB and at most half, left to the page cache; `-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). @@ -234,12 +234,14 @@ disk-full error. has committed, and when a new pool or large allocation would push that past the watermark — by default the smaller of total physical RAM and the container's cgroup memory limit (cgroup v2 `memory.max` / v1 `memory.limit_in_bytes`, -including limits set on a parent slice), or the `-m SIZE` flag when given — it +including limits set on a parent slice), less a quarter of it (at least 3 GiB, +at most half) left to the page cache, or the `-m SIZE` flag when given — it 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` -figure shows the footprint approaching total RAM — the point where spill begins. +figure shows the footprint approaching total RAM; spill begins below it, at the +watermark. ### Checking total RAM @@ -256,24 +258,28 @@ total-mem | 16777216000 ### Gauging headroom -To see how close a workload is to spilling to disk, compare the live object -footprint (`bytes-allocated + direct-bytes` from `(.sys.mem)`) against -`total-mem` from `(.sys.info)`: +To see how close a workload is to spilling to disk, compare the anonymous +footprint the heap has committed (`anon-committed` from `(.sys.mem)`: pools, +large blocks and the off-heap tables such as the symbol arenas) against the +spill threshold (`anon-watermark`): ```lisp -;; Live footprint as a percentage of physical RAM +;; Committed RAM as a percentage of the spill threshold (set stats (.sys.mem)) -(set info (.sys.info)) -(* 100.0 (/ (+ (get stats 'bytes-allocated) (get stats 'direct-bytes)) - (get info 'total-mem))) +(* 100.0 (/ (get stats 'anon-committed) (get stats 'anon-watermark))) ``` ```text 29.4 ``` -This shows 29.4% of physical RAM is in use — plenty of headroom before the heap -begins spilling to disk. +This shows the workload uses 29.4% of the RAM it may take before new memory +starts going to spill files. + +A spill file is mapped shared. An embedding process that `fork()`s and keeps +running rayforce code in the child shares the spilled blocks with the parent +instead of getting its own copy, so the child must not write them; run the +child through `exec` (as `.sys.exec` does) or start it before anything spills. ## 9. Practical Patterns diff --git a/docs/docs/guides/storage.md b/docs/docs/guides/storage.md index 03c4bad7d..bee02b6e5 100644 --- a/docs/docs/guides/storage.md +++ b/docs/docs/guides/storage.md @@ -92,7 +92,7 @@ ray_t* ray_col_load(const char* path); ray_t* ray_col_mmap(const char* path); ``` -The file format is compact: a header with type and length, followed by the raw element data. For string columns (`RAY_STR`), the pool data is written after the element array. +The file format is compact: a header with type and length, followed by the raw element data. For string columns (`RAY_STR`), the pool data is written after the element array, and each pooled string's descriptor stores its content hash so that mapping the column does not reread the pool. See [Storage: Columnar Files](../storage/index.md#columnar-files) for the layout. The difference between `ray_col_load` and `ray_col_mmap`: @@ -139,7 +139,7 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name); ``` -From Rayfall, load a partitioned table with `(.db.parted.get "db" 'trades)`; list a root's tables with `(.db.parted.tables "db")`. +From Rayfall, load a partitioned table with `(.db.parted.get "db" 'trades)`; list a root's tables with `(.db.parted.tables "db")`. On the same thread, retaining the earlier view lets the next mount reuse unchanged partitions. The cache holds at most 1024 partition tables per thread. GC, symbol-domain opens and the next mount release entries with no remaining column users; after dropping a view, `(.sys.gc)` releases its cached mappings and LIST payloads. Expected directory layout: diff --git a/docs/docs/language/control-flow.md b/docs/docs/language/control-flow.md index dbe7a7497..9602485fa 100644 --- a/docs/docs/language/control-flow.md +++ b/docs/docs/language/control-flow.md @@ -142,6 +142,8 @@ Recursive lambdas use `self` to refer to the enclosing function: 55 ``` +`self` is also a value: `(map self node)` recurses over a nested list. Inside a closure it is the closure itself, not the function that made it. + ## Error Handling: try / raise `raise` throws an error with an arbitrary value. `try` catches it and passes the value to a handler function: @@ -182,9 +184,11 @@ Nested lambdas capture visible lexical bindings when they are created: 12 ``` +Inside the closure its captures are locals: a `let` of `x` rebinds it for that call only, and a capture named like a builtin is the callee. See [Lambdas & the VM](syntax.md#lambdas-the-vm) for how closures compile. + ## Early Return: return -`return` exits the innermost enclosing compiled lambda early with the given value: +`return` exits the innermost enclosing lambda early with the given value, whether it runs as bytecode or on the tree-walking interpreter: ```lisp ‣ (set f (fn [x] (if (< x 0) (return -1) (+ x 1)))) diff --git a/docs/docs/language/functions.md b/docs/docs/language/functions.md index ced66c164..06390f49b 100644 --- a/docs/docs/language/functions.md +++ b/docs/docs/language/functions.md @@ -146,10 +146,15 @@ Functions that take other functions as arguments. Operations on vectors as collections. +Outside queries, `in` matches null to null. `not-in` inverts each membership result, preserving nested list/vector shapes. For numeric, temporal, SYM, and GUID membership evaluated during a query (including called functions), null input rows return `false` for both operations. STR string/character membership keeps its collection behavior and is not supported by the typed query-plan kernel. + +Query `concat` joins text row by row when every vector operand comes from a source column, including computed text columns and column arguments to inlined helpers. Scalar text operands also retain query string concatenation. A literal or bound collection operand keeps ordinary collection concatenation, in either argument order. Inside a user function `concat` keeps ordinary collection semantics unless an operand derives from the query's rows. Numeric collection concatenation evaluates over the whole column, or each group inside an aggregate. Non-text collection concatenation is binary. Scalars broadcast to the projected collection length; a one-row input column is still a column. Non-scalar output columns of different lengths are rejected before `take:`; a standalone collection projection may change the row count. When a `where:` selection is applied to a collection projection, its rows must align with the input rows. Counting a constant collection returns its length, independently of the source row count or group size. In a projection, a `concat` operand the planner has no node for (a reordered, indexed or cast column such as `(reverse s)`, `(at s 0)` or `(as 'STR x)`) is evaluated over the whole column, so select, update, `where:` and `by:` agree. Inside a helper body a quoted symbol is the symbol itself, as when the helper runs as bytecode, and a nested helper's free names are globals or source columns, never its caller's formals; a helper whose body uses only pure builtins is inlined; a closure never is, since its body reads its captures. Grouped outputs that the planner cannot serve natively keep the requested output order, and an output named like a group key keeps both columns, the key first. A helper that the planner cannot inline (several statements, a closure, recursion) runs as bytecode when called from a query fallback; `return`, lazy arguments and recursion depth behave as outside a query, and each value carries whether it derives from the query's rows, so `concat` keeps text semantics through `let` bindings, nested calls and helper results while a bound vector stays a collection. Inside such a helper a free name that is a source column is the row's cell during row-by-row evaluation and the whole column otherwise; an output alias never captures it, and other free names are globals. Such a helper can also be the `by:` key, evaluated over the rows `where:` keeps: a body built from pure builtins and pure helpers runs whole first, and again row by row when a conditional in it tested a vector or the whole-column run failed (a failed run is swallowed whole, its `raise` payload included); a body with an effect runs row by row from the start, so the effect happens once per row. The decision follows each callee wherever it is bound (a global helper, a parameter, a `let`, a capture, a lambda literal bound earlier in the body): `set`, `eval`, system and I/O builtins and a callee that is computed or unknown are effects; every other builtin and every helper built from them is pure, and a pure body keeps the whole-column semantics whichever way it is reached. A source column shadows a global of the same name inside a helper, on the planned path and in fallbacks alike. A text cell reduced from a column (`first`, `last`, `min`, `max`) is a cell of those rows: in a grouped select or update `(concat (first s) 'zz)` joins each group's cell with the literal, and an empty symbol cell is empty text, as for the cell itself; a cell reduced from a STR column makes the result STR, as the column does. + | Function | Type | Description | Example | |---|---|---|---| | `distinct` | unary | Remove duplicates | `(distinct [1 2 2 3])` → `[1 2 3]` | | `in` | binary | Membership test (element in vector) | `(in 2 [1 2 3])` → `true` | +| `not-in` | binary | Negated membership test | `(not-in 2 [1 3])` → `true` | | `except` | binary | Set difference | `(except [1 2 3] [2])` → `[1 3]` | | `union` | binary | Set union | `(union [1 2] [2 3])` → `[1 2 3]` | | `sect` | binary | Set intersection | `(sect [1 2 3] [2 3 4])` → `[2 3]` | @@ -497,7 +502,7 @@ spills exactly as it did before. | `fn` | variadic, special | Create lambda function | `(fn [x] (* x x))` | | `try` | binary, special | Error handling (expr handler-or-fallback) | `(try (/ 1 0) (fn [e] 0))` | | `raise` | unary | Throw an error | `(raise "bad input")` | -| `return` | variadic | Early return from compiled lambda (0 args → null) | `(return 42)` | +| `return` | variadic | Early return from the enclosing lambda (0 args → null) | `(return 42)` | | `quote` | variadic, special | Return argument unevaluated; a bare name becomes a literal symbol (`(quote x)` ≡ `'x`) | `(quote (+ 1 2))` → `(+ 1 2)` | | `resolve` | variadic, special | Resolve a symbol in current scope | `(resolve 'x)` | diff --git a/docs/docs/language/syntax.md b/docs/docs/language/syntax.md index 8832fde8c..4d4f5c8b9 100644 --- a/docs/docs/language/syntax.md +++ b/docs/docs/language/syntax.md @@ -387,6 +387,8 @@ User-defined functions are created with `fn`. Lambdas compile lazily to bytecode The VM supports trap frames for `try`/`raise` error handling, ensuring exceptions unwind cleanly through compiled code. +A lambda made inside another function is a closure over the locals visible where it was made. A `fn` literal inside a compiled body is compiled once, as a template, when the enclosing function compiles; every closure made from it shares that bytecode and captures only the enclosing locals its body mentions (all of them when the body uses `eval` or `resolve`), so making a closure costs no compilation and its recursion depth does not shrink with the bindings in scope. Its captures are locals of its own body: a `let` of a captured name rebinds it for that call, a capture (or a parameter or `let`) named like a builtin or a special form is the callee, a parameter shadows a capture of its name, `self` inside a closure is the closure itself, and a caller's local of the same name never stands in for a capture. A `let` that has not run leaves its name unbound, in the body and in a closure made after it, so a read of it finds the global of that name or raises a name error, as on the tree walker. Capture is lexical: a closure captures the bindings of the function it is written in, never a caller's locals. A closure body resolves the names it does not capture when it runs, so a global rebound after the closure was made is seen; a lambda made with nothing captured keeps the builtins it names as they were when it compiled. `eval` and `resolve` inside a compiled body see its locals and captures; their arguments run as part of the body. A lazy value is materialized when captured. A body nested deeper than 2048 levels (built at run time; parsed text stops at 1024) is not compiled and runs on the interpreter, whose own depth limit of 512 nested evaluations applies. A closure made by interpreted code (at the top level, by `eval`, or inside a special form the compiler hands to the tree walker) shares a template too, kept per literal and capture set in a per-thread table of 256 entries, so it is born compiled as well; one written inside a query stays on the tree walker and keeps the query's rule for quoted symbols. + ## Select & Update The `select` and `update` builtins bridge to the Rayforce DAG executor. They accept a dictionary of options: diff --git a/docs/docs/namespaces/db.md b/docs/docs/namespaces/db.md index 63f3d45b5..6fd39237d 100644 --- a/docs/docs/namespaces/db.md +++ b/docs/docs/namespaces/db.md @@ -56,6 +56,10 @@ Returns a `table` with every column memory-mapped — zero allocation per row. Signature: `(.db.parted.get "db_root" 'tbl_name)`. The table name **must** be a quoted symbol atom (e.g. `'trades`), not a string. +Calling it again on the same thread reuses unchanged partitions while the earlier view is still held. The loader checks the resolved generation directory and each schema/column file's device, inode, size, modification time and change time. New or changed partitions are loaded afresh; disappeared partitions are dropped. An earlier view keeps its rows when a writer publishes a replacement generation. + +Each thread caches at most 1024 partition tables, evicting the least recently mounted entries first. GC (including `(.sys.gc)`), symbol-domain opens and the next mount release cached tables whose columns have no remaining users. Dropping a view and running GC therefore releases its mappings and copied LIST payloads, even if the database directory was deleted. Thread heap teardown and runtime shutdown clear the cache. + Returns a single logical table assembled from every partition directory under `db_root/tbl_name/`. The result carries a virtual `MAPCOMMON` partition column derived from directory names, and every data column is a `RAY_PARTED_*` view over the segment files. Partition pruning kicks in automatically for `select` predicates on the virtual column. The directory names decide the key type and the partition order. `YYYY.MM.DD` names give a `date` column; digit-only names give an `int64` `part` column and are ordered by value, so `1`, `2`, `10` load as `[1 2 10]` with no zero-padding; any other digit/dot names give a `sym` `part` column in name order. A digit-only name that does not fit `int64` is rejected as `corrupt`, and the message names the directory. diff --git a/docs/docs/reference/all-functions.md b/docs/docs/reference/all-functions.md index 2c3e552ec..13accb781 100644 --- a/docs/docs/reference/all-functions.md +++ b/docs/docs/reference/all-functions.md @@ -247,10 +247,15 @@ Functions that take other functions as arguments for mapping, folding, and filte Operations on vectors and lists as collections — set operations, indexing, searching, and construction. +Outside queries, `in` matches null to null. `not-in` inverts each membership result, preserving nested list/vector shapes. For numeric, temporal, SYM, and GUID membership evaluated during a query (including called functions), null input rows return `false` for both operations. STR string/character membership keeps its collection behavior and is not supported by the typed query-plan kernel. + +Query `concat` joins text row by row when an operand comes from a source column, including computed text columns. Scalar text operands also retain query string concatenation. Literal and bound collections keep ordinary `concat` semantics, as do calls inside user functions whose operands do not derive from the query's rows. Numeric collection concatenation evaluates over the whole column, or each group inside an aggregate. Non-text collection concatenation is binary. Scalars broadcast to the projected collection length; a one-row input column is still a column. Non-scalar output columns of different lengths are rejected before `take:`; a standalone collection projection may change the row count. When a `where:` selection is applied to a collection projection, its rows must align with the input rows. A `concat` operand the planner has no node for (a reordered, indexed or cast column) is evaluated over the whole column in a projection, matching update, `where:` and `by:`. Inside a helper body a quoted symbol is the symbol itself and a nested helper's free names are globals or source columns, never its caller's formals; helpers built from pure builtins are inlined, never closures. Grouped outputs the planner cannot serve natively keep the requested output order; an output named like a group key keeps both columns, the key first. Helpers the planner cannot inline run as bytecode from a query fallback with row provenance tracked per value: `concat` keeps text semantics through `let`, nested calls and results, a bound vector stays a collection, and a free source-column name is the row's cell (or the whole column) rather than an output alias. Such a helper can also be the `by:` key, evaluated over the rows `where:` keeps: a body built from pure builtins and pure helpers runs whole first, and again row by row when a conditional in it tested a vector or the whole-column run failed (a failed run is swallowed whole, its `raise` payload included); a body with an effect (`set`, `eval`, system or I/O builtins, a computed or unknown callee) runs row by row from the start, so the effect happens once per row; callees are followed wherever they are bound, so a pure helper reached through a parameter, a `let` or a capture keeps the whole-column semantics. A source column shadows a global of the same name inside a helper, on the planned path and in fallbacks alike. A text cell reduced from a column (`first`, `last`, `min`, `max`) is a cell of those rows, so a grouped `(concat (first s) 'zz)` joins each group's cell with the literal, an empty cell is empty text, and a cell of a STR column keeps STR output, at every operand position (a query `concat` takes up to 255 operands). + | Function | Type | Flags | Description | Example | |---|---|---|---|---| | `distinct` | unary | — | Remove duplicates, preserving order | `(distinct [1 2 2 3])` → `[1 2 3]` | | `in` | binary | — | Membership test (is element in vector?) | `(in 2 [1 2 3])` → `true` | +| `not-in` | binary | — | Negated membership test | `(not-in 2 [1 3])` → `true` | | `except` | binary | — | Set difference (elements in A not in B) | `(except [1 2 3] [2])` → `[1 3]` | | `union` | binary | — | Set union (deduplicated) | `(union [1 2] [2 3])` → `[1 2 3]` | | `sect` | binary | — | Set intersection | `(sect [1 2 3] [2 3 4])` → `[2 3]` | diff --git a/docs/docs/storage/index.md b/docs/docs/storage/index.md index 4d41952e7..e24bcb0a2 100644 --- a/docs/docs/storage/index.md +++ b/docs/docs/storage/index.md @@ -17,9 +17,17 @@ The header carries a single-byte format generation. The current generation is `0 * Bytes 0-31: ray_t header (type, attrs, len, etc.) * Bytes 32-N: element data (len * elem_size bytes) * nulls use type-correct sentinels in this payload + * + * String columns (RAY_STR) continue: + * Bytes 32-N: 16-byte descriptors; a string longer than 12 bytes + * lives in the pool and its descriptor carries the + * pool offset and a 32-bit content hash + * Bytes N+1..: 32-byte pool header, then the pool bytes */ ``` +A string column file written by the current engine stores the content hash of every pooled string in its descriptor and marks the header to say so. Loading or mapping such a file checks descriptor bounds only: no string bytes are read and no descriptor page is written, so the mapping stays shared with the page cache. Files written before the hash was stored carry padding in that field; the loaders detect the missing mark, recompute the hashes and repair them in the private mapping, without touching the file. + ### C API | Function | Description | @@ -87,12 +95,15 @@ 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. +Publication keeps only the selected generation and removes the others +best-effort, so a replaced table holds one copy of itself on disk. A reader that +resolved a generation removed before it opened every file resolves the manifest +again and reads the selected one; a table already loaded stays readable. 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, and the column files it named are removed from the table +directory; nothing else there is touched. The `.write.lock` writer lock is local-filesystem coordination. Do not rely on it for NFS-backed shared writers. @@ -183,6 +194,10 @@ ray_t* trades = ray_read_parted("db", "trades"); !!! note "Rayfall builtin" Use `.db.parted.get` from Rayfall to load partitioned tables: `(.db.parted.get "db" 'trades)`. See the [Rayfall Storage Builtins](#rayfall-storage) section below. +Mounting the same root again on the same thread reuses unchanged partitions while the earlier view is held. Cache entries record the resolved generation directory and the device, inode, size, modification time and change time of the schema and every column file. A changed partition is loaded afresh; a disappeared partition is dropped. Symbol columns must match the root's current domain, so a missing `.sym` is still an error. + +The cache holds at most 1024 partition tables per thread. GC, symbol-domain opens and the next mount discard entries whose columns have no external references; heap abandonment, heap teardown and runtime shutdown clear the thread's entries. To release a dropped view's mappings and copied LIST values immediately, call `(.sys.gc)`. C callers can also use `ray_parted_cache_clear()` from `store/part.h` to clear their thread's cache. + !!! warning "`update` over a partitioned table materializes in memory" `update` on a partitioned table flattens the whole table into memory first — the parted/`MAPCOMMON` columns cannot be mutated in place — so the result is an ordinary in-memory table. It is **not** written back to the store: re-reading the root returns the original values, and the returned table loses its parted / memory-mapped identity. diff --git a/fuzz/README.md b/fuzz/README.md index 844d343cb..a607177ce 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -15,6 +15,7 @@ runtime). | `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 | +| `fuzz_select_merge` | nested `select` vs materialized `select` | two/three-layer queries, nullable numeric/SYM/STR columns, serialized results and errors | The journal log is a sequence of IPC frames verbatim, so the `de` corpus also hardens journal replay's decode step. @@ -37,15 +38,32 @@ input has no such construct. make fuzz-parse # 60s (default) run of one target make fuzz-parse FUZZ_RUNTIME=0 # run until a crash / Ctrl-C make fuzz-smoke # short pass over the fast targets (PR CI gate) +make fuzz-select_merge FUZZ_RUNTIME=600 # structured nested-query differential check ``` +`select_merge` generates two/three-layer queries and compares them with the +same queries wrapped in `do` to force inner materialization. It checks serialized +results and error codes, allowing relative/absolute tolerance `1e-12` only for +F64 aggregate values (fusion changes addition order). Row expressions, schema, +order and null metadata still compare exactly. +The generator also covers extreme F64 values and tables of 8,191, 8,192, +16,385 and 131,073 rows. Run `RAY_FUZZ_CORES=4 make fuzz-select_merge` to +exercise parallel execution; the default remains serial for deterministic +coverage. `RAY_FUZZ_CORES` is read only by this fuzz driver. The generator +includes products of two independent F64 columns, squares, nested products, +and scalar/grouped reductions. PR CI runs this target for one minute each in +serial and four-worker modes, each with a fresh corpus and the committed seeds. +This leaves time for mutations instead of spending the whole short run replaying +the growing cache. Its nightly campaign uses four workers and a cached corpus. + `fuzz-smoke` covers `parse`, `numparse`, and `de` (the fast, stateless -targets); `eval`, `csv`, and `journal` run in the nightly `fuzz-long` job +targets); `eval`, `csv`, `journal`, and `select_merge` run in the nightly `fuzz-long` job (`.github/workflows/nightly.yml`), 15 minutes each over a cached corpus. -Grown corpora live in `fuzz/corpus//` (gitignored); committed starter -inputs live in `fuzz/seeds//`. Regenerate the working corpora from the -test suite before a session: +Grown corpora live in `fuzz/corpus//` (gitignored); override the root with +`FUZZ_CORPUS_ROOT=/path/to/corpus` to use a separate working corpus. Committed +starter inputs in `fuzz/seeds//` are included with either root. +Regenerate the working corpora from the test suite before a session: ```sh scripts/fuzz-seed-parse.sh # parse/eval inputs from test/rfl diff --git a/fuzz/fuzz_select_merge.c b/fuzz/fuzz_select_merge.c new file mode 100644 index 000000000..c2f700d8e --- /dev/null +++ b/fuzz/fuzz_select_merge.c @@ -0,0 +1,176 @@ +/* Structured differential fuzzer for nested select composition (#752). + * Compare two/three literal layers against do-wrapped materialization, + * including rejected shapes. The oracle checks wire bytes or error codes. + */ +#include "common.h" +#include "lang/eval.h" +#include "store/serde.h" +#include "vec/vec.h" +#include + +static void drop(ray_t* x) { + if (x && RAY_IS_ERR(x)) ray_error_free(x); + else if (x) ray_release(x); +} + +static unsigned byte(const uint8_t* data, size_t size, size_t* at) { + return size ? data[(*at)++ % size] : 0; +} + +/* Fusing a floating sum can change its addition order. Permit roundoff only + * in the generated aggregate `total`; row expressions, schema and wire attrs + * still compare exactly, including nulls created by extreme F64 arithmetic. */ +static bool aggregate_roundoff(ray_t* a, ray_t* b) { + if (a->type != RAY_TABLE || b->type != RAY_TABLE || + ray_table_ncols(a) != ray_table_ncols(b) || ray_table_nrows(a) != ray_table_nrows(b) || + (a->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SORTED)) != + (b->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SORTED))) return false; + int64_t total = ray_sym_intern("total", 5); + for (int64_t i = 0; i < ray_table_ncols(a); i++) { + int64_t name = ray_table_col_name(a, i); + if (name != ray_table_col_name(b, i)) return false; + ray_t* x = ray_table_get_col_idx(a, i), *y = ray_table_get_col_idx(b, i); + ray_t* sx = ray_ser(x), *sy = ray_ser(y); + bool same = sx && sy && !RAY_IS_ERR(sx) && !RAY_IS_ERR(sy) && sx->len == sy->len && + !memcmp(ray_data(sx), ray_data(sy), sx->len); + drop(sx); drop(sy); + if (same) continue; + if (name != total || x->type != RAY_F64 || y->type != RAY_F64 || x->len != y->len || + (x->attrs & RAY_ATTR_HAS_NULLS) != (y->attrs & RAY_ATTR_HAS_NULLS)) return false; + const double* xv = ray_data(x), *yv = ray_data(y); + for (int64_t row = 0; row < x->len; row++) { + bool xn = ray_vec_is_null(x, row), yn = ray_vec_is_null(y, row); + if (xn != yn) return false; + if (xn) continue; + if (!isfinite(xv[row]) || !isfinite(yv[row]) || + fabs(xv[row] - yv[row]) > 1e-12 * fmax(1.0, fmax(fabs(xv[row]), fabs(yv[row])))) return false; + } + } + return true; +} + +static void query(char* out, const unsigned* choices, bool barrier) { + static const char* const filters[] = { + "", "where:(== a 1)", "where:(> p 3)", "where:(== s 'beta)", + "where:(== text \"b\")", "where:(and (== a 1) (== b 1))", + "where:(== a 9)", "where:(== p 0Nf)" + }; + static const char* const projections[] = { + "", "a:a b:b k:k p:p s:s text:text", "a:a b:b k:k p:p s:s text:text q:(* p 2)", + "p:p q:(- p (avg p))", "p:p q:(sums p)", "p:p q:(reverse p)", + "p:p bad:missing", "p:p q:(missing p)", "take:2", "desc:p" + }; + static const char* const outputs[] = { + "", "p:p s:s text:text", "total:(sum p)", "by:k total:(sum p)", + "total:(sum q)", "q:q", "take:3", "p:p desc:p take:2", + "a:(+ a 1) r:a", "total:(count s)" + }; + static const char* const computed[] = { + "(* p 2)", "(* p 1.7)", "(+ p 1.3)", "(- p 0.7)", + "(* p r)", "(* p p)", "(* (* p 2) r)", "(* p a)", + "(* (* a 2) 1.0)", "(* (* p 1e300) 1e-300)" + }; + static const char* const reductions[] = { + "total:(sum q)", "total:(avg q)", "total:(min q)", + "total:(max q)", "by:k total:(sum q)", "by:k total:(avg q)" + }; + char projection[256]; + snprintf(projection, sizeof(projection), "a:a b:b k:k p:p s:s text:text q:%s", computed[(choices[1] / 10) % 10]); + snprintf(out, 4096, "(select {from:T %s %s})", filters[choices[0] % 8], + choices[1] % 10 == 2 ? projection : projections[choices[1] % 10]); + for (unsigned layer = 0; layer < 1 + choices[2] % 2; layer++) { + char prev[4096]; + strcpy(prev, out); + unsigned output = choices[4 + layer * 2]; + /* Each layer adds at most 200 bytes; the generated depth is <= 3. */ + snprintf(out, 4096, "(select {from:%s%.3000s%s %s %s})", barrier ? "(do " : "", prev, + barrier ? ")" : "", filters[choices[3 + layer * 2] % 8], + output % 10 == 4 ? reductions[(output / 10) % 6] : outputs[output % 10]); + } +} + +int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (!ray_fuzz_ready && getenv("RAY_FUZZ_CORES")) { + setenv("RAYFORCE_CORES", getenv("RAY_FUZZ_CORES"), 1); + ray_runtime_create(0, NULL); + ray_fuzz_ready = 1; + } else ray_fuzz_init(); + size_t at = 0; + unsigned choices[7]; + for (int i = 0; i < 7; i++) choices[i] = byte(data, size, &at); + unsigned rows = byte(data, size, &at) % 33; + char src[8192]; size_t pos = 0; + pos += snprintf(src + pos, sizeof(src) - pos, "(set T (table [a b k p s text r] (list "); + for (int col = 0; col < 7; col++) { + bool floating = col == 3 || col == 6; + if (!rows) { + static const char* const empty[] = {"[0]", "[0]", "[0]", "[0.0]", "[alpha]", "[\"a\"]", "[0.0]"}; + pos += snprintf(src + pos, sizeof(src) - pos, "(take %s 0) ", empty[col]); + continue; + } + src[pos++] = '['; + for (unsigned row = 0; row < rows; row++) { + unsigned v = byte(data, size, &at); + if (col == 4) { + const char* sym[] = {"'", "alpha", "beta"}; + pos += snprintf(src + pos, sizeof(src) - pos, "%s ", sym[v % 3]); + } else if (col == 5) { + const char* str[] = {"\"\"", "\"a\"", "\"b\""}; + pos += snprintf(src + pos, sizeof(src) - pos, "%s ", str[v % 3]); + } else if (v % 7 == 0 && !(floating && v >= 250 && v <= 253)) { + pos += snprintf(src + pos, sizeof(src) - pos, "%s ", floating ? "0Nf" : "0N"); + } else if (floating) { + const char* edge = v == 250 ? "1.7976931348623157e308" : + v == 251 ? "-1.7976931348623157e308" : + v == 252 ? "1e300" : v == 253 ? "-1e300" : NULL; + if (edge) pos += snprintf(src + pos, sizeof(src) - pos, "%s ", edge); + else pos += snprintf(src + pos, sizeof(src) - pos, "%u.%u ", v % 17, (v / 17) % 10); + } else { + if (v == 250) pos += snprintf(src + pos, sizeof(src) - pos, "4611686018427387904 "); + else pos += snprintf(src + pos, sizeof(src) - pos, "%u ", v % 3); + } + } + src[pos++] = ']'; src[pos++] = ' '; + } + snprintf(src + pos, sizeof(src) - pos, ")))" ); + ray_t* t = ray_eval_str(src); + if (!t || RAY_IS_ERR(t)) abort(); + drop(t); + /* Occasionally cross the merge threshold, morsel boundaries and the + * parallel dispatch threshold. A short input still controls all values. */ + unsigned scale = choices[2] >> 4; + int large_rows = scale == 12 ? 8191 : scale == 13 ? 8192 : + scale == 14 ? 16385 : scale == 15 ? 131073 : 0; + if (rows && large_rows) { + char grow[64]; + snprintf(grow, sizeof(grow), "(set T (take T %d))", large_rows); + t = ray_eval_str(grow); + if (!t || RAY_IS_ERR(t)) abort(); + drop(t); + } + char optimized[4096], reference[4096]; + query(optimized, choices, false); query(reference, choices, true); + ray_t* got = ray_eval_str(optimized), *want = ray_eval_str(reference); + bool equal = got && want && RAY_IS_ERR(got) == RAY_IS_ERR(want); + if (equal && RAY_IS_ERR(got)) { + equal = got->slen == want->slen && !memcmp(got->sdata, want->sdata, got->slen); + } else if (equal) { + ray_t* a = ray_ser(got), *b = ray_ser(want); + equal = a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b) && + a->len == b->len && !memcmp(ray_data(a), ray_data(b), a->len); + if (!equal) equal = aggregate_roundoff(got, want); + if (!equal && a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b)) { + fprintf(stderr, "Serialized lengths: %lld / %lld\n", (long long)a->len, (long long)b->len); + for (int64_t i = 0; i < a->len && i < b->len; i++) + if (((uint8_t*)ray_data(a))[i] != ((uint8_t*)ray_data(b))[i]) + fprintf(stderr, "Byte %lld: %u / %u\n", (long long)i, ((uint8_t*)ray_data(a))[i], ((uint8_t*)ray_data(b))[i]); + } + drop(a); drop(b); + } + if (!equal) { + fprintf(stderr, "Fixture: %s\nExpanded rows: %d\nOptimized: %s\nReference: %s\n", src, large_rows, optimized, reference); + abort(); + } + drop(got); drop(want); + return 0; +} diff --git a/fuzz/seeds/select_merge/aggregate_roundoff b/fuzz/seeds/select_merge/aggregate_roundoff new file mode 100644 index 000000000..ed1ca2a03 Binary files /dev/null and b/fuzz/seeds/select_merge/aggregate_roundoff differ diff --git a/fuzz/seeds/select_merge/column_product_avg b/fuzz/seeds/select_merge/column_product_avg new file mode 100644 index 000000000..514cdd564 Binary files /dev/null and b/fuzz/seeds/select_merge/column_product_avg differ diff --git a/fuzz/seeds/select_merge/column_product_group b/fuzz/seeds/select_merge/column_product_group new file mode 100644 index 000000000..19477b99d Binary files /dev/null and b/fuzz/seeds/select_merge/column_product_group differ diff --git a/fuzz/seeds/select_merge/column_product_sum b/fuzz/seeds/select_merge/column_product_sum new file mode 100644 index 000000000..aa123de8a Binary files /dev/null and b/fuzz/seeds/select_merge/column_product_sum differ diff --git a/fuzz/seeds/select_merge/column_square_sum b/fuzz/seeds/select_merge/column_square_sum new file mode 100644 index 000000000..b9f11d261 Binary files /dev/null and b/fuzz/seeds/select_merge/column_square_sum differ diff --git a/fuzz/seeds/select_merge/composed_parallel_cancellation b/fuzz/seeds/select_merge/composed_parallel_cancellation new file mode 100644 index 000000000..eb93a7951 Binary files /dev/null and b/fuzz/seeds/select_merge/composed_parallel_cancellation differ diff --git a/fuzz/seeds/select_merge/derived_group b/fuzz/seeds/select_merge/derived_group new file mode 100644 index 000000000..364de8ce2 Binary files /dev/null and b/fuzz/seeds/select_merge/derived_group differ diff --git a/fuzz/seeds/select_merge/empty_inner b/fuzz/seeds/select_merge/empty_inner new file mode 100644 index 000000000..e9cb7a4dc --- /dev/null +++ b/fuzz/seeds/select_merge/empty_inner @@ -0,0 +1 @@ +Ž�Šš \ No newline at end of file diff --git a/fuzz/seeds/select_merge/mixed_integer_product b/fuzz/seeds/select_merge/mixed_integer_product new file mode 100644 index 000000000..6343e73a0 Binary files /dev/null and b/fuzz/seeds/select_merge/mixed_integer_product differ diff --git a/fuzz/seeds/select_merge/morsel_group b/fuzz/seeds/select_merge/morsel_group new file mode 100644 index 000000000..14d535f87 Binary files /dev/null and b/fuzz/seeds/select_merge/morsel_group differ diff --git a/fuzz/seeds/select_merge/nested_column_product b/fuzz/seeds/select_merge/nested_column_product new file mode 100644 index 000000000..6043ea5aa Binary files /dev/null and b/fuzz/seeds/select_merge/nested_column_product differ diff --git a/fuzz/seeds/select_merge/nullable_offset b/fuzz/seeds/select_merge/nullable_offset new file mode 100644 index 000000000..34c54980c Binary files /dev/null and b/fuzz/seeds/select_merge/nullable_offset differ diff --git a/fuzz/seeds/select_merge/parallel_offset_overflow b/fuzz/seeds/select_merge/parallel_offset_overflow new file mode 100644 index 000000000..d302b062d Binary files /dev/null and b/fuzz/seeds/select_merge/parallel_offset_overflow differ diff --git a/fuzz/seeds/select_merge/parallel_scale_overflow b/fuzz/seeds/select_merge/parallel_scale_overflow new file mode 100644 index 000000000..575031ea5 Binary files /dev/null and b/fuzz/seeds/select_merge/parallel_scale_overflow differ diff --git a/fuzz/seeds/select_merge/parallel_three_layers b/fuzz/seeds/select_merge/parallel_three_layers new file mode 100644 index 000000000..846a51b5a Binary files /dev/null and b/fuzz/seeds/select_merge/parallel_three_layers differ diff --git a/fuzz/seeds/select_merge/parallel_two_filters b/fuzz/seeds/select_merge/parallel_two_filters new file mode 100644 index 000000000..08f5ba94c Binary files /dev/null and b/fuzz/seeds/select_merge/parallel_two_filters differ diff --git a/fuzz/seeds/select_merge/scaled_overflow_chain b/fuzz/seeds/select_merge/scaled_overflow_chain new file mode 100644 index 000000000..e230b049d Binary files /dev/null and b/fuzz/seeds/select_merge/scaled_overflow_chain differ diff --git a/fuzz/seeds/select_merge/text_take b/fuzz/seeds/select_merge/text_take new file mode 100644 index 000000000..24bd48ab9 --- /dev/null +++ b/fuzz/seeds/select_merge/text_take @@ -0,0 +1 @@ +ØÔÔÔtake \ No newline at end of file diff --git a/fuzz/seeds/select_merge/text_take_chain b/fuzz/seeds/select_merge/text_take_chain new file mode 100644 index 000000000..7f342db1e --- /dev/null +++ b/fuzz/seeds/select_merge/text_take_chain @@ -0,0 +1 @@ +ZPÀL \ No newline at end of file diff --git a/fuzz/seeds/select_merge/three_layers b/fuzz/seeds/select_merge/three_layers new file mode 100644 index 000000000..75e83c901 Binary files /dev/null and b/fuzz/seeds/select_merge/three_layers differ diff --git a/fuzz/seeds/select_merge/threshold_at b/fuzz/seeds/select_merge/threshold_at new file mode 100644 index 000000000..e09910832 Binary files /dev/null and b/fuzz/seeds/select_merge/threshold_at differ diff --git a/fuzz/seeds/select_merge/threshold_below b/fuzz/seeds/select_merge/threshold_below new file mode 100644 index 000000000..3c639113a Binary files /dev/null and b/fuzz/seeds/select_merge/threshold_below differ diff --git a/fuzz/seeds/select_merge/unmerged_parallel_cancellation b/fuzz/seeds/select_merge/unmerged_parallel_cancellation new file mode 100644 index 000000000..6a410295f Binary files /dev/null and b/fuzz/seeds/select_merge/unmerged_parallel_cancellation differ diff --git a/src/app/main.c b/src/app/main.c index 8ff50a9c2..43d4dd5a4 100644 --- a/src/app/main.c +++ b/src/app/main.c @@ -241,7 +241,8 @@ int main(int argc, char** argv) { " -l BASE enable journal logging (BASE.log + BASE.qdb)\n" " -L BASE enable journal logging with fsync per write\n" " -m, --mem SIZE RAM budget (e.g. 4G, 512M); allocations past it\n" - " spill to disk instead of OOM (default: physical RAM)\n" + " spill to disk instead of OOM (default: RAM or the\n" + " cgroup limit, less a quarter: 3G to half of it)\n" " -h, --help show this message\n" " -- pass following args to the app; read\n" " them in Rayfall via (.sys.args)\n" diff --git a/src/app/repl.c b/src/app/repl.c index b5cd32d86..9729d7186 100644 --- a/src/app/repl.c +++ b/src/app/repl.c @@ -874,23 +874,25 @@ static void eval_and_print(ray_term_t* term, const char* input, ray_qlog_end(&qc, input, strlen(input), result); + /* An interrupted statement still ends here: whatever it built before the + * ^C is free now and goes back at the boundary below like any other. */ if (ray_term_interrupted()) { ray_term_clear_interrupt(); ray_eval_clear_interrupt(); fprintf(stdout, "\n^C\n"); fflush(stdout); if (result && !RAY_IS_ERR(result)) ray_release(result); - return; - } - - if (result) { - repl_print_result(stdout, result, use_color); - fflush(stdout); - if (!RAY_IS_ERR(result)) ray_release(result); + } else { + if (result) { + repl_print_result(stdout, result, use_color); + fflush(stdout); + if (!RAY_IS_ERR(result)) ray_release(result); + } + if (profiling) profile_print(use_color); } - if (profiling) profile_print(use_color); ray_heap_gc(); + ray_heap_relieve(); /* Statement boundary. Check BEFORE stamping: the clock still holds the * end of the previous statement, so what we measure is the gap between * statements — the time the process actually sat idle. Stamping first @@ -1530,5 +1532,9 @@ int ray_repl_run_file(const char* path) { * exists to avoid. */ ray_heap_note_activity(); ray_heap_gc(); + /* The script's own temporaries — a load, say, before it hands over to a + * server's poll loop — go back here under memory pressure, as after a + * REPL statement. */ + ray_heap_relieve(); return rc; } diff --git a/src/core/epoll.c b/src/core/epoll.c index 73e57e68d..b7c7142fe 100644 --- a/src/core/epoll.c +++ b/src/core/epoll.c @@ -347,9 +347,12 @@ int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) /* A fired timer is work, and on a timer-driven server it is the * only work there is: without this stamp the decay sees an idle * process mid-workload, and — having disarmed itself — never - * looks again. */ - if (ray_timers_fire_expired((ray_timers_t*)poll->timers) > 0) + * looks again. It is also a unit of work ending, so the same + * boundary relief as after an IPC request applies. */ + if (ray_timers_fire_expired((ray_timers_t*)poll->timers) > 0) { ray_heap_note_activity(); + ray_heap_relieve(); + } } /* After the events of this wakeup, not before: a request handled * above has just re-stamped the activity clock, so a busy loop diff --git a/src/core/ipc.c b/src/core/ipc.c index 279a8be54..43041a970 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -360,6 +360,7 @@ static bool hook_vm_bind(hook_vm_t* hv) { static void hook_vm_unbind(hook_vm_t* hv) { if (!hv->owned) return; if (hv->owned->raise_val) ray_release(hv->owned->raise_val); + if (hv->owned->return_val) ray_release(hv->owned->return_val); if (hv->owned->trace) ray_release(hv->owned->trace); __VM = NULL; ray_free_raw(hv->owned); @@ -1171,6 +1172,7 @@ static ray_t* ipc_read_payload(ray_poll_t* poll, ray_selector_t* sel) * one between two requests. Stamping on frame arrival instead would * make the measured gap the request's own duration. */ ray_heap_note_activity(); + ray_heap_relieve(); return NULL; } diff --git a/src/core/kqueue.c b/src/core/kqueue.c index 11c0d3ac4..c3f2eab98 100644 --- a/src/core/kqueue.c +++ b/src/core/kqueue.c @@ -346,9 +346,12 @@ int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) /* A fired timer is work, and on a timer-driven server it is the * only work there is: without this stamp the decay sees an idle * process mid-workload, and — having disarmed itself — never - * looks again. */ - if (ray_timers_fire_expired((ray_timers_t*)poll->timers) > 0) + * looks again. It is also a unit of work ending, so the same + * boundary relief as after an IPC request applies. */ + if (ray_timers_fire_expired((ray_timers_t*)poll->timers) > 0) { ray_heap_note_activity(); + ray_heap_relieve(); + } } /* After the events of this wakeup, not before: a request handled * above has just re-stamped the activity clock, so a busy loop diff --git a/src/core/platform.c b/src/core/platform.c index e6cd89d42..8606b9ec9 100644 --- a/src/core/platform.c +++ b/src/core/platform.c @@ -31,20 +31,41 @@ /* ========================================================================== * Linux / macOS (POSIX) * ========================================================================== */ +#include + +/* Bytes asked for ahead so far (ray_vm_advise_willneed), process-wide: + * the pool's trace summary, and tests of the readers that must ask before + * they read a mapped column they sample. */ +static _Atomic(uint64_t) vm_willneed_bytes; +uint64_t ray_vm_willneed_bytes(void) { + return atomic_load_explicit(&vm_willneed_bytes, memory_order_relaxed); +} + #if defined(RAY_OS_LINUX) || defined(RAY_OS_MACOS) #include #include #include #include +#include #include #include #include #include #include +#include /* the lazily read page size and read-ahead step */ #if defined(RAY_OS_MACOS) #include /* sysctlbyname — hw.physicalcpu */ #endif +#if defined(RAY_OS_LINUX) +#include /* /sys/block — the read-ahead caps */ +#include /* EINTR — ray_os_cgroup_stat_flush */ +#include +#include /* getrusage: ray_io_counters */ +#if !defined(RUSAGE_THREAD) +#define RUSAGE_THREAD 1 +#endif +#endif #include "mem/sys.h" /* -------------------------------------------------------------------------- @@ -113,6 +134,137 @@ void ray_vm_advise_seq(void* ptr, size_t size) { if (ptr) madvise(ptr, size, MADV_SEQUENTIAL); } +/* Read once, from whichever thread asks first: the threads that race on it + * all store the same value, relaxed. */ +static size_t vm_page_size(void) { + static _Atomic(size_t) cached = 0; + size_t pg = atomic_load_explicit(&cached, memory_order_relaxed); + if (pg == 0) { + long ps = sysconf(_SC_PAGESIZE); + pg = (ps > 0) ? (size_t)ps : 4096; + atomic_store_explicit(&cached, pg, memory_order_relaxed); + } + return pg; +} + +#if defined(RAY_OS_LINUX) +/* A block device's queue attribute in KiB, -1 when it cannot be read. */ +static long vm_queue_kb(const char* dev, const char* attr) { + char path[320], buf[32]; + snprintf(path, sizeof(path), "/sys/block/%s/queue/%s", dev, attr); + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + ssize_t n = read(fd, buf, sizeof(buf) - 1); + close(fd); + if (n <= 0) return -1; + buf[n] = 0; + return strtol(buf, NULL, 10); +} +#endif + +/* Bytes one WILLNEED is asked for at a time. Linux reads at most + * max(read_ahead_kb, max_sectors_kb) of the file's device per call, and a + * longer step would leave the rest of it unread: so the smallest such cap + * of the block devices, within [32 KiB, 256 KiB]; 128 KiB, the kernel's + * default read-ahead, when none can be read or elsewhere. */ +static size_t vm_willneed_step(void) { +#if defined(RAY_OS_LINUX) + static _Atomic(size_t) cached = 0; + size_t step = atomic_load_explicit(&cached, memory_order_relaxed); + if (step) return step; + DIR* d = opendir("/sys/block"); + if (d) { + struct dirent* e; + while ((e = readdir(d))) { + if (e->d_name[0] == '.') continue; + long ra = vm_queue_kb(e->d_name, "read_ahead_kb"); + long mx = vm_queue_kb(e->d_name, "max_sectors_kb"); + long cap = ra > mx ? ra : mx; + if (cap > 0 && (!step || ((size_t)cap << 10) < step)) step = (size_t)cap << 10; + } + closedir(d); + } + if (!step) step = (size_t)128 << 10; + if (step < ((size_t)32 << 10)) step = (size_t)32 << 10; + if (step > ((size_t)256 << 10)) step = (size_t)256 << 10; + step &= ~(vm_page_size() - 1); + if (step < vm_page_size()) step = vm_page_size(); /* pages above 32 KiB */ + atomic_store_explicit(&cached, step, memory_order_relaxed); + return step; +#else + return (size_t)128 << 10; +#endif +} + +void ray_vm_advise_willneed(void* ptr, size_t size) { + if (!ptr || !size) return; + atomic_fetch_add_explicit(&vm_willneed_bytes, size, memory_order_relaxed); + /* madvise wants a page-aligned start. One WILLNEED reads at most what + * the device allows per call (vm_willneed_step), so a large range is + * requested step by step: each call only queues its reads, so the steps + * are all in flight together. */ + const size_t chunk = vm_willneed_step(); + uintptr_t a = (uintptr_t)ptr & ~(uintptr_t)(vm_page_size() - 1); + uintptr_t end = (uintptr_t)ptr + size; + for (; a < end; a += chunk) + madvise((void*)a, end - a < chunk ? end - a : chunk, MADV_WILLNEED); +} + +void ray_file_writeback_start(int fd, int64_t off, int64_t len) { +#if defined(__linux__) + if (fd >= 0 && off >= 0 && len > 0) + (void)sync_file_range(fd, (off64_t)off, (off64_t)len, SYNC_FILE_RANGE_WRITE); +#else + (void)fd; (void)off; (void)len; +#endif +} + +void ray_sleep_ms(int ms) { + struct timespec ts = { ms / 1000, (long)(ms % 1000) * 1000000L }; + nanosleep(&ts, NULL); +} + +bool ray_vm_resident(const void* ptr, size_t size) { + if (!ptr || !size) return true; + size_t pg = vm_page_size(); + uintptr_t a = (uintptr_t)ptr & ~(uintptr_t)(pg - 1); + size_t pages = ((uintptr_t)ptr + size - a + pg - 1) / pg; + size_t samples = pages < 16 ? pages : 16; + for (size_t i = 0; i < samples; i++) { + size_t at = samples > 1 ? (pages - 1) * i / (samples - 1) : 0; +#if defined(RAY_OS_MACOS) + char v = 0; +#else + unsigned char v = 0; +#endif + if (mincore((void*)(a + at * pg), pg, &v) != 0 || !(v & 1)) return false; + } + return true; +} + +size_t ray_vm_resident_end(const void* ptr, size_t size) { + size_t pg = vm_page_size(); +#if defined(RAY_OS_MACOS) + char vec[4096]; +#else + unsigned char vec[4096]; +#endif + uintptr_t a = (uintptr_t)ptr & ~(uintptr_t)(pg - 1); + size_t pages = ((uintptr_t)ptr + size - a + pg - 1) / pg; + for (size_t top = pages; top > 0; ) { + size_t k = top < sizeof(vec) ? top : sizeof(vec); + size_t at = top - k; + if (mincore((void*)(a + at * pg), k * pg, vec) != 0) return size; + for (size_t i = k; i-- > 0; ) + if (vec[i] & 1) { + size_t end = (at + i + 1) * pg - ((uintptr_t)ptr - a); + return end < size ? end : size; + } + top = at; + } + return 0; +} + void ray_vm_release(void* ptr, size_t size) { if (!ptr) return; #if defined(RAY_OS_MACOS) @@ -138,11 +290,7 @@ void ray_vm_release_block(void* blk, size_t bsize, bool hugepage) { * read back as zero and the next GC freelist walk crashed on a * NULL link (issue #240). Rounding inward to page-aligned bounds * makes the kernel's own rounding a no-op on every platform. */ - static size_t pg = 0; - if (pg == 0) { - long ps = sysconf(_SC_PAGESIZE); - pg = (ps > 0) ? (size_t)ps : 4096; - } + size_t pg = vm_page_size(); uintptr_t s = ((uintptr_t)blk + 32 + (pg - 1)) & ~(uintptr_t)(pg - 1); uintptr_t e = ((uintptr_t)blk + bsize) & ~(uintptr_t)(pg - 1); if (e > s) ray_vm_release((void*)s, e - s); @@ -399,8 +547,10 @@ static int64_t cgroup_read_limit(const char* path) { 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) { +/* Smallest limit found in `root`/`cgpath`/`file` and every ancestor; the + * directory that sets it into at[512] when at is not NULL. */ +static int64_t cgroup_walk_limit(const char* root, const char* cgpath, const char* file, + char* at) { char dir[512]; if (snprintf(dir, sizeof(dir), "%s%s", root, cgpath) >= (int)sizeof(dir)) return 0; size_t rootlen = strlen(root); @@ -409,7 +559,10 @@ static int64_t cgroup_walk_limit(const char* root, const char* cgpath, const cha 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 (v > 0 && (limit == 0 || v < limit)) { + limit = v; + if (at) memcpy(at, dir, sizeof(dir)); + } if (strlen(dir) <= rootlen) break; /* mount root checked */ char* slash = strrchr(dir, '/'); if (!slash || (size_t)(slash - dir) < rootlen) break; @@ -429,7 +582,9 @@ static bool cgroup_has_memory(const char* ctrls) { return false; } -int64_t ray_os_cgroup_mem_limit(void) { +/* The smallest limit, and into dir[n] (when not NULL) the directory of the + * cgroup that sets it — at most 511 bytes, as the walk's own. */ +static int64_t cgroup_mem_limit(char* dir, size_t n) { FILE* f = fopen("/proc/self/cgroup", "r"); if (!f) return 0; int64_t limit = 0; @@ -444,20 +599,47 @@ int64_t ray_os_cgroup_mem_limit(void) { char* cgpath = c2 + 1; cgpath[strcspn(cgpath, "\n")] = 0; if (strcmp(cgpath, "/") == 0) cgpath[0] = 0; + char at[512]; int64_t v; if (*ctrls == 0) - v = cgroup_walk_limit("/sys/fs/cgroup", cgpath, "memory.max"); + v = cgroup_walk_limit("/sys/fs/cgroup", cgpath, "memory.max", at); else if (cgroup_has_memory(ctrls)) - v = cgroup_walk_limit("/sys/fs/cgroup/memory", cgpath, "memory.limit_in_bytes"); + v = cgroup_walk_limit("/sys/fs/cgroup/memory", cgpath, "memory.limit_in_bytes", at); else continue; - if (v > 0 && (limit == 0 || v < limit)) limit = v; + if (v > 0 && (limit == 0 || v < limit)) { + limit = v; + if (dir && snprintf(dir, n, "%s", at) >= (int)n) dir[0] = 0; + } } fclose(f); return limit; } + +int64_t ray_os_cgroup_mem_limit(void) { + return cgroup_mem_limit(NULL, 0); +} + +bool ray_os_cgroup_mem_dir(char* buf, size_t n) { + if (n) buf[0] = 0; + return n && cgroup_mem_limit(buf, n) > 0 && buf[0]; +} + +bool ray_os_cgroup_stat_flush(const char* cg) { + char path[600], buf[256]; + if (!cg || !*cg) return false; + snprintf(path, sizeof(path), "%s/memory.stat", cg); + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return false; + ssize_t r; + do r = read(fd, buf, sizeof(buf)); while (r < 0 && errno == EINTR); + close(fd); + return r > 0; +} #else int64_t ray_os_cgroup_mem_limit(void) { return 0; } +bool ray_os_cgroup_mem_dir(char* buf, size_t n) { if (n) buf[0] = 0; return false; } +bool ray_os_cgroup_stat_flush(const char* cg) { (void)cg; return false; } #endif static uint64_t cache_llc_probe(void) { @@ -647,6 +829,24 @@ void ray_vm_advise_seq(void* ptr, size_t size) { PrefetchVirtualMemory(GetCurrentProcess(), 1, &entry, 0); } +void ray_vm_advise_willneed(void* ptr, size_t size) { + if (!ptr || !size) return; + atomic_fetch_add_explicit(&vm_willneed_bytes, size, memory_order_relaxed); + WIN32_MEMORY_RANGE_ENTRY entry; + entry.VirtualAddress = ptr; + entry.NumberOfBytes = size; + PrefetchVirtualMemory(GetCurrentProcess(), 1, &entry, 0); +} + +void ray_file_writeback_start(int fd, int64_t off, int64_t len) { (void)fd; (void)off; (void)len; } + +void ray_sleep_ms(int ms) { Sleep((DWORD)ms); } + +/* No cheap residency query here: report "not resident" so a read-ahead is + * still requested (PrefetchVirtualMemory skips resident pages itself). */ +bool ray_vm_resident(const void* ptr, size_t size) { (void)ptr; (void)size; return false; } +size_t ray_vm_resident_end(const void* ptr, size_t size) { (void)ptr; return size; } + void ray_vm_release(void* ptr, size_t size) { if (!ptr) return; /* DiscardVirtualMemory (Win8.1+) or fallback to decommit+recommit */ @@ -731,6 +931,8 @@ uint32_t ray_physical_core_count(void) { } int64_t ray_os_cgroup_mem_limit(void) { return 0; } +bool ray_os_cgroup_mem_dir(char* buf, size_t n) { if (n) buf[0] = 0; return false; } +bool ray_os_cgroup_stat_flush(const char* cg) { (void)cg; return false; } /* Sum of every level-3 cache instance reported by the processor topology * (each SYSTEM_LOGICAL_PROCESSOR_INFORMATION cache record is one instance). @@ -814,6 +1016,8 @@ void* ray_vm_alloc(size_t size) { * Round up to a 64KB WASM page. */ size_t aligned = (size + 65535u) & ~(size_t)65535u; p = aligned_alloc(65536, aligned); + /* zero-filled, as a fresh mapping is (ray_sys_alloc's contract) */ + if (p) memset(p, 0, aligned); } if (p) ray_sys_track_add((int64_t)size); return p; @@ -862,6 +1066,13 @@ void* ray_vm_map_fd_ro(int fd, size_t size) { /* madvise hints are advisory and have no analog on WASM — no-ops. */ void ray_vm_advise_seq(void* ptr, size_t size) { (void)ptr; (void)size; } +void ray_vm_advise_willneed(void* ptr, size_t size) { + if (ptr && size) atomic_fetch_add_explicit(&vm_willneed_bytes, size, memory_order_relaxed); +} +void ray_file_writeback_start(int fd, int64_t off, int64_t len) { (void)fd; (void)off; (void)len; } +void ray_sleep_ms(int ms) { (void)ms; } +bool ray_vm_resident(const void* ptr, size_t size) { (void)ptr; (void)size; return true; } +size_t ray_vm_resident_end(const void* ptr, size_t size) { (void)ptr; return size; } void ray_vm_release(void* ptr, size_t size) { (void)ptr; (void)size; } void ray_vm_release_block(void* blk, size_t bsize, bool hugepage) { @@ -894,6 +1105,8 @@ 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; } +bool ray_os_cgroup_mem_dir(char* buf, size_t n) { if (n) buf[0] = 0; return false; } +bool ray_os_cgroup_stat_flush(const char* cg) { (void)cg; return false; } static uint64_t cache_llc_probe(void) { return 0; } /* Semaphore — counter-only. Single-threaded so wait never blocks (the @@ -930,3 +1143,27 @@ uint64_t ray_cache_llc_bytes(void) { #endif return cache_llc_probe(); } + +/* ---- I/O counters for the traces ----------------------------------------- */ +void ray_io_counters(bool thread, ray_io_counters_t* out) { + *out = (ray_io_counters_t){0}; +#if defined(RAY_OS_LINUX) + struct rusage ru; + if (getrusage(thread ? RUSAGE_THREAD : RUSAGE_SELF, &ru) == 0) out->majflt = ru.ru_majflt; + FILE* f = fopen(thread ? "/proc/thread-self/io" : "/proc/self/io", "r"); + if (f) { + char line[128]; + while (fgets(line, sizeof(line), f)) { + long long v; + if (sscanf(line, "read_bytes: %lld", &v) == 1) out->rd = v; + else if (sscanf(line, "write_bytes: %lld", &v) == 1) out->wr = v; + else if (sscanf(line, "cancelled_write_bytes: %lld", &v) == 1) out->cwr = v; + else if (sscanf(line, "syscr: %lld", &v) == 1) out->syscr = v; + else if (sscanf(line, "syscw: %lld", &v) == 1) out->syscw = v; + } + fclose(f); + } +#else + (void)thread; +#endif +} diff --git a/src/core/platform.h b/src/core/platform.h index e89292829..0640524f0 100644 --- a/src/core/platform.h +++ b/src/core/platform.h @@ -156,6 +156,33 @@ void* ray_vm_map_file(const char* path, size_t* out_size); void* ray_vm_map_fd_ro(int fd, size_t size); void ray_vm_unmap_file(void* ptr, size_t size); void ray_vm_advise_seq(void* ptr, size_t size); +/* Ask the kernel to start reading [ptr, ptr+size) of a file mapping now, + * asynchronously, so a later access finds it resident. Best effort. */ +void ray_vm_advise_willneed(void* ptr, size_t size); +/* Bytes asked for so far by ray_vm_advise_willneed, process-wide: the + * pool's trace summary, and tests of readers that must ask before they + * read a mapped column they sample. */ +uint64_t ray_vm_willneed_bytes(void); +/* Start writing back bytes [off, off+len) of open file `fd` without waiting + * (Linux sync_file_range WRITE; a no-op elsewhere): a later fsync then + * finds them on disk. */ +void ray_file_writeback_start(int fd, int64_t off, int64_t len); +/* The I/O counters the converters' traces read: bytes read from and + * written to storage, written bytes whose writeback was cancelled, read and + * write calls, and major faults; of the process, or of the calling thread + * (thread true). Linux reads /proc/self/io (/proc/thread-self/io) and + * getrusage; every field reads zero elsewhere, or where they cannot be read. */ +typedef struct { int64_t rd, wr, cwr, syscr, syscw, majflt; } ray_io_counters_t; +void ray_io_counters(bool thread, ray_io_counters_t* out); +void ray_sleep_ms(int ms); +/* True when a sample of the pages of [ptr, ptr+size) is resident: a cheap + * check (a handful of page probes) that a read-ahead would find nothing to + * read. Where residency cannot be queried it reports false. */ +bool ray_vm_resident(const void* ptr, size_t size); +/* How far into [ptr, ptr+size) pages are in RAM: to the end of the last + * resident page (mincore), 0 if none; size where residency cannot be + * queried. */ +size_t ray_vm_resident_end(const void* ptr, size_t size); void ray_vm_release(void* ptr, size_t size); /* Release physical pages for a free block. When hugepage is true, only the * 2MB-aligned interior is released so a partial MADV_DONTNEED does not @@ -185,6 +212,15 @@ uint64_t ray_cache_llc_bytes(void); * the process's cgroup and its ancestors. 0 when none is set, or on * platforms without cgroups. */ int64_t ray_os_cgroup_mem_limit(void); +/* The directory of the cgroup that sets that limit, into buf[n]; false when + * no limit is set, or on platforms without cgroups. */ +bool ray_os_cgroup_mem_dir(char* buf, size_t n); +/* Read the memory.stat of cgroup `cg` (a directory from + * ray_os_cgroup_mem_dir), for what reading does: the kernel updates a + * cgroup's statistics lazily and flushes them when the file is read. With + * open/read, no stdio. false when there is no such file (and on platforms + * without cgroups). */ +bool ray_os_cgroup_stat_flush(const char* cg); #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 4c3fd9403..2d4653cae 100644 --- a/src/core/pool.c +++ b/src/core/pool.c @@ -188,6 +188,170 @@ static bool pool_steal(ray_pool_t* pool, uint32_t w, uint32_t* c0, uint32_t* c1) * 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. */ +/* -------------------------------------------------------------------------- + * Scan read-ahead + * + * A mapped column is read on first touch, one page fault at a time per + * worker (plus the kernel's own read-ahead), so a scan over storage with a + * high per-request latency runs at a couple of requests in flight per + * worker whatever the storage could serve in parallel. A query registers + * the mapped columns it reads (ray_pool_scan_set); while one of its + * dispatches runs, each thread keeps the next `scan_bytes` of every + * registered column, from the row it is at, requested (MADV_WILLNEED, + * window by window), topping the request up once half of it is used. A + * window stops where the thread's own run of rows does: the rows past it + * are another thread's to ask for, and asking twice costs on fast storage. + * + * The row comes from the ticket for a dispatch over exactly the registered + * rows (ticket base+i holds rows [i*grain, (i+1)*grain)), and from the task + * itself (ray_pool_scan_at) for dispatch_n tasks that walk a row range, or + * (ray_pool_scan_col_at) for tasks that know the one column they read. + * Rows of zone chunks the query's filter rules out (scan->gate) are never + * requested. RAY_SCAN_PREFETCH sets the window in KiB (default 4096, 0 + * turns read-ahead off); it is read when the pool is created. + * -------------------------------------------------------------------------- */ +static RAY_TLS const ray_pool_scan_t* t_scan; + +/* Dispatch generations, process-wide: a pool made again after + * ray_pool_destroy (which zeroes it) must not meet per-thread state left + * by a dispatch of the old one under the same number. */ +static _Atomic(uint64_t) pool_scan_gens; + +/* Where residency cannot be queried (ray_vm_resident is always false) the + * probe below would never see a column read: there every column counts as + * read, as before the probe. */ +#if defined(RAY_OS_WINDOWS) +#define POOL_SCAN_PROBED 0 +#else +#define POOL_SCAN_PROBED 1 +#endif + +/* What this thread has requested for the current dispatch: rows + * [lo[c], hi[c]) of column c. Stale (gen differs) at a new dispatch. + * + * A dispatch reads only some of the registered columns (a filter its + * predicate's, a counting pass its keys). Requesting the others too + * interleaves streams the dispatch does not need, which a spinning disk pays + * for in seeks. So a column is requested only once the dispatch is seen to + * read it: its page in the middle of the rows this thread went through since + * its previous call is in the page cache (`active`). A column the dispatch + * does not read, or reads only sparsely, stays out of the page cache there. */ +typedef struct { + uint64_t gen; + uint32_t active; /* columns this dispatch reads, by bit */ + int64_t last; /* row of the previous call in this dispatch; -1 none */ + uint8_t miss[RAY_POOL_SCAN_MAX]; /* probes that found column c not read */ + int64_t lo[RAY_POOL_SCAN_MAX]; + int64_t hi[RAY_POOL_SCAN_MAX]; +} pool_scan_tls_t; +static RAY_TLS pool_scan_tls_t t_pf; + +const ray_pool_scan_t* ray_pool_scan_set(const ray_pool_scan_t* scan) { + const ray_pool_scan_t* prev = t_scan; + t_scan = scan; + return prev; +} + +const ray_pool_scan_t* ray_pool_scan_get(void) { return t_scan; } + +/* Requested so far (all pools), for the RAY_POOL_TRACE summary. */ +static _Atomic(uint64_t) pool_scan_req_bytes, pool_scan_req_ranges; + +static void pool_scan_willneed(const ray_pool_scan_t* s, uint32_t c, int64_t a, int64_t b) { + size_t bytes = (size_t)(b - a) * s->esz[c]; + void* p = (void*)(s->base[c] + (size_t)a * s->esz[c]); + /* Rows an earlier dispatch of the query requested are in the page cache + * already (or on their way in): asking again only walks those pages. */ + if (ray_vm_resident(p, bytes)) return; + ray_vm_advise_willneed(p, bytes); + atomic_fetch_add_explicit(&pool_scan_req_bytes, bytes, memory_order_relaxed); + atomic_fetch_add_explicit(&pool_scan_req_ranges, 1, memory_order_relaxed); +} + +/* Request rows [a, b) of column c, skipping the chunks the gate rules out. */ +static void pool_scan_request(const ray_pool_scan_t* s, uint32_t c, int64_t a, int64_t b) { + if (!s->gate) { pool_scan_willneed(s, c, a, b); return; } + uint8_t lg = s->gate_log2; + int64_t run = -1; + for (int64_t ch = a >> lg; (ch << lg) < b; ch++) { + int64_t c0 = ch << lg; + if (c0 < a) c0 = a; + if ((s->gate[ch >> 6] >> (ch & 63)) & 1) { + if (run < 0) run = c0; + } else if (run >= 0) { + pool_scan_willneed(s, c, run, c0); + run = -1; + } + } + if (run >= 0) pool_scan_willneed(s, c, run, b); +} + +/* This thread is about to read row r and goes on towards `end`. `reads`: + * the columns the caller says it reads, by bit (0 when it does not say, and + * the probe finds them). */ +static void pool_scan_ahead(ray_pool_t* pool, int64_t r, int64_t end, uint32_t reads) { + const ray_pool_scan_t* s = pool->scan; + if (end > s->rows) end = s->rows; + if (r < 0 || r >= end) return; + pool_scan_tls_t* t = &t_pf; + if (t->gen != pool->scan_gen) { + t->gen = pool->scan_gen; + t->active = POOL_SCAN_PROBED ? 0 : UINT32_MAX; + t->last = -1; + memset(t->miss, 0, sizeof(t->miss)); + for (uint32_t c = 0; c < s->n; c++) t->lo[c] = t->hi[c] = r; + } + /* Rows the filter's zones rule out are skipped by the pass: nothing to + * learn or request there, and the run starts again past them. */ + if (s->gate) { + int64_t ch = r >> s->gate_log2; + if (!((s->gate[ch >> 6] >> (ch & 63)) & 1)) { t->last = -1; return; } + } + /* Which columns were read over the rows behind this one; the rows a + * column had resident when registered tell nothing (scan->warm). A + * column found unread a few times is one this pass reads sparsely or + * not at all: this thread stops probing it for the rest of the + * dispatch. A caller that names its columns needs no probe, from its + * first call. */ + if (reads) { + t->active |= reads; + } else if (t->last >= 0 && t->last != r) { + int64_t mid = (t->last < r ? t->last + r : r + t->last) / 2; + for (uint32_t c = 0; c < s->n && c < 32; c++) { + if ((t->active >> c & 1) || t->miss[c] >= 4 || mid < s->warm[c]) continue; + if (ray_vm_resident(s->base[c] + (size_t)mid * s->esz[c], 1)) + t->active |= UINT32_C(1) << c; + else + t->miss[c]++; + } + } + t->last = r; + for (uint32_t c = 0; c < s->n; c++) { + if (c >= 32 || !(t->active >> c & 1)) continue; + /* A jump outside what was requested starts a new run. */ + if (r < t->lo[c] || r > t->hi[c]) t->lo[c] = t->hi[c] = r; + int64_t win = (int64_t)(pool->scan_bytes / s->esz[c]); + if (win < 1) win = 1; + if (t->hi[c] - r > win / 2) continue; + int64_t want = end - r > win ? r + win : end; + if (want <= t->hi[c]) continue; + pool_scan_request(s, c, t->hi[c], want); + t->hi[c] = want; + } +} + +/* Ticket tk is next, and this thread's run of tickets goes on to `until` + * (to the tail of own range `s` when given): past it are other threads' + * rows, which they ask for themselves. */ +static inline void pool_scan_ticket(ray_pool_t* pool, uint32_t tk, uint32_t until, + ray_pool_slot_t* s) { + if (!pool->scan_auto) return; + if (s) until = RANGE_TAIL(atomic_load_explicit(&s->range, memory_order_relaxed)); + uint32_t base = (uint32_t)pool->scan_base; + pool_scan_ahead(pool, (int64_t)(uint32_t)(tk - base) * pool->scan_grain, + (int64_t)(uint32_t)(until - base) * pool->scan_grain, 0); +} + 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 */ @@ -195,6 +359,7 @@ static void pool_run_steal(ray_pool_t* pool, uint32_t w, bool prog) { uint32_t tk; while (pool_range_take(s, &tk)) { if ((uint32_t)(tk - ch0) < (uint32_t)(ch1 - ch0)) s->stolen++; else s->own++; + pool_scan_ticket(pool, tk, 0, s); pool_exec(pool, w, tk); if (prog) ray_progress_pump(); } @@ -222,6 +387,7 @@ static void pool_run_steal(ray_pool_t* pool, uint32_t w, bool prog) { } s->stolen += c1 - c0; for (; c0 != c1; c0++) { + pool_scan_ticket(pool, c0, c1, NULL); pool_exec(pool, w, c0); if (prog) ray_progress_pump(); } @@ -276,6 +442,11 @@ static void pool_trace_dump(const ray_pool_t* pool) { (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); + fprintf(stderr, "pool: scan read-ahead %llu KiB per column, requested %llu MiB in %llu ranges, %llu MiB asked for in all\n", + (unsigned long long)(pool->scan_bytes >> 10), + (unsigned long long)(atomic_load_explicit(&pool_scan_req_bytes, memory_order_relaxed) >> 20), + (unsigned long long)atomic_load_explicit(&pool_scan_req_ranges, memory_order_relaxed), + (unsigned long long)(ray_vm_willneed_bytes() >> 20)); 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, @@ -298,6 +469,9 @@ static void worker_loop(void* arg) { * pairs with its acquire: the heap is fully initialised when seen). */ atomic_store_explicit(&pool->worker_heaps[wctx.worker_id - 1], ray_tl_heap, memory_order_release); + /* started: no getenv of this thread's start runs after this (the + * creator waits for it, ray_pool_create_impl) */ + ray_sem_signal(&pool->started); for (;;) { ray_sem_wait(&pool->work_ready); @@ -387,6 +561,9 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, { const char* e = getenv("RAY_POOL_STEAL"); pool->steal = (e && *e) ? (strtol(e, NULL, 10) != 0) : 1; + e = getenv("RAY_SCAN_PREFETCH"); + long kib = (e && *e) ? strtol(e, NULL, 10) : 4096; + pool->scan_bytes = kib > 0 ? (size_t)(kib > (1L << 20) ? (1L << 20) : kib) << 10 : 0; e = getenv("RAY_POOL_TRACE"); pool->trace = (e && *e && strtol(e, NULL, 10) != 0); } @@ -452,12 +629,19 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, ray_sys_free(pool->tasks); return err; } + err = ray_sem_init(&pool->started, 0); + if (err != RAY_OK) { + ray_sem_destroy(&pool->work_ready); + ray_sys_free(pool->slots_raw); + ray_sys_free(pool->tasks); + return err; + } /* Spawn worker threads */ if (n_workers > 0) { pool->threads = (ray_thread_t*)ray_sys_alloc(n_workers * sizeof(ray_thread_t)); if (!pool->threads) { - ray_sem_destroy(&pool->work_ready); + ray_sem_destroy(&pool->work_ready); ray_sem_destroy(&pool->started); ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); return RAY_ERR_OOM; @@ -465,7 +649,7 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, pool->worker_heaps = ray_sys_alloc(n_workers * sizeof(*pool->worker_heaps)); if (!pool->worker_heaps) { ray_sys_free(pool->threads); - ray_sem_destroy(&pool->work_ready); + ray_sem_destroy(&pool->work_ready); ray_sem_destroy(&pool->started); ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); return RAY_ERR_OOM; @@ -486,7 +670,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_sem_destroy(&pool->work_ready); ray_sem_destroy(&pool->started); ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); return RAY_ERR_OOM; @@ -506,12 +690,17 @@ 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_sem_destroy(&pool->work_ready); ray_sem_destroy(&pool->started); ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); return err; } } + /* Every worker through its start before the pool is handed out: + * ray_heap_init reads the environment (getenv), and a caller's + * setenv right after this returns could otherwise free the + * environment array under one of those reads. */ + for (uint32_t i = 0; i < n_workers; i++) ray_sem_wait(&pool->started); } return RAY_OK; @@ -543,12 +732,30 @@ void ray_pool_free(ray_pool_t* pool) { ray_sys_free(pool->worker_heaps); ray_sys_free(pool->threads); - ray_sem_destroy(&pool->work_ready); + ray_sem_destroy(&pool->work_ready); ray_sem_destroy(&pool->started); ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); memset(pool, 0, sizeof(*pool)); } +/* Arm read-ahead for the window about to be published: the caller's + * registration, requested per ticket when the window covers exactly its + * rows (`total` elements, `grain` per ticket from `base`). */ +static void pool_scan_begin(ray_pool_t* pool, int64_t total, uint64_t base, int64_t grain) { + const ray_pool_scan_t* sc = (pool->scan_bytes && t_scan && t_scan->n) ? t_scan : NULL; + pool->scan_gen = atomic_fetch_add_explicit(&pool_scan_gens, 1, memory_order_relaxed) + 1; + pool->scan = sc; + pool->scan_auto = sc && pool->steal && grain > 0 && sc->rows == total; + pool->scan_base = base; + pool->scan_grain = grain; +} + +/* The window has drained: nothing reads the registration any more. */ +static inline void pool_scan_end(ray_pool_t* pool) { + pool->scan = NULL; + pool->scan_auto = false; +} + /* -------------------------------------------------------------------------- * ray_pool_dispatch * -------------------------------------------------------------------------- */ @@ -617,6 +824,8 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, * steal mode the range words are the publication (release each) and * the cursors only record the high-water mark. */ atomic_store_explicit(&pool->pending, n_tasks, memory_order_relaxed); + /* Scan read-ahead for this window, published with the ranges. */ + pool_scan_begin(pool, total_elems, base, grain); if (pool->steal) { atomic_store_explicit(&pool->task_claim, base + n_tasks, memory_order_relaxed); atomic_store_explicit(&pool->task_limit, base + n_tasks, memory_order_relaxed); @@ -681,6 +890,8 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, } } + pool_scan_end(pool); + /* All tasks done, workers heading to sem_wait (no GC in loop). * Safe for main to modify worker heaps between dispatches. */ atomic_store_explicit(&ray_parallel_flag, 0, memory_order_release); @@ -712,6 +923,7 @@ 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); + pool_scan_begin(pool, -1, base, 0); /* tasks are not row ranges */ if (pool->steal) { atomic_store_explicit(&pool->task_claim, base + n_tasks, memory_order_relaxed); atomic_store_explicit(&pool->task_limit, base + n_tasks, memory_order_relaxed); @@ -769,6 +981,7 @@ static void dispatch_n_round(ray_pool_t* pool, ray_pool_fn fn, void* ctx, } } + pool_scan_end(pool); atomic_store_explicit(&ray_parallel_flag, 0, memory_order_release); atomic_thread_fence(memory_order_seq_cst); ray_rc_sync = false; @@ -869,6 +1082,72 @@ ray_pool_t* ray_pool_get(void) { } } +/* Read-ahead from inside a task of the singleton's open dispatch (the only + * pool the executor's kernels run on). Outside a dispatch `scan` is NULL. */ +void ray_pool_scan_at(int64_t nrows, int64_t r, int64_t end) { + ray_pool_t* pool = &g_pool; + const ray_pool_scan_t* s = pool->scan; + if (!s || s->rows != nrows) return; + pool_scan_ahead(pool, r, end, 0); +} + +/* The bit of the `nrows`-row column at `col` in registration `s`; 0 when + * it is not registered there. */ +static uint32_t pool_scan_col_bit(const ray_pool_scan_t* s, const void* col, int64_t nrows) { + if (!s || s->rows != nrows) return 0; + for (uint32_t c = 0; c < s->n && c < 32; c++) + if (s->base[c] == (const uint8_t*)col) return UINT32_C(1) << c; + return 0; +} + +void ray_pool_scan_col_at(const void* col, int64_t nrows, int64_t r, int64_t end) { + ray_pool_t* pool = &g_pool; + uint32_t bit = pool_scan_col_bit(pool->scan, col, nrows); + if (bit) pool_scan_ahead(pool, r, end, bit); +} + +bool ray_pool_scan_holds(const void* col, int64_t nrows) { + return g_pool.scan_bytes && pool_scan_col_bit(t_scan, col, nrows); +} + +bool ray_pool_scan_on(void) { + if (atomic_load_explicit(&g_pool_init_state, memory_order_acquire) == 2) + return g_pool.scan_bytes != 0; + /* no pool yet: the switch as the pool will read it */ + const char* e = getenv("RAY_SCAN_PREFETCH"); + return !(e && *e && strtol(e, NULL, 10) <= 0); +} + +/* Asking for a range costs the caller about a microsecond a page: the + * kernel allocates and queues each page before the call returns. A large + * range asked for outside a dispatch is split over the pool's threads. */ +typedef struct { + uintptr_t a, end; + size_t step; +} pool_want_ctx_t; + +static void pool_want_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + const pool_want_ctx_t* c = raw; + for (int64_t i = start; i < end; i++) { + uintptr_t a = c->a + (uintptr_t)i * c->step; + ray_vm_advise_willneed((void*)a, c->end - a < c->step ? c->end - a : c->step); + } +} + +void ray_pool_want(const void* p, size_t bytes) { + ray_pool_t* pool = &g_pool; + size_t step = (size_t)1 << 20; + if (bytes / step > RAY_POOL_INIT_TASKS) step = (bytes + RAY_POOL_INIT_TASKS - 1) / RAY_POOL_INIT_TASKS; + uint32_t n = (uint32_t)((bytes + step - 1) / step); + if (n < 4 || !ray_pool_par_dispatch_ok(pool, n, 4)) { + ray_vm_advise_willneed((void*)p, bytes); + return; + } + pool_want_ctx_t c = { (uintptr_t)p, (uintptr_t)p + bytes, step }; + ray_pool_dispatch_n(pool, pool_want_fn, &c, n); +} + /* -------------------------------------------------------------------------- * Public API wrappers (declared in rayforce.h) * -------------------------------------------------------------------------- */ @@ -941,3 +1220,17 @@ void ray_cancel_reset(void) { if (atomic_load_explicit(&g_pool_init_state, memory_order_acquire) == 2) atomic_store_explicit(&g_pool.cancelled, 0, memory_order_release); } + +/* The worker heaps of the live pool, for heap maintenance run from the + * dispatcher's thread between dispatches (see pool_reclaim_worker_heaps for + * why only these). Like ray_cancel it touches the pool only when it is + * already live, so maintenance never starts one. */ +void ray_pool_each_worker_heap(void (*fn)(ray_heap_t* h, void* ctx), void* ctx) { + if (atomic_load_explicit(&g_pool_init_state, memory_order_acquire) != 2) + return; + for (uint32_t i = 0; i < g_pool.n_workers; i++) { + ray_heap_t* h = (ray_heap_t*)atomic_load_explicit(&g_pool.worker_heaps[i], + memory_order_acquire); + if (h) fn(h, ctx); + } +} diff --git a/src/core/pool.h b/src/core/pool.h index c914ff0fd..7c11e3511 100644 --- a/src/core/pool.h +++ b/src/core/pool.h @@ -66,6 +66,26 @@ typedef struct { uint64_t steals; /* successful steal operations */ } ray_pool_slot_t; +/* Scan read-ahead: the mapped columns a query reads, registered for the + * dispatches it runs (ray_pool_scan_set). While a dispatch runs, each + * worker keeps the rows just ahead of the ones it reads requested from + * storage (see pool.c). `gate`, when set, is the zone-index verdict of the + * query's filter: bit c clear means no row of [c << gate_log2, + * (c + 1) << gate_log2) can pass it, so nothing there is requested. + * warm[c]: the rows at the start of column c that were resident when it was + * registered (the kernel reads them ahead with the header when the column + * is opened); their residency says nothing of what a pass reads. */ +#define RAY_POOL_SCAN_MAX 32 +typedef struct { + const uint8_t* base[RAY_POOL_SCAN_MAX]; + uint32_t esz[RAY_POOL_SCAN_MAX]; + int64_t warm[RAY_POOL_SCAN_MAX]; + uint32_t n; + int64_t rows; + const uint64_t* gate; + uint8_t gate_log2; +} ray_pool_scan_t; + /* Thread pool */ struct ray_pool { ray_thread_t* threads; /* worker thread handles [n_workers] */ @@ -113,12 +133,25 @@ struct ray_pool { uint32_t steal; uint32_t trace; /* RAY_POOL_TRACE: histogram at destroy */ ray_pool_slot_t* slots; /* [n_workers+1], 64-byte aligned */ + /* Scan read-ahead of the open dispatch: the registered columns (NULL + * when none), set by the dispatcher before the window is published and + * cleared once it has drained. With scan_auto the dispatch covers + * exactly their rows, ticket base+i holding rows [i*grain, (i+1)*grain), + * and the pool requests ahead itself; otherwise only tasks that report + * their position (ray_pool_scan_at) do. */ + const ray_pool_scan_t* scan; + bool scan_auto; + uint64_t scan_base; /* first ticket of the window */ + int64_t scan_grain; /* rows per ticket */ + uint64_t scan_gen; /* dispatches so far: resets per-thread state */ + size_t scan_bytes; /* bytes kept requested per column and worker */ 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 */ + ray_sem_t started; /* a signal from each worker once its heap is up */ /* Query cancellation — set by ray_cancel(), checked per-morsel */ _Atomic(uint32_t) cancelled; @@ -175,6 +208,39 @@ void ray_pool_free(ray_pool_t* pool); /* Dispatch fn over [0, total_elems) partitioned into morsel-sized tasks. * Blocks until all tasks complete. Main thread participates as worker 0. */ +/* Register the columns the calling thread's next dispatches scan (NULL + * clears); returns the previous registration so nested executions can + * restore it. The registration must outlive those dispatches. */ +const ray_pool_scan_t* ray_pool_scan_set(const ray_pool_scan_t* scan); +const ray_pool_scan_t* ray_pool_scan_get(void); + +/* Called by a task about to read rows [r, end) of an `nrows`-row input: + * when that input is the registered one, keep the rows just ahead of r + * requested. For dispatch_n tasks that walk row ranges of their own; a + * dispatch over exactly the registered rows needs no call (the pool + * requests per ticket). Cheap when nothing is registered. */ +void ray_pool_scan_at(int64_t nrows, int64_t r, int64_t end); + +/* ray_pool_scan_at for a task that reads one registered column, its data + * at `col` (a gather): only that column is requested, from the first call + * on. No-op when `col` is not registered for the open dispatch. */ +void ray_pool_scan_col_at(const void* col, int64_t nrows, int64_t r, int64_t end); + +/* True when read-ahead is on and the calling thread's registration holds + * the `nrows`-row column with data at `col`: a dispatch it makes next can + * have its tasks report positions in that column (ray_pool_scan_col_at). */ +bool ray_pool_scan_holds(const void* col, int64_t nrows); + +/* Read-ahead is on (RAY_SCAN_PREFETCH unset, or a positive number of KiB). + * For requests made outside the per-dispatch windows, which honour the same + * switch. */ +bool ray_pool_scan_on(void); + +/* Ask for [p, p+bytes) of a file mapping (ray_vm_advise_willneed), with the + * work of a large range split over the pool's threads when called outside + * a dispatch. */ +void ray_pool_want(const void* p, size_t bytes); + void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, int64_t total_elems); /* Dispatch exactly n_tasks tasks, each with range [i, i+1). @@ -191,4 +257,12 @@ ray_err_t ray_pool_init(uint32_t n_workers); ray_err_t ray_pool_init_total(uint32_t total_workers); void ray_pool_destroy(void); +/* Call fn on the heap of every worker of the live singleton pool; nothing + * when no pool is running (this never starts one). For heap maintenance on + * the dispatcher's thread with ray_parallel_flag clear: a parked worker + * allocates and frees nothing until the next dispatch, so its heap may be + * worked on from there — which holds for no other thread's heap. */ +struct ray_heap; +void ray_pool_each_worker_heap(void (*fn)(struct ray_heap* h, void* ctx), void* ctx); + #endif /* RAY_POOL_H */ diff --git a/src/core/runtime.c b/src/core/runtime.c index 0c7d23c04..a67d69b93 100644 --- a/src/core/runtime.c +++ b/src/core/runtime.c @@ -26,6 +26,7 @@ #include "mem/heap.h" #include "mem/sys.h" #include "table/sym.h" +#include "store/part.h" #include #include #include @@ -286,7 +287,10 @@ static ray_runtime_t* runtime_create_impl(const char* sym_path, 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; + if (cg > 0 && cg < rt->ram_limit) { + rt->ram_limit = cg; + ray_os_cgroup_mem_dir(rt->mem_cg, sizeof(rt->mem_cg)); + } } /* __RUNTIME must be visible before ray_sym_load so the sym-load size @@ -387,6 +391,10 @@ int64_t ray_sys_ram_limit(void) { return __RUNTIME ? __RUNTIME->ram_limit : 0; } +void ray_sys_mem_flush(void) { + if (__RUNTIME && __RUNTIME->mem_cg[0]) (void)ray_os_cgroup_stat_flush(__RUNTIME->mem_cg); +} + int8_t ray_obj_type(ray_t* v) { return v ? v->type : 0; } @@ -430,6 +438,7 @@ void ray_runtime_destroy(ray_runtime_t* rt) { for (int32_t i = 0; i < rt->n_vms; i++) { ray_vm_t* vm = rt->vms[i]; if (vm->raise_val) ray_release(vm->raise_val); + if (vm->return_val) ray_release(vm->return_val); if (vm->trace) { ray_release(vm->trace); vm->trace = NULL; } ray_sys_free(vm); } @@ -449,6 +458,7 @@ void ray_runtime_destroy(ray_runtime_t* rt) { g_ray_profile.n = 0; g_ray_profile_last.n = 0; + ray_parted_cache_clear(); ray_sym_destroy(); ray_heap_destroy(); diff --git a/src/core/runtime.h b/src/core/runtime.h index a7eb32caa..135295825 100644 --- a/src/core/runtime.h +++ b/src/core/runtime.h @@ -37,6 +37,7 @@ typedef struct { #define RAY_FRAME_CAP 64 #define RAY_SCOPE_LEXICAL 0 #define RAY_SCOPE_QUERY 1 +#define RAY_SCOPE_CALL 2 /* interpreted named call: stop at globals */ /* One lexical or synthetic query scope frame. keys/vals start out pointing * at the inline arrays and move to heap blocks if the frame grows past @@ -45,11 +46,42 @@ typedef struct { typedef struct { int64_t keys_inline[RAY_FRAME_CAP]; ray_t* vals_inline[RAY_FRAME_CAP]; + uint8_t rows_inline[RAY_FRAME_CAP]; int64_t* keys; /* -> keys_inline, or heap once grown */ ray_t** vals; /* -> vals_inline, or heap once grown */ + /* Row provenance of each binding while a query runs: 1 derived from + * the query's rows (a column, its cell or its group slice, a value + * computed from one), 0 not, 2 unknown. */ + uint8_t* rows; int32_t cap; int32_t count; uint8_t kind; + /* A lambda call's frame: a closure made inside the body captures the + * bindings down to here and no further. A caller's locals are not + * the body's, whether the body runs compiled or interpreted. */ + uint8_t lexical; + /* A compiled frame's window around `eval` or `resolve`: it binds the + * frame's locals for the text being evaluated, and for nothing that + * text calls. A lookup made by compiled code, or from inside a lambda + * called under the window, passes it by. */ + uint8_t eval_window; + /* RAY_SCOPE_CALL only: the call was made by name, so the body's text + * was written outside the query and its literal symbols are literals. */ + uint8_t named; + /* RAY_SCOPE_CALL only: the query's source table (borrowed, may be + * NULL). Lookups that reach this frame still see its columns before + * falling to the globals, as a helper body compiled in a query does; + * the query's aliases and locals below the frame stay hidden. */ + ray_t* table; + /* RAY_SCOPE_CALL only: bindings at this index and above are source + * columns bound on demand; earlier ones are a closure's captured + * values or the call's parameters. */ + int32_t table_from; + /* RAY_SCOPE_QUERY only: a serial unique to this frame instance. A + * closure made while it was the innermost query records it with its + * captures' row flags; those flags apply only while a frame with this + * serial is the innermost query again. */ + uint32_t serial; } ray_scope_frame_t; /* ===== Per-thread VM ===== @@ -68,6 +100,9 @@ typedef struct { * block within the first 32 bytes — ray_sys_alloc data starts at * page+32, so offsets 0..31 share one cache line. */ int32_t eval_depth; + /* Bumped when a conditional tests a vector condition derived from the + * active query's rows: the expression needed row-by-row evaluation. */ + int32_t rows_cond; int32_t scope_depth; bool restricted; /* -U connection on this stack */ int32_t id; @@ -104,6 +139,10 @@ typedef struct { /* ── cold: error paths only */ ray_t *trace; /* error trace list (owned) */ ray_t *raise_val; /* pending (raise x) value (owned) */ + ray_t *return_val; /* pending (return x) value (owned) */ + int32_t lambda_depth; /* lambda bodies running on this thread + * (tree-walked calls and VM runs); a + * `return` outside any is its value */ ray_err_info_t err; /* ── big: lexical scope stack, own cache lines */ ray_scope_frame_t scope_stack[RAY_SCOPE_CAP]; @@ -119,6 +158,7 @@ typedef struct ray_runtime_s { int32_t n_vms; int64_t total_ram; /* total physical RAM, bytes */ int64_t ram_limit; /* min(total_ram, cgroup limit) — default anon watermark */ + char mem_cg[512]; /* limiting cgroup's directory; "" = the machine */ 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; @@ -131,6 +171,10 @@ extern _Thread_local ray_vm_t *__VM; ray_runtime_t* ray_runtime_create(int argc, char** argv); void ray_runtime_destroy(ray_runtime_t* rt); +/* Flush the statistics of the cgroup that limits the process + * (ray_os_cgroup_stat_flush); nothing outside a limiting cgroup. */ +void ray_sys_mem_flush(void); + /* Main event-loop accessors. The host (main.c) registers the poll it * created; runtime-level builtins read it back through these to avoid * pulling poll.h into runtime.h. */ diff --git a/src/io/csv.c b/src/io/csv.c index a5c7f7f2f..c7e4cf9f4 100644 --- a/src/io/csv.c +++ b/src/io/csv.c @@ -1244,11 +1244,7 @@ static int64_t build_row_offsets_window(const char* buf, size_t buf_size, /* Readahead hint for the window about to be scanned: the scanner's * tasks fault the pages in parallel, which a cold file serves best * when the kernel already streams the range. */ - { - size_t ps = (size_t)sysconf(_SC_PAGESIZE); - size_t a = data_offset & ~(ps - 1); - madvise((void*)(buf + a), end - a, MADV_WILLNEED); - } + ray_vm_advise_willneed((void*)(buf + data_offset), end - data_offset); int64_t* offs = NULL; ray_t* hdr = NULL; int64_t n = build_row_offsets_par(buf, end, data_offset, 0, 0, data_has_quotes, &offs, &hdr); diff --git a/src/io/parquet.c b/src/io/parquet.c index c9ca37476..8f41c281d 100644 --- a/src/io/parquet.c +++ b/src/io/parquet.c @@ -10,9 +10,14 @@ #include "core/platform.h" #include "core/pool.h" #include "core/crc32.h" +#include "core/profile.h" +#include "core/runtime.h" /* ray_error_msg: a pool task's error message */ #include "mem/heap.h" +#include "mem/sys.h" /* ray_sys_free: the grouped import's redo list */ #include "table/sym.h" #include "table/domain.h" +#include "table/symimp.h" /* ray_symimp_stats_t: RAY_CSV_TRACE */ +#include "table/symgrp.h" /* the grouped symbol import */ #include "vec/str.h" #include "vec/vec.h" #include "ops/idxop.h" @@ -257,7 +262,7 @@ 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]; + uint64_t hashes[8192]; /* ray_hash_bytes, all 64 bits */ int64_t ids[8192], positions[8192]; } pq_symbol_scratch; typedef struct { @@ -673,31 +678,44 @@ static int64_t pq_dict_max_len(ray_parquet_t* r, pq_span meta) { * 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. */ + * partitioned writer can count partitions with it before decoding. `cols` + * is the group's column chunk metadata (pq_group_columns). */ +static int64_t pq_cols_batch(ray_parquet_t* r, const pq_span* cols) { + int64_t batch = r->batch_rows; + 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; + } + return batch; +} 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; - } - } + if (pq_group_columns(r,g,cols,&rows,NULL)) batch = pq_cols_batch(r,cols); ray_free_raw(cols); return batch; } -static const char* pq_start_group(ray_parquet_t* r) { +/* An error of schema column c (-1: of none), named as the decoder names a + * column's: " (column )". */ +static ray_t* pq_col_error(const ray_parquet_t* r, const char* err, int64_t c) { + if (c < 0) return pq_error(err); + ray_t* name = ray_sym_str(r->schema[c].name); + return ray_error("parquet","%s (column %s)",err,name ? ray_str_ptr(name) : "?"); +} +/* *bad: the schema column a column's error is of, -1 for the group's own. */ +static const char* pq_start_group(ray_parquet_t* r, int64_t* bad) { + *bad = -1; pq_span* cols = ray_alloc_raw((size_t)r->ncols*sizeof(*cols)); if (!cols) return "row group allocation failed"; pq_span filter_chunk = {0}; @@ -707,7 +725,7 @@ static const char* pq_start_group(ray_parquet_t* r) { * 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); + r->group_batch = pq_cols_batch(r,cols); /* the metadata just read, not read again */ /* 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. */ @@ -722,6 +740,7 @@ static const char* pq_start_group(ray_parquet_t* r) { 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]]; + *bad = 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); @@ -737,6 +756,7 @@ static const char* pq_start_group(ray_parquet_t* r) { 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); + if (!err) *bad = -1; 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) { @@ -746,10 +766,15 @@ static bool pq_unpack(pq_column* c, const uint8_t* p, size_t n, size_t decoded, 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) { +/* A dictionary page of `size` bytes in the file, `n` decoded: decompressed + * straight into c->dict (not through c->page and a copy), or copied there + * when stored. */ +static bool pq_dictionary(pq_column* c, pq_schema* s, const uint8_t* payload, size_t size, 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); + if (c->codec) { if (!ray_parquet_snappy(payload,size,c->dict,n)) return false; } + else if (size != n) return false; + else if (n) memcpy(c->dict,payload,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)); @@ -770,14 +795,14 @@ static bool pq_dictionary(pq_column* c, pq_schema* s, const uint8_t* data, size_ 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; + uint64_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]); + hashes[i] = 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; + if (!ray_sym_domain_intern_batch64(s->import_domain,n,strings,lengths,hashes,c->symbol_ids+off)) return false; } } return true; @@ -785,16 +810,47 @@ static bool pq_dictionary(pq_column* c, pq_schema* s, const uint8_t* data, size_ size_t width = s->physical == 1 || s->physical == 4 ? 4 : 8; return s->physical != 0 && (uint64_t)count*width == n; } +/* The steps of reading a page that the decoder (pq_page) and the seeding + * of a grouped import's direct columns (pq_seed_dicts) share, so that the + * seeding takes only what the decoder would. A page at the cursor: its + * header's fields into f[10], its sizes checked, its payload taken past + * it. */ +static const char* pq_page_take(pq_cur* cur, pq_span* f, int64_t* raw, int64_t* size, const uint8_t** payload) { + const uint8_t* start = cur->p; + if (!pq_skip(cur,12,0,false)) return "invalid page header"; + if (!pq_fields((pq_span){start,cur->p,12},f,10)) return "invalid page fields"; + *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)"; + if (!pq_take(cur,(uint64_t)*size,payload)) return "truncated page"; + return NULL; +} +/* Its checksum, when the header has one: the ordinary CRC-32 over the + * compressed page body. */ +static const char* pq_page_crc(const pq_span* f, const uint8_t* payload, int64_t size) { + if (!f[4].type) return NULL; + int64_t expected; + if (!pq_num(f[4],&expected)) return "invalid page checksum"; + if (ray_crc32(0,payload,(size_t)size) != (uint32_t)expected) return "page checksum mismatch"; + return NULL; +} +/* A dictionary page's header (PLAIN or PLAIN_DICTIONARY values) and its + * values into the cursor (pq_dictionary); *count its entries. False when + * either cannot be read: "invalid dictionary page". */ +static bool pq_dict_page(pq_column* c, pq_schema* s, const pq_span* f, const uint8_t* payload, int64_t size, int64_t raw, + int64_t* count) { + pq_span h[9]; + if (!pq_fields(f[7],h,9) || !pq_num(h[1],count)) return false; + int64_t encoding = pq_get(h[2],-1); + return (encoding == 0 || encoding == 2) && pq_dictionary(c,s,payload,(size_t)size,(size_t)raw,*count); +} 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)"; + int64_t raw, size; const uint8_t* payload; - if (!pq_take(&c->chunk,(uint64_t)size,&payload)) return "truncated page"; + const char* perr = pq_page_take(&c->chunk,f,&raw,&size,&payload); + if (perr) return perr; + int64_t kind = pq_get(f[1],-1); 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) || @@ -806,20 +862,12 @@ static const char* pq_page(pq_column* c, pq_schema* s, int64_t* skip) { 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 ((perr = pq_page_crc(f,payload,size))) return perr; 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"; + if (!pq_dict_page(c,s,f,payload,size,raw,&count)) return "invalid dictionary page"; continue; } if (kind == 0) { @@ -958,7 +1006,7 @@ static const char* pq_decode_symbols(pq_column* c, pq_schema* s, ray_t** out, in 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; + uint64_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"; @@ -996,11 +1044,11 @@ static const char* pq_decode_symbols(pq_column* c, pq_schema* s, ray_t** out, in 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; + hashes[count] = 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"; + if (!ray_sym_domain_intern_batch64(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; @@ -1149,14 +1197,14 @@ static const char* pq_intern_selected(pq_column* c, ray_t** vector, ray_sym_doma 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; + uint64_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]); + hashes[i] = ray_hash_bytes(strings[i],lengths[i]); } - if (!ray_sym_domain_intern_batch(domain,n,strings,lengths,hashes,ids)) { + if (!ray_sym_domain_intern_batch64(domain,n,strings,lengths,hashes,ids)) { ray_release(dst); return "symbol domain allocation failed"; } for (int64_t i = 0; i < n; i++) { @@ -1189,8 +1237,9 @@ ray_t* ray_parquet_next(ray_parquet_t* r) { 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); } + int64_t bad; + err = pq_start_group(r,&bad); + if (err) { r->failed = true; return pq_col_error(r,err,bad); } } if (!r->group_left && r->emitted) return NULL; int64_t cap = r->group_batch > 0 ? r->group_batch : r->batch_rows; @@ -1285,11 +1334,7 @@ ray_t* ray_parquet_next(ray_parquet_t* r) { 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); + return pq_col_error(r,err,bad_col >= 0 ? r->selected[bad_col] : -1); } /* Optional Rayfall scan settings: {columns: [x y] range: {column: k min: 1 max: 9}}. @@ -1354,14 +1399,16 @@ static ray_t* pq_open_options(const char* path, ray_t* options, ray_parquet_t** } /* 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) { + * cursors, page buffers, dictionary and selection. The parent outlives the join. + * Cursors for the first `nselected` of the parent's selected columns (all of + * them, or the one column a direct import task sets). */ +static ray_parquet_t* pq_group_reader(const ray_parquet_t* parent, int64_t group, int64_t nselected) { 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->nselected = nselected; r->noutput = parent->noutput; r->filter_pos = parent->filter_pos; r->filter_lo = parent->filter_lo; r->filter_hi = parent->filter_hi; r->filter_nulls = parent->filter_nulls; r->text_pattern = parent->text_pattern; r->text_pos = parent->text_pos; @@ -1395,13 +1442,45 @@ static ray_t* pq_append_table(ray_t** vectors, ray_t* batch, int64_t ncols) { } return NULL; } +/* An error object carries its code; its message is the raising thread's + * (ray_error_msg, thread local). A pool task that fails on a worker notes + * that message here, the lowest failed task's kept, and the thread that + * reports the task's error raises it again with it (pq_task_msg_raise): + * otherwise only the code reached the caller. */ +typedef struct { + _Atomic(bool) busy; /* a spin lock, taken only on a failure */ + int64_t task; /* the lowest failed task noted, INT64_MAX: none */ + char msg[256]; +} pq_task_msg; +static void pq_task_msg_reset(pq_task_msg* m) { + atomic_init(&m->busy,false); m->task = INT64_MAX; m->msg[0] = 0; +} +/* After `task` failed with an error raised on this thread. */ +static void pq_task_msg_note(pq_task_msg* m, int64_t task) { + if (!m) return; + const char* s = ray_error_msg(); + while (atomic_exchange_explicit(&m->busy,true,memory_order_acquire)) RAY_CPU_RELAX(); + if (task < m->task) { m->task = task; snprintf(m->msg,sizeof(m->msg),"%s",s ? s : ""); } + atomic_store_explicit(&m->busy,false,memory_order_release); +} +/* `task`'s error `e`, reported on this thread, the tasks joined: raised again + * with the message noted for it (none when it had none). */ +static ray_t* pq_task_msg_raise(pq_task_msg* m, int64_t task, ray_t* e) { + if (!m || !e || !RAY_IS_ERR(e) || m->task != task) return e; + char code[8]; + snprintf(code,sizeof(code),"%s",ray_err_code(e)); + ray_t* again = m->msg[0] ? ray_error(code,"%s",m->msg) : ray_error(code,NULL); + ray_error_free(e); + return again; +} static ray_t* pq_materialize(ray_parquet_t* r); -typedef struct { ray_parquet_t* parent; int64_t first; ray_t** tables; } pq_read_work; +typedef struct { ray_parquet_t* parent; int64_t first; ray_t** tables; pq_task_msg* emsg; } 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); + ray_parquet_t* r = pq_group_reader(w->parent,w->first+i,w->parent->nselected); w->tables[i] = r ? pq_materialize(r) : ray_error("oom",NULL); + if (w->tables[i] && RAY_IS_ERR(w->tables[i])) pq_task_msg_note(w->emsg,i); } } static ray_t* pq_materialize(ray_parquet_t* r) { @@ -1426,19 +1505,22 @@ static ray_t* pq_materialize(ray_parquet_t* r) { 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; } + pq_task_msg emsg; /* the failed groups' messages, a wave at a time */ 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}; + pq_task_msg_reset(&emsg); + pq_read_work work = {r,first,tables,&emsg}; 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 if (RAY_IS_ERR(batch)) { err = pq_task_msg_raise(&emsg,i,batch); batch = NULL; } else err = pq_append_table(vectors,batch,r->noutput); } - if (batch) ray_release(batch); + /* an error past the one reported: freed (release leaves errors) */ + if (batch) { if (RAY_IS_ERR(batch)) ray_error_free(batch); else ray_release(batch); } } } ray_free_raw(tables); @@ -1569,6 +1651,7 @@ typedef struct { int64_t *offsets; ray_t** errors; bool durable; + pq_task_msg* emsg; /* the failed tasks' messages */ } 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. @@ -1635,9 +1718,10 @@ static ray_t* pq_write_reader(ray_parquet_t* r, const char* root, const char* ta 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; } + ray_parquet_t* r = pq_group_reader(w->parent,g,w->parent->nselected); + if (!r) { w->errors[g] = ray_error("oom",NULL); pq_task_msg_note(w->emsg,g); continue; } w->errors[g] = pq_write_reader(r,w->root,w->table,w->offsets[g],w->durable); + if (w->errors[g]) pq_task_msg_note(w->emsg,g); ray_parquet_close(r); } } @@ -1660,14 +1744,16 @@ static ray_t* pq_write_groups(ray_parquet_t* r, const char* root, const char* ta *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}; + pq_task_msg emsg; + pq_task_msg_reset(&emsg); + pq_native_work work = {r,root,table,offsets,errors,durable,&emsg}; 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) err = pq_task_msg_raise(&emsg,g,errors[g]); else ray_error_free(errors[g]); } if (!err && ray_interrupted()) err = ray_error("cancel","parquet conversion interrupted"); done: @@ -1783,6 +1869,10 @@ static bool pq_remove_dir(const char* path) { return rmdir(path) == 0; #endif } +/* Column by column below this many times the output's bytes of memory + * (see pq_write_direct). */ +#define PQ_COLWISE_RATIO 2 + typedef struct { ray_parquet_t* parent; ray_col_stream_t* writers; @@ -1790,22 +1880,276 @@ typedef struct { _Atomic uint32_t* nulls; _Atomic uint32_t* locks; ray_t** errors; + const int64_t* pass; /* the columns of the current pass */ + int64_t npass; + const int64_t* chunk_lo; /* [ngroups * ncols] byte range of each column chunk, */ + const int64_t* chunk_hi; /* lo < 0 when the metadata does not give one */ + _Atomic uint8_t* prefetched; /* [ngroups * ncols]: read-ahead already requested */ + int64_t prefetch; /* row groups requested ahead of the one starting */ + int64_t ahead_bytes; /* cap on what one task requests past its own chunk */ + bool writeback; /* start each written chunk's writeback (one-pass layout) */ + pq_column* spare; /* [nspare] each worker's buffers between its tasks */ + int64_t nspare; + bool reverse; /* debug: the row groups last to first (RAY_PQ_DIRECT_REVERSE) */ + pq_task_msg* emsg; /* the failed tasks' messages (errors[]'s) */ } pq_direct_work; + +/* Trade a task cursor's page, dictionary and symbol buffers with its + * worker's spare ones: a worker grows them once for all its tasks, instead + * of each task allocating and doubling its own. Buffers past PQ_SPARE_MAX + * (large pages or dictionaries of one column) are freed when the pass that + * grew them ends, not held to the end of the import. */ +#define PQ_SPARE_MAX ((size_t)4 << 20) +static void pq_trade_buffers(pq_column* c, pq_column* spare) { + uint8_t* page = c->page; size_t page_cap = c->page_cap; + uint8_t* dict = c->dict; size_t dict_cap = c->dict_cap; + pq_symbol_scratch* symbols = c->symbols; + c->page = spare->page; c->page_cap = spare->page_cap; + c->dict = spare->dict; c->dict_cap = spare->dict_cap; + c->symbols = spare->symbols; + spare->page = page; spare->page_cap = page_cap; + spare->dict = dict; spare->dict_cap = dict_cap; + spare->symbols = symbols; +} + +/* Byte range of every column chunk — from its dictionary page (or first + * data page) for total_compressed bytes — and each column's uncompressed + * total, INT64_MAX when a chunk of rows has no size (missing or not + * positive: its text unbounded, so an import of it is not taken for small). + * False when a row group's metadata cannot be read. */ +static bool pq_chunk_ranges(ray_parquet_t* r, int64_t* lo, int64_t* hi, int64_t* col_bytes) { + pq_span* cols = ray_calloc_raw((size_t)r->ncols*sizeof(*cols)); + bool ok = cols != NULL; + for (int64_t g = 0; ok && g < r->ngroups; g++) { + int64_t rows = 0; + if (!pq_group_columns(r,g,cols,&rows,NULL)) { ok = false; break; } + for (int64_t c = 0; c < r->ncols; c++) { + int64_t i = g*r->ncols+c; pq_span mf[17]; + lo[i] = hi[i] = -1; + if (!pq_fields(cols[c],mf,17)) continue; + int64_t data = pq_get(mf[9],-1), dict = pq_get(mf[11],-1), bytes = pq_get(mf[7],-1); + int64_t raw = pq_get(mf[6],-1), start = dict > 0 && dict < data ? dict : data; + if (raw > 0) col_bytes[c] = raw > INT64_MAX - col_bytes[c] ? INT64_MAX : col_bytes[c] + raw; + else if (rows > 0) col_bytes[c] = INT64_MAX; /* rows of no size: unbounded (pq_chunk_vocab's unsure) */ + if (start < 0 || bytes < 0 || start > (int64_t)r->size || bytes > (int64_t)r->size - start) continue; + lo[i] = start; hi[i] = start + bytes; + } + } + ray_free_raw(cols); + return ok; +} + +/* What the direct import holds a distinct string by, beyond its bytes: its + * record's offset, its slot in the shard tables at their load factor, the + * tables' doubling. */ +#define PQ_DIRECT_STRING_COST 48 +/* A chunk's dictionary page header: its decoded bytes (every entry's + * length prefix and bytes) and its entries. False when it cannot be read + * here. */ +static bool pq_dict_header(ray_parquet_t* r, int64_t dict, int64_t* raw, int64_t* entries) { + if (dict < 4 || (uint64_t)dict >= r->data_end) return false; + 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 false; + pq_span f[10], h[4]; + if (!pq_fields((pq_span){start,c.p,12},f,10) || pq_get(f[1],-1) != 2 || !pq_fields(f[7],h,4)) return false; + *raw = pq_get(f[2],-1); *entries = pq_get(h[1],-1); + return *raw >= 0 && *entries >= 0; +} +/* From a chunk's encoding stats (ColumnMetaData 13): 1 when one of its data + * pages is not dictionary-encoded (a writer's PLAIN fallback, or another + * encoding of the values themselves), 0 when none is, -1 when there are no + * stats or they cannot be read. */ +static int pq_value_pages(pq_span stats) { + if (stats.type != 9) return -1; + pq_cur c = {stats.p,stats.end,false}; + uint8_t et; uint64_t n = pq_list(&c,&et); + if (c.bad || et != 12) return -1; + int any = 0; + for (uint64_t i = 0; i < n; i++) { + pq_span e, f[4]; + if (!pq_element(&c,et,&e) || !pq_fields(e,f,4)) return -1; + int64_t kind = pq_get(f[1],-1), enc = pq_get(f[2],-1), count = pq_get(f[3],-1); + if (kind < 0 || enc < 0) return -1; + if ((kind == 0 || kind == 3) && enc != 2 && enc != 8 && count != 0) any = 1; + } + return any; +} +/* Sums and products of a footer's sizes, which are the file's word: never + * negative, saturating at INT64_MAX instead of wrapping. */ +static inline int64_t pq_sat_add(int64_t a, int64_t b) { + if (a < 0) a = 0; + if (b < 0) b = 0; + return a > INT64_MAX - b ? INT64_MAX : a + b; +} +static inline int64_t pq_sat_mul(int64_t a, int64_t b) { + if (a <= 0 || b <= 0) return 0; + return a > INT64_MAX / b ? INT64_MAX : a * b; +} +/* An upper bound on the memory the direct import would hold for a symbol + * chunk's distinct strings: their bytes and PQ_DIRECT_STRING_COST each. A + * dictionary page counts its decoded bytes and entries (from its header); + * the data pages count only when they may hold the values themselves: no + * dictionary, the encoding stats naming such a page, or no stats at all + * (unsure: then every data byte may be a string's, a string at least the 4 + * bytes of its length prefix). An unreadable dictionary header counts the + * whole chunk so; a chunk of no size (missing or not positive) is unsure, + * unbounded. Asked only for a chunk of rows (pq_vocab_bounds leaves out + * the zero-row groups, as the decoder does). Saturating, never negative. */ +static int64_t pq_chunk_vocab(ray_parquet_t* r, pq_span* mf, bool* dict_only) { + int64_t raw = pq_get(mf[6],-1), values = pq_get(mf[5],-1); + int64_t data = pq_get(mf[9],-1), dict = pq_get(mf[11],-1); + *dict_only = false; + if (raw <= 0) return INT64_MAX; + if (values < 0 || values > raw) values = raw; + int64_t draw, entries, rest = raw, bound = 0; + if (dict > 0 && dict < data && pq_dict_header(r,dict,&draw,&entries)) { + bound = pq_sat_add(draw,pq_sat_mul(PQ_DIRECT_STRING_COST,entries)); + *dict_only = pq_value_pages(mf[13]) == 0; + rest = *dict_only ? 0 : raw > draw ? raw - draw : raw; + } + int64_t n = rest / 4 < values ? rest / 4 : values; + return pq_sat_add(pq_sat_add(bound,rest),pq_sat_mul(PQ_DIRECT_STRING_COST,n)); +} +/* The symbol columns' bounds (pq_chunk_vocab), summed over the row groups, + * into vocab[c] for the columns order[from, to), and in dict_only[c] + * whether every chunk's strings are its dictionary page's (the encoding + * stats say no data page holds values), zero-row groups left out. The + * dictionary page headers are asked for all at once first (one small read + * each, in flight together) and then parsed. */ +static void pq_vocab_bounds(ray_parquet_t* r, const int64_t* order, int64_t from, int64_t to, int64_t* vocab, + uint8_t* dict_only) { + pq_span* cols = ray_calloc_raw((size_t)r->ncols*sizeof(*cols)); + for (int64_t i = from; i < to; i++) { vocab[order[i]] = cols ? 0 : INT64_MAX; dict_only[order[i]] = cols != NULL; } + if (!cols) return; + for (int pass = 0; pass < 2; pass++) + for (int64_t g = 0; g < r->ngroups; g++) { + int64_t rows = 0; + bool ok = pq_group_columns(r,g,cols,&rows,NULL); + if (ok && rows == 0) continue; /* nothing decoded (pq_start_group), whatever its chunks say */ + for (int64_t i = from; i < to; i++) { + int64_t c = order[i]; pq_span mf[17]; + if (!ok || !pq_fields(cols[c],mf,17)) { if (pass) { vocab[c] = INT64_MAX; dict_only[c] = 0; } continue; } + if (!pass) { + int64_t dict = pq_get(mf[11],-1); + if (dict >= 4 && (uint64_t)dict < r->data_end) + ray_vm_advise_willneed(r->map + dict,(size_t)(r->data_end - (uint64_t)dict < 256 ? r->data_end - (uint64_t)dict : 256)); + continue; + } + bool only; + int64_t v = pq_chunk_vocab(r,mf,&only); + vocab[c] = pq_sat_add(vocab[c],v); + if (!only) dict_only[c] = 0; + } + } + ray_free_raw(cols); +} +/* A direct column of a grouped import: the dictionary pages of its chunks + * interned in row-group order before its pass (its chunks are dictionary + * pages and ids only, pq_vocab_bounds' dict_only), so the parallel pass + * finds every string there and the positions do not depend on the workers. + * The pages are asked for together first. NULL, or the reason a page + * cannot be read: the decoder's own, so the import reports what the pass + * itself would have, and in *bad_col the column it is of (-1: none). */ +static const char* pq_seed_dicts(ray_parquet_t* r, const int64_t* order, int64_t from, int64_t to, int64_t* entries, + int64_t* bad_col) { + pq_span* cols = ray_calloc_raw((size_t)r->ncols*sizeof(*cols)); + *bad_col = -1; + if (!cols) return "symbol dictionary allocation failed"; + const char* err = NULL; + for (int pass = 0; !err && pass < 2; pass++) + for (int64_t g = 0; !err && g < r->ngroups; g++) { + int64_t rows = 0; + if (!pq_group_columns(r,g,cols,&rows,NULL)) { err = "invalid row group"; *bad_col = -1; break; } + if (rows == 0) continue; /* no rows: pq_vocab_bounds and the decoder skip it too */ + for (int64_t i = from; !err && i < to; i++) { + int64_t c = order[i]; pq_span mf[17]; + *bad_col = c; /* its errors name the column, as the decoder's do */ + if (!pq_fields(cols[c],mf,17)) { err = "invalid column metadata"; break; } + int64_t dict = pq_get(mf[11],-1), data = pq_get(mf[9],-1), codec = pq_get(mf[4],-1); + int64_t bytes = pq_get(mf[7],-1); + if (codec != 0 && codec != 1) { err = "unsupported compression codec (supported: uncompressed, Snappy)"; break; } + /* the decoder's bounds (pq_start_group): the chunk from its + * dictionary page for total_compressed_size bytes, whatever + * data_page_offset says past it */ + if (dict > data) { err = "dictionary follows data"; break; } + if (dict < 4 || bytes < 0 || (uint64_t)dict > r->data_end || (uint64_t)bytes > r->data_end-(uint64_t)dict) { + err = "column chunk outside file data"; break; + } + if (!pass) { + /* the dictionary page: to the first data page where that + * lies within the chunk, else the chunk */ + ray_vm_advise_willneed(r->map + dict,(size_t)(data > dict && data - dict <= bytes ? data - dict : bytes)); + continue; + } + /* the decoder's steps (pq_page): a page gone bad is refused + * before any of its strings is interned */ + pq_cur cur = {r->map+dict,r->map+dict+bytes,false}; + pq_span f[10]; + int64_t raw, size, count = 0; + const uint8_t* payload; + if ((err = pq_page_take(&cur,f,&raw,&size,&payload))) break; + if ((err = pq_page_crc(f,payload,size))) break; + if (pq_get(f[1],-1) != 2) { err = "invalid dictionary page"; break; } + pq_column col = {0}; + col.codec = (int)codec; + pq_schema sch = r->schema[c]; + if (!sch.import_domain) err = "symbol column without an import dictionary"; + else if (!pq_dict_page(&col,&sch,f,payload,size,raw,&count)) err = "invalid dictionary page"; + else *entries += count; + ray_free_raw(col.dict); ray_free_raw(col.strings); ray_free_raw(col.symbol_ids); ray_free_raw(col.symbols); + } + } + if (!err) *bad_col = -1; + ray_free_raw(cols); + return err; +} + +/* A mapped column chunk is read on first touch, one fault at a time per + * worker, so a worker has a single read in flight; on storage with a high + * per-request latency (a network block device) that bounds the import. A + * task asks the kernel for its whole chunk and for the same column's chunks + * of the next `prefetch` row groups (up to `ahead_bytes`), so the reads are + * in flight together while it decodes. RAY_PQ_PREFETCH sets the depth + * (default 2, 0 turns it off). */ +static void pq_prefetch_chunks(pq_direct_work* w, int64_t g, int64_t c) { + ray_parquet_t* r = w->parent; + int64_t ahead = 0; + for (int64_t k = 0; k <= w->prefetch && g + k < r->ngroups; k++) { + int64_t i = (g+k)*r->ncols+c, lo = w->chunk_lo[i], hi = w->chunk_hi[i]; + if (lo < 0) continue; + if (k > 0 && (ahead += hi - lo) > w->ahead_bytes) break; + uint8_t z = 0; + if (!atomic_compare_exchange_strong_explicit(&w->prefetched[i],&z,1, + memory_order_relaxed,memory_order_relaxed)) continue; + ray_vm_advise_willneed(r->map + lo,(size_t)(hi-lo)); + } +} static void pq_write_direct_group(void* ptr, uint32_t worker, int64_t start, int64_t end) { - (void)worker; pq_direct_work* w = ptr; + pq_direct_work* w = ptr; + pq_column* spare = (int64_t)worker < w->nspare ? &w->spare[worker] : NULL; 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; } + /* Row groups outermost within a pass: a worker reads one group's + * chunks of the pass's columns side by side. */ + int64_t g = task/w->npass, c = w->pass[task%w->npass]; + if (w->reverse) g = w->parent->ngroups-1-g; + if (w->prefetched) pq_prefetch_chunks(w,g,c); + ray_parquet_t* r = pq_group_reader(w->parent,g,1); + if (!r) { w->errors[task] = ray_error("oom",NULL); goto next; } /* 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; + if (spare) pq_trade_buffers(&r->cursors[0],spare); 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; } + if (!local.fp) { + w->errors[task] = pq_error("cannot open native column"); + if (spare) pq_trade_buffers(&r->cursors[0],spare); + ray_parquet_close(r); goto next; + } int64_t offset = 32+row*(int64_t)size; #ifdef RAY_OS_WINDOWS bool seek = _fseeki64(local.fp,offset,SEEK_SET) == 0; @@ -1835,22 +2179,754 @@ static void pq_write_direct_group(void* ptr, uint32_t worker, int64_t start, int /* 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; } + /* Start this chunk's writeback now: the pages leave while the + * import goes on, instead of all at the final sync. A failed flush + * has dropped its buffer, and the close after it may well succeed: + * it is the task's error. */ + if (w->writeback && !w->errors[task]) { + if (fflush(local.fp) != 0) w->errors[task] = pq_error("native column write failed"); + else ray_file_writeback_start(fileno(local.fp),32+w->offsets[g]*(int64_t)size, + (row-w->offsets[g])*(int64_t)size); + } if (fclose(local.fp) && !w->errors[task]) w->errors[task] = pq_error("native column close failed"); + /* The task's writer owns no file of its own (tmp_path is the + * column's, left unset here): abort only frees what an append may + * have made, such as the runtime id cache of a runtime-domain + * chunk. */ + local.fp = NULL; + ray_col_stream_abort(&local); 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"); + if (spare) pq_trade_buffers(&r->cursors[0],spare); ray_parquet_close(r); + next: + if (w->errors[task]) pq_task_msg_note(w->emsg,task); + } +} + +/* While the passes run, a background thread appends the file domain's new + * entries to the symbol file every quarter second (and starts their + * writeback), so the final flush writes only the tail and its sync finds + * the rest on disk. */ +typedef struct { ray_sym_domain_t* dom; _Atomic(bool) stop; _Atomic(int) err; } pq_symflush_t; +static void pq_symflush_fn(void* arg) { + pq_symflush_t* s = arg; + while (!atomic_load_explicit(&s->stop,memory_order_acquire)) { + ray_err_t e = ray_sym_domain_flush_append(s->dom,false); + if (e != RAY_OK) { atomic_store_explicit(&s->err,(int)e,memory_order_release); return; } + /* in slices, so the import's end does not wait out the interval */ + for (int i = 0; i < 25 && !atomic_load_explicit(&s->stop,memory_order_acquire); i++) + ray_sleep_ms(10); + } +} + +/* ---- the grouped symbol import (table/symgrp.h) --------------------------- + * A symbol column whose strings would make the import dictionary too big to + * probe at random goes in two decodes of its chunks: the first deduplicates + * each chunk and stages its distinct strings' hashes and lengths, the + * dictionary then gives them verdicts one hash group at a time, and the + * second decode writes the new strings, compares every candidate's bytes + * with its record and writes the codes. No string is kept between the two; + * the symbol file is only appended to and read in position order. */ +typedef enum { PQ_SYM_AUTO, PQ_SYM_DIRECT, PQ_SYM_GROUPED } pq_sym_mode; + +/* One chunk's exact dedupe: local ids by first occurrence (0 is the null + * and "" row), a repeat found by length, then hash, then bytes. The bytes + * of the generation's strings sit in an arena; when it is full the table + * starts over, so a later repeat gets an id of its own, which the + * dictionary links to the first. Both decodes make the same ids. */ +typedef struct { + ray_symgrp_fp_t* fp; /* local id i + 1 at fp[i] */ + uint32_t* cnt; /* FREQ: rows per local id */ + int64_t n, cap; + uint32_t* slot; uint64_t mask; + int64_t* aoff; /* arena offset, by local id - first */ + char* arena; int64_t abytes, acap, first, gens; + int64_t alim; /* a generation's arena bytes (the pass's; the + * arena may have grown past it for one string) */ +} pq_dedup; + +static void pq_dedup_free(pq_dedup* d) { + ray_free_raw(d->fp); ray_free_raw(d->cnt); ray_free_raw(d->slot); + ray_free_raw(d->aoff); ray_free_raw(d->arena); + memset(d,0,sizeof(*d)); +} +/* The arena starts small and doubles up to a generation's bytes: a worker + * whose chunks are small never holds the generation limit's memory. */ +#define PQ_DEDUP_ARENA0 ((int64_t)64 << 10) +static bool pq_dedup_init(pq_dedup* d, int64_t alim, bool counts) { + memset(d,0,sizeof(*d)); + d->alim = alim; d->acap = alim < PQ_DEDUP_ARENA0 ? alim : PQ_DEDUP_ARENA0; + d->first = 1; d->cap = 1024; d->mask = 2047; + d->fp = ray_alloc_raw((size_t)d->cap*sizeof(*d->fp)); + d->aoff = ray_alloc_raw((size_t)d->cap*sizeof(*d->aoff)); + d->slot = ray_calloc_raw((size_t)(d->mask+1)*sizeof(*d->slot)); + d->arena = ray_alloc_raw((size_t)(d->acap > 0 ? d->acap : 1)); + if (counts) d->cnt = ray_calloc_raw((size_t)(d->cap+1)*sizeof(*d->cnt)); + return d->fp && d->aoff && d->slot && d->arena && (!counts || d->cnt); +} +/* A worker's dedupe for its next chunk, the buffers its earlier chunks grew + * kept (warm pages, no allocation a task). The ids depend only on the + * chunk and the generation limit, so both decodes still agree. */ +static bool pq_dedup_reset(pq_dedup* d, int64_t alim, bool counts) { + if (!d->fp) return pq_dedup_init(d,alim,counts); + d->n = 0; d->first = 1; d->abytes = 0; d->gens = 0; d->alim = alim; + memset(d->slot,0,(size_t)(d->mask+1)*sizeof(*d->slot)); + if (counts && !d->cnt) d->cnt = ray_alloc_raw((size_t)(d->cap+1)*sizeof(*d->cnt)); + if (counts && !d->cnt) return false; + if (d->cnt) memset(d->cnt,0,(size_t)(d->cap+1)*sizeof(*d->cnt)); + return true; +} +static bool pq_dedup_rehash(pq_dedup* d, uint64_t cap) { + uint32_t* s = ray_calloc_raw((size_t)cap*sizeof(*s)); + if (!s) return false; + ray_free_raw(d->slot); d->slot = s; d->mask = cap-1; + for (int64_t id = d->first; id <= d->n; id++) { + uint64_t i = d->fp[id-1].h & d->mask; + while (d->slot[i]) i = (i+1) & d->mask; + d->slot[i] = (uint32_t)id; + } + return true; +} +/* The local id of a non-empty string; *fresh when it is its first + * occurrence (of the generation). 0 on allocation failure. */ +static uint32_t pq_dedup_id(pq_dedup* d, uint64_t h, const char* s, uint32_t len, bool* fresh) { + uint64_t i = h & d->mask; + for (uint32_t v; (v = d->slot[i]); i = (i+1) & d->mask) { + const ray_symgrp_fp_t* f = &d->fp[v-1]; + if (f->len == len && f->h == h && !memcmp(d->arena+d->aoff[v-d->first],s,len)) { *fresh = false; return v; } + } + *fresh = true; + if (d->n >= UINT32_MAX-1) return 0; + if (d->abytes+len > d->alim && d->n >= d->first) { + /* a new generation */ + memset(d->slot,0,(size_t)(d->mask+1)*sizeof(*d->slot)); + d->abytes = 0; d->first = d->n+1; d->gens++; + i = h & d->mask; + } + if (d->n == d->cap) { + int64_t nc = d->cap*2; + ray_symgrp_fp_t* fp = ray_realloc_raw(d->fp,(size_t)nc*sizeof(*fp)); + if (!fp) return 0; + d->fp = fp; + if (d->cnt) { + uint32_t* c = ray_realloc_raw(d->cnt,(size_t)(nc+1)*sizeof(*c)); + if (!c) return 0; + memset(c+d->cap+1,0,(size_t)(nc-d->cap)*sizeof(*c)); + d->cnt = c; + } + d->cap = nc; + } + if (d->n+1-d->first >= (int64_t)(d->mask+1)/2) { + int64_t* ao = ray_realloc_raw(d->aoff,(size_t)(d->mask+1)*sizeof(*ao)); + if (!ao || (d->aoff = ao, !pq_dedup_rehash(d,(d->mask+1)*2))) return 0; + i = h & d->mask; + while (d->slot[i]) i = (i+1) & d->mask; + } + if (d->abytes+len > d->acap) { + /* doubled up to the generation's bytes (past them by one string at + * most) */ + int64_t need = d->abytes+len, nc = d->acap*2; + if (nc > d->alim) nc = d->alim; + if (nc < need) nc = need; + char* a = ray_realloc_raw(d->arena,(size_t)nc); + if (!a) return 0; + d->arena = a; d->acap = nc; + } + if (len) memcpy(d->arena+d->abytes,s,len); + d->aoff[d->n+1-d->first] = d->abytes; d->abytes += len; + d->fp[d->n] = (ray_symgrp_fp_t){h,len,(uint32_t)(d->n+1)}; + d->slot[i] = (uint32_t)(++d->n); + return (uint32_t)d->n; +} + +/* A worker's buffers for the pass's chunks, kept from one chunk to the + * next: grown once, their pages warm, freed with the pass. */ +typedef struct { + pq_dedup d; + uint32_t* dmap; int64_t dcap; /* dictionary index -> local id */ + ray_symgrp_res_t* res; uint32_t* map; int64_t rcap; + ray_t* vec; /* a batch of codes */ + char* wbuf; /* records on their way to the file, 2 PQ_GWBUF */ +} pq_gscratch; +#define PQ_GWBUF ((int64_t)1 << 20) + +/* The trace's split of the second decode: verdicts, walk, finish (per + * task, summed over the workers) and the windows' load and settle. */ +enum { PQ_GS_VERDICTS, PQ_GS_WALK, PQ_GS_FINISH, PQ_GS_LOAD, PQ_GS_SETTLE, PQ_GS_N }; +typedef struct { int64_t ns, majflt, rd, wr; } pq_tio_t; + +typedef struct { + pq_direct_work* dw; + int64_t c; /* the column */ + ray_symgrp_t* g; + ray_symimp_t* imp; + int64_t ta, tb; /* the window of the second decode */ + int64_t acap; /* dedupe arena per task */ + uint64_t hmask; /* the hashes kept (all but in a collision test) */ + bool counts, redo, trace; + pq_gscratch* ws; /* [nws], by worker */ + int64_t nws; + _Atomic(int64_t) rows, gens; + _Atomic(int64_t) split[PQ_GS_N][4]; +} pq_gwork; + +/* One chunk's walk, either decode. */ +typedef struct { + pq_gwork* w; + int64_t t; + uint32_t worker; + pq_dedup d; + uint32_t* dmap; /* dictionary index -> local id */ + int64_t dcap; + bool dmapped; + bool second; + int64_t nres; /* second: local ids the first decode made */ + ray_symgrp_res_t* res; /* second: verdicts by local id */ + uint32_t* map; /* second: positions by local id */ + /* second, ROWS*: the task's records in two runs, [1] those later tasks + * meet again, [0] the others (ray_symgrp_task_off) */ + int64_t cursor[2]; /* the next record's offset */ + char* wbuf[2]; /* records not yet written, */ + int64_t wlen[2], woff[2]; /* wlen bytes for file offset woff on */ + uint32_t* codes; int64_t ncodes; + ray_t* vec; ray_col_stream_t* out; + int64_t cmp, cmpb; + const char* err; +} pq_gtask; + +static bool pq_g_inject(const char* step); +/* Records to the symbol file (RAY_PQ_SYM_INJECT=write fails them). */ +static bool pq_g_write(pq_gtask* k, int64_t off, const void* p, size_t n) { + return !pq_g_inject("write") && ray_symimp_write(k->w->imp,off,p,n); +} +/* The task's buffered records of run `a` to the file. */ +static bool pq_g_wflush1(pq_gtask* k, int a) { + if (!k->wlen[a]) return true; + bool ok = pq_g_write(k,k->woff[a],k->wbuf[a],(size_t)k->wlen[a]); + k->woff[a] += k->wlen[a]; k->wlen[a] = 0; + return ok; +} +static bool pq_g_wflush(pq_gtask* k) { return pq_g_wflush1(k,0) && pq_g_wflush1(k,1); } +/* ROWS*: record `pos` at `off`, run a's next: through the run's buffer, + * written with pwrite in large requests (the mapping's pages are never + * faulted in to be overwritten). */ +static bool pq_g_record(pq_gtask* k, int a, int64_t pos, int64_t off, const char* s, uint32_t len) { + ray_symimp_place(k->w->imp,pos,off); + if (k->wlen[a] && k->woff[a] + k->wlen[a] != off && !pq_g_wflush1(k,a)) return false; + if (k->wlen[a] + 4 + (int64_t)len > PQ_GWBUF && !pq_g_wflush1(k,a)) return false; + if (!k->wlen[a]) k->woff[a] = off; + if (4 + (int64_t)len > PQ_GWBUF) /* past the buffer: straight to the file */ + return pq_g_write(k,off,&len,4) && pq_g_write(k,off+4,s,len) && + (k->woff[a] = off + 4 + len, true); + memcpy(k->wbuf[a] + k->wlen[a],&len,4); + if (len) memcpy(k->wbuf[a] + k->wlen[a] + 4,s,len); + k->wlen[a] += 4 + (int64_t)len; + return true; +} +/* Whether `s` is this task's own new record at `pos` (maybe still in one + * of its buffers). */ +static bool pq_g_same_own(pq_gtask* k, uint32_t pos, const char* s, uint32_t len) { + int64_t off = ray_symimp_offset(k->w->imp,pos); + for (int a = 0; a < 2; a++) + if (k->wlen[a] && off >= k->woff[a] && off < k->woff[a] + k->wlen[a]) { + const char* r = k->wbuf[a] + (off - k->woff[a]); + uint32_t rl; memcpy(&rl,r,4); + return rl == len && (!len || !memcmp(r + 4,s,len)); + } + return ray_symgrp_same(k->w->g,pos,s,len); +} + +/* A local id's first occurrence in the second decode: its verdict. */ +static bool pq_g2_first(pq_gtask* k, uint32_t local, uint64_t h, const char* s, uint32_t len) { + ray_symgrp_res_t* v = &k->res[local]; + int64_t pos = v->pos; + if (v->kind == RAY_SYMGRP_NEW) { + /* a redo wrote it already */ + if (v->off < 0) { + int a = v->again ? 1 : 0; + int64_t off = k->cursor[a]; k->cursor[a] += 4+(int64_t)len; + if (!k->w->redo && !pq_g_record(k,a,pos,off,s,len)) return false; + } else if (!k->w->redo) ray_symimp_put(k->w->imp,pos,v->off,s,len); + } else if (v->kind == RAY_SYMGRP_OLD || v->kind == RAY_SYMGRP_REF) { + if (k->w->redo) { + /* compared in the first run: a mismatch has the position the + * window's settle gave it */ + int64_t o = ray_symgrp_override(k->w->g,k->t,local); + if (o >= 0) pos = o; + } else if (v->kind == RAY_SYMGRP_REF && v->owner != k->t && v->owner >= k->w->ta) { + /* another task of the window writes the record: compared after it */ + if (!ray_symgrp_defer(k->w->g,k->worker,k->t,local,h,(uint32_t)pos,s,len)) return false; + } else { + /* compared now; a mismatch takes its position at the window's + * end, in an order the workers do not decide (the codes written + * meanwhile are written again) */ + k->cmp++; k->cmpb += len; + bool same = v->kind == RAY_SYMGRP_REF && v->owner == k->t ? pq_g_same_own(k,(uint32_t)pos,s,len) + : ray_symgrp_same(k->w->g,(uint32_t)pos,s,len); + if (!same && !ray_symgrp_mismatch(k->w->g,k->worker,k->t,local,h,s,len)) return false; + } + } else return false; + k->map[local] = (uint32_t)pos; + return true; +} + +/* A string's local id, first occurrences seen to. */ +static bool pq_g_local(pq_gtask* k, const char* s, uint32_t len, uint32_t* local) { + if (!len) { *local = 0; return true; } + uint64_t h = ray_hash_bytes(s,len) & k->w->hmask; + bool fresh; + uint32_t id = pq_dedup_id(&k->d,h,s,len,&fresh); + if (!id || (k->second && id > k->nres)) return false; + if (fresh && k->second && !pq_g2_first(k,id,h,s,len)) return false; + *local = id; + return true; +} + +static bool pq_g_flush(pq_gtask* k) { + if (!k->ncodes) return true; + k->vec->len = k->ncodes; + ray_err_t e = ray_col_stream_append(k->out,k->vec); + k->ncodes = 0; + return e == RAY_OK; +} +/* `run` rows of local id `local`. */ +static bool pq_g_emit(pq_gtask* k, uint32_t local, int64_t run) { + if (k->d.cnt) k->d.cnt[local] += (uint32_t)run; + if (!k->second) return true; + uint32_t pos = k->map[local]; + while (run > 0) { + int64_t room = PQ_BATCH-k->ncodes, m = run < room ? run : room; + for (int64_t i = 0; i < m; i++) k->codes[k->ncodes+i] = pos; + k->ncodes += m; run -= m; + if (k->ncodes == PQ_BATCH && !pq_g_flush(k)) return false; + } + return true; +} + +/* The chunk's rows, as pq_decode_symbols reads them. */ +static const char* pq_g_walk(pq_column* c, pq_schema* s, int64_t rows, pq_gtask* k) { + 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; } + if (c->have_dict && !k->dmapped) { + if (k->dcap < c->dict_count) { + uint32_t* m = ray_realloc_raw(k->dmap,(size_t)c->dict_count*sizeof(*k->dmap)); + if (!m) return "symbol dictionary allocation failed"; + k->dmap = m; k->dcap = c->dict_count; + } + k->dmapped = true; + for (int64_t i = 0; i < c->dict_count; i++) + if (!pq_g_local(k,(const char*)c->strings[i].p,c->strings[i].n,&k->dmap[i])) return "symbol allocation failed"; + } + int64_t n = rows-at < c->page_left ? rows-at : c->page_left; + for (int64_t i = 0; i < n; i++) { + uint32_t local; + if (!c->optional && c->encoding && c->ids.left && !c->ids.packed) { + uint32_t id = c->ids.value; + if (id >= c->dict_count || !k->dmapped) return "invalid symbol dictionary index"; + local = k->dmap[id]; + if (!local && s->strict) return "nonnull empty text collides with native null"; + int64_t run = n-i < (int64_t)c->ids.left ? n-i : (int64_t)c->ids.left; + if (!pq_g_emit(k,local,run)) return "symbol code write failed"; + c->ids.left -= (uint64_t)run; i += run-1; continue; + } + uint32_t present = 1; + if (c->optional && (!pq_rle_next(&c->defs,&present) || present > 1)) return "invalid definition levels"; + if (!present) { c->page_nulls++; if (!pq_g_emit(k,0,1)) return "symbol code write failed"; continue; } + if (c->encoding) { + uint32_t id; + if (!pq_rle_next(&c->ids,&id) || id >= c->dict_count || !k->dmapped) return "invalid symbol dictionary index"; + local = k->dmap[id]; + if (!local && s->strict) return "nonnull empty text collides with native null"; + } 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"; + if (!pq_g_local(k,(const char*)p,len,&local)) return "symbol allocation failed"; + } + if (!pq_g_emit(k,local,1)) return "symbol code write failed"; + } + 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; +} + +/* Fault injection for the suite: RAY_PQ_SYM_INJECT names the step that + * fails as out of memory ("r1", "p2", "load", "r2", "settle"; "reload" in + * table/symgrp.c: a window's load after the first), whose record writes + * fail ("write"), or is cancelled ("cancel"); debug builds only. */ +static bool pq_g_inject(const char* step) { +#if defined(DEBUG) + const char* e = getenv("RAY_PQ_SYM_INJECT"); + if (!e || strcmp(e,step) != 0) return false; + if (!strcmp(step,"cancel")) { ray_request_interrupt(); return false; } + return true; +#else + (void)step; return false; +#endif +} + +/* A grouped task's error: "cancel" once the import is interrupted (the + * walks stop on it with an error of their own), as the direct import has it. */ +static ray_t* pq_g_error(const ray_parquet_t* r, const char* err, int64_t c) { + return ray_interrupted() ? ray_error("cancel","parquet conversion interrupted") : pq_col_error(r,err,c); +} + +/* The chunk's reader, its cursor holding the worker's buffers. */ +static ray_parquet_t* pq_g_reader(pq_gwork* w, int64_t g, uint32_t worker, const char** err, int64_t* bad) { + pq_direct_work* dw = w->dw; + ray_parquet_t* r = pq_group_reader(dw->parent,g,1); + if (!r) { *err = "row group allocation failed"; return NULL; } + r->selected[0] = (int32_t)w->c; r->nselected = r->noutput = 1; + if ((int64_t)worker < dw->nspare) pq_trade_buffers(&r->cursors[0],&dw->spare[worker]); + r->group++; + *err = pq_start_group(r,bad); + return r; +} +static void pq_g_reader_close(pq_gwork* w, ray_parquet_t* r, uint32_t worker) { + if ((int64_t)worker < w->dw->nspare) pq_trade_buffers(&r->cursors[0],&w->dw->spare[worker]); + ray_parquet_close(r); +} +/* The chunk read ahead again for the second decode (and the same column's + * next chunks), whatever the first asked for. */ +static void pq_g_prefetch(pq_direct_work* w, int64_t g, int64_t c) { + if (!w->prefetched) return; + ray_parquet_t* r = w->parent; + int64_t ahead = 0; + for (int64_t k = 0; k <= w->prefetch && g + k < r->ngroups; k++) { + int64_t i = (g+k)*r->ncols+c, lo = w->chunk_lo[i], hi = w->chunk_hi[i]; + if (lo < 0) continue; + if (k > 0 && (ahead += hi - lo) > w->ahead_bytes) break; + ray_vm_advise_willneed(r->map + lo,(size_t)(hi-lo)); + } +} + +/* The calling thread's major faults, read and written bytes and time + * (the trace's split; zero without it). */ +static pq_tio_t pq_tio_now(bool on) { + pq_tio_t io = {0}; + if (!on) return io; + io.ns = ray_profile_now_ns(); + ray_io_counters_t c; + ray_io_counters(true,&c); + io.majflt = c.majflt; io.rd = c.rd; io.wr = c.wr; + return io; +} +static void pq_tio_add(pq_gwork* w, int part, pq_tio_t a, pq_tio_t b) { + if (!w->trace) return; + atomic_fetch_add_explicit(&w->split[part][0],b.ns-a.ns,memory_order_relaxed); + atomic_fetch_add_explicit(&w->split[part][1],b.majflt-a.majflt,memory_order_relaxed); + atomic_fetch_add_explicit(&w->split[part][2],b.rd-a.rd,memory_order_relaxed); + atomic_fetch_add_explicit(&w->split[part][3],b.wr-a.wr,memory_order_relaxed); +} + +/* The worker's buffers into the task, and back after it. */ +static pq_gscratch* pq_g_scratch(pq_gwork* w, uint32_t worker, pq_gtask* k) { + pq_gscratch* ws = (int64_t)worker < w->nws ? &w->ws[worker] : NULL; + if (ws) { k->d = ws->d; k->dmap = ws->dmap; k->dcap = ws->dcap; } + return ws; +} +static void pq_g_scratch_back(pq_gscratch* ws, pq_gtask* k) { + if (ws) { ws->d = k->d; ws->dmap = k->dmap; ws->dcap = k->dcap; } + else { pq_dedup_free(&k->d); ray_free_raw(k->dmap); } +} + +/* First decode of row group g: stage its distinct strings. */ +static void pq_g1_task(void* ptr, uint32_t worker, int64_t start, int64_t end) { + pq_gwork* w = ptr; pq_direct_work* dw = w->dw; + for (int64_t g = start; g < end; g++) { + if (dw->prefetched) pq_prefetch_chunks(dw,g,w->c); + pq_gtask k = {.w = w, .t = g, .worker = worker}; + pq_gscratch* ws = pq_g_scratch(w,worker,&k); + const char* err = NULL; + int64_t bad = -1; /* the column, for its decode errors */ + ray_parquet_t* r = pq_g_reader(w,g,worker,&err,&bad); + if (!err && !pq_dedup_reset(&k.d,w->acap,w->counts)) err = "symbol dedupe allocation failed"; + if (!err && pq_g_inject("r1")) err = "symbol dedupe allocation failed"; + if (!err && r->group_left) { + pq_schema schema = r->schema[w->c]; schema.import_domain = NULL; + err = pq_g_walk(&r->cursors[0],&schema,r->group_left,&k); + if (err) bad = w->c; + } + if (!err) atomic_fetch_add_explicit(&w->rows,r->group_rows,memory_order_relaxed); + if (!err && !ray_symgrp_stage(w->g,g,k.d.n,k.d.fp,k.d.cnt ? k.d.cnt+1 : NULL)) + err = "symbol staging allocation failed"; + atomic_fetch_add_explicit(&w->gens,k.d.gens,memory_order_relaxed); + if (err && !dw->errors[g]) { dw->errors[g] = pq_g_error(dw->parent,err,bad); pq_task_msg_note(dw->emsg,g); } + pq_g_scratch_back(ws,&k); + if (r) pq_g_reader_close(w,r,worker); } } +/* Second decode of row group g: records, comparisons, codes. */ +static void pq_g2_task(void* ptr, uint32_t worker, int64_t start, int64_t end) { + pq_gwork* w = ptr; pq_direct_work* dw = w->dw; + for (int64_t i = start; i < end; i++) { + int64_t g = w->redo ? i : w->ta+i; /* a redo is given its task itself */ + pq_tio_t io0 = pq_tio_now(w->trace), io1 = io0, io2 = io0; + pq_g_prefetch(dw,g,w->c); + pq_gtask k = {.w = w, .t = g, .worker = worker, .second = true}; + pq_gscratch* ws = pq_g_scratch(w,worker,&k); + ray_col_stream_t local = {0}; + const char* err = NULL; + int64_t n = ray_symgrp_task_size(w->g,g); + k.nres = n; + int64_t bad = -1; /* the column, for its decode errors */ + ray_parquet_t* r = pq_g_reader(w,g,worker,&err,&bad); + if (ws && ws->rcap < n+1) { + ray_symgrp_res_t* res = ray_realloc_raw(ws->res,(size_t)(n+1)*sizeof(*res)); + if (res) ws->res = res; + uint32_t* map = res ? ray_realloc_raw(ws->map,(size_t)(n+1)*sizeof(*map)) : NULL; + if (map) { ws->map = map; ws->rcap = n+1; } + } + if (ws && !ws->vec) { + ray_t* v = ray_sym_vec_new(RAY_SYM_W32,PQ_BATCH); + if (v && !RAY_IS_ERR(v)) { v->sym_domain = dw->writers[w->c].dom; ray_sym_domain_retain(v->sym_domain); ws->vec = v; } + else if (v) ray_release(v); + } + if (ws && !ws->wbuf) ws->wbuf = ray_alloc_raw((size_t)PQ_GWBUF*2); + if (ws && ws->rcap >= n+1) { k.res = ws->res; k.map = ws->map; } + if (ws) { k.vec = ws->vec; k.wbuf[0] = ws->wbuf; k.wbuf[1] = ws->wbuf ? ws->wbuf + PQ_GWBUF : NULL; } + if (!err && (!ws || !k.res || !k.map || !k.vec || !k.wbuf[0] || !pq_dedup_reset(&k.d,w->acap,false))) + err = "symbol code allocation failed"; + if (!err && pq_g_inject("r2")) err = "symbol code allocation failed"; + if (!err) (void)pq_g_inject("cancel"); /* the walk below sees it */ + if (!err && !ray_symgrp_task(w->g,g,k.res)) err = "symbol verdicts unavailable"; + io1 = pq_tio_now(w->trace); + if (!err) { + k.map[0] = 0; + k.cursor[0] = ray_symgrp_task_off(w->g,g,false); + k.cursor[1] = ray_symgrp_task_off(w->g,g,true); + k.codes = (uint32_t*)ray_data(k.vec); + k.ncodes = 0; + local.type = RAY_SYM; local.dom = dw->writers[w->c].dom; + local.fp = fopen(dw->writers[w->c].tmp_path,"r+b"); + if (!local.fp) err = "cannot open native column"; + } + if (!err) { + int64_t offset = 32+dw->offsets[g]*4; +#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) err = "cannot seek native output range"; + } + k.out = &local; + if (!err && r->group_left) { + pq_schema schema = r->schema[w->c]; schema.import_domain = NULL; + err = pq_g_walk(&r->cursors[0],&schema,r->group_left,&k); + if (err) bad = w->c; + } + if (!err && !pq_g_wflush(&k)) err = "symbol file write failed"; + io2 = pq_tio_now(w->trace); + if (!err && !pq_g_flush(&k)) err = "native column write failed"; + if (!err && dw->writeback) { + if (fflush(local.fp) != 0) err = "native column write failed"; + else ray_file_writeback_start(fileno(local.fp),32+dw->offsets[g]*4,(dw->offsets[g+1]-dw->offsets[g])*4); + } + if (local.fp && fclose(local.fp) && !err) err = "native column close failed"; + local.fp = NULL; + ray_col_stream_abort(&local); /* frees what an append made; no file of its own */ + if (!err && local.rows != dw->offsets[g+1]-dw->offsets[g]) err = "row group ended before its assigned output range"; + if (local.had_nulls) atomic_store_explicit(&dw->nulls[w->c],1,memory_order_relaxed); + if (err && !dw->errors[g]) { dw->errors[g] = pq_g_error(dw->parent,err,bad); pq_task_msg_note(dw->emsg,g); } + ray_symgrp_note(w->g,k.cmp,k.cmpb); + pq_g_scratch_back(ws,&k); + if (r) pq_g_reader_close(w,r,worker); + if (w->trace) { + pq_tio_t io3 = pq_tio_now(true); + if (!io2.ns) io2 = io3; + pq_tio_add(w,PQ_GS_VERDICTS,io0,io1); + pq_tio_add(w,PQ_GS_WALK,io1,io2); + pq_tio_add(w,PQ_GS_FINISH,io2,io3); + } + } +} + +/* The process's I/O counters (ray_io_counters), for the trace's phase lines. */ +typedef struct { int64_t rd, wr, syscr, syscw, majflt; } pq_io_t; +static pq_io_t pq_io_now(void) { + ray_io_counters_t c; + ray_io_counters(false,&c); + return (pq_io_t){c.rd,c.wr,c.syscr,c.syscw,c.majflt}; +} +static void pq_io_print(const char* phase, pq_io_t a, pq_io_t b, int64_t t0, int64_t t1) { + fprintf(stderr," %s=%.1fms rd=%.1fMB wr=%.1fMB syscr=%lld syscw=%lld majflt=%lld",phase, + (double)(t1-t0)/1e6,(double)(b.rd-a.rd)/1048576.0,(double)(b.wr-a.wr)/1048576.0, + (long long)(b.syscr-a.syscr),(long long)(b.syscw-a.syscw),(long long)(b.majflt-a.majflt)); +} + +/* One symbol column, grouped: errors land in dw->errors by row group. */ +static void pq_sym_grouped(pq_direct_work* dw, ray_symgrp_t* g, ray_symimp_t* imp, int64_t c, + int groups, int64_t budget, int64_t workers, bool trace) { + ray_parquet_t* r = dw->parent; + ray_pool_t* pool = ray_pool_get(); + pq_gwork w = {.dw = dw, .c = c, .g = g, .imp = imp, .hmask = UINT64_MAX}; + w.acap = budget/4/workers; + if (w.acap < ((int64_t)4 << 20)) w.acap = (int64_t)4 << 20; + w.counts = ray_symgrp_order(g) == RAY_SYMGRP_FREQ; +#if defined(DEBUG) + { + const char* e = getenv("RAY_PQ_SYM_HASH_BITS"); + if (e && *e) { long b = strtol(e,NULL,10); w.hmask = b <= 0 ? 0 : b >= 64 ? UINT64_MAX : (UINT64_C(1) << b) - 1; } + /* or its top bits (the hash groups' and logs' own): collisions in + * every group, not only the first */ + e = getenv("RAY_PQ_SYM_HASH_TOP"); + if (e && *e) { long b = strtol(e,NULL,10); w.hmask = b <= 0 ? 0 : b >= 64 ? UINT64_MAX : ~((UINT64_C(1) << (64 - b)) - 1); } + e = getenv("RAY_PQ_SYM_ARENA"); + if (e && *e && strtol(e,NULL,10) > 0) w.acap = strtol(e,NULL,10); + } +#endif + atomic_init(&w.rows,0); atomic_init(&w.gens,0); + w.trace = trace; + for (int p = 0; p < PQ_GS_N; p++) for (int q = 0; q < 4; q++) atomic_init(&w.split[p][q],0); + int64_t tasks = r->ngroups; + pq_io_t io0 = {0}, io1 = {0}, io2 = {0}, io3 = {0}; + int64_t t0 = 0, t1 = 0, t2 = 0, t3 = 0; + if (trace) { io0 = pq_io_now(); t0 = ray_profile_now_ns(); } + w.ws = (pq_gscratch*)ray_sys_alloc((size_t)workers*sizeof(pq_gscratch)); /* zero-filled */ + w.nws = w.ws ? workers : 0; + /* the strings earlier direct passes added, into the index first */ + if (!w.ws || !ray_symgrp_adopt(g,w.hmask) || !ray_symgrp_begin(g,tasks,groups,workers)) { dw->errors[0] = ray_error("oom",NULL); goto out; } + /* first decode */ + if (tasks > 0) { + if (ray_pool_par_dispatch_ok(pool,tasks,2)) ray_pool_dispatch_n(pool,pq_g1_task,&w,(uint32_t)tasks); + else pq_g1_task(&w,0,0,tasks); + } + for (int64_t t = 0; t < tasks; t++) if (dw->errors[t]) goto out; + if (ray_interrupted()) goto out; + if (trace) { io1 = pq_io_now(); t1 = ray_profile_now_ns(); } + /* the verdicts, group by group */ + if (pq_g_inject("p2") || !ray_symgrp_resolve(g)) { dw->errors[0] = pq_g_error(dw->parent,"symbol dictionary allocation or file growth failed",-1); goto out; } + if (trace) { io2 = pq_io_now(); t2 = ray_profile_now_ns(); } + /* second decode, window by window: the candidates' records of a window + * (from earlier passes and windows) in half the budget */ + int64_t store = budget/2 < ((int64_t)16 << 20) ? (int64_t)16 << 20 : budget/2; +#if defined(DEBUG) + { + const char* e = getenv("RAY_PQ_SYM_WINDOW"); + if (e && *e && strtol(e,NULL,10) > 0) store = strtol(e,NULL,10); + } +#endif + for (int64_t ta = 0; ta < tasks;) { + int64_t tb = ray_symgrp_window(g,ta,store); + pq_tio_t la = pq_tio_now(trace); + if (pq_g_inject("load") || !ray_symgrp_load(g,ta,tb)) { dw->errors[ta] = pq_g_error(dw->parent,"symbol record load failed",-1); goto out; } + pq_tio_add(&w,PQ_GS_LOAD,la,pq_tio_now(trace)); + w.ta = ta; w.tb = tb; w.redo = false; + if (ray_pool_par_dispatch_ok(pool,tb-ta,2)) ray_pool_dispatch_n(pool,pq_g2_task,&w,(uint32_t)(tb-ta)); + else pq_g2_task(&w,0,0,tb-ta); + for (int64_t t = ta; t < tb; t++) if (dw->errors[t]) goto out; + if (ray_interrupted()) goto out; + int64_t* redo = NULL; int64_t nredo = 0; + pq_tio_t sa = pq_tio_now(trace); + if (pq_g_inject("settle") || !ray_symgrp_settle(g,&redo,&nredo)) { dw->errors[ta] = pq_g_error(dw->parent,"symbol comparison failed",-1); goto out; } + pq_tio_add(&w,PQ_GS_SETTLE,sa,pq_tio_now(trace)); + /* the tasks whose deferred candidates did not match: their codes again */ + w.redo = true; + for (int64_t i = 0; i < nredo && !dw->errors[redo[i]]; i++) pq_g2_task(&w,0,redo[i],redo[i]+1); + ray_sys_free(redo); + for (int64_t t = ta; t < tb; t++) if (dw->errors[t]) goto out; + ray_symgrp_writeback(g,ta,tb); /* the window's records start to disk */ + ta = tb; + } + /* the pass written: the header's count, and its records read at random + * from now on (ray_symimp_sync) */ + (void)ray_symimp_sync(imp,false); + if (trace) { + io3 = pq_io_now(); t3 = ray_profile_now_ns(); + ray_symgrp_stats_t st; + ray_symgrp_stats(g,&st); + int64_t arena = 0; /* the workers' dedupe arenas, as grown */ + for (int64_t i = 0; i < w.nws; i++) arena += w.ws[i].d.acap; + ray_t* nm = ray_sym_str(r->schema[c].name); + static const char* orders[] = {"rows","shards","freq","rowsflat"}; + fprintf(stderr,"parquet symgrp: col=%.*s order=%s groups=%d windows=%lld rows=%lld gens=%lld staged=%lld stage_mb=%.1f arena_mb=%.1f arena_kb=%lld" + " owners=%lld again=%lld again_mb=%.1f old=%lld refs=%lld log_loaded=%lld budget_mb=%.0f store_cap_mb=%.0f store_pos=%lld store_spans=%lld store_mb=%.1f" + " store_read_mb=%.1f store_kept=%lld deferred=%lld settle_read_mb=%.1f compares=%lld cmp_mb=%.1f collisions=%lld redo=%lld entries=%lld rec_bytes=%lld wb_bytes=%lld adopted=%lld imp_index_kb=%lld\n", + (int)ray_str_len(nm),ray_str_ptr(nm),orders[ray_symgrp_order(g)],groups,(long long)st.windows, + (long long)atomic_load(&w.rows),(long long)atomic_load(&w.gens),(long long)st.staged,(double)st.stage_bytes/1048576.0,(double)arena/1048576.0,(long long)(arena/1024), + (long long)st.owners,(long long)st.again,(double)st.again_bytes/1048576.0,(long long)st.old,(long long)st.refs,(long long)st.log_loaded, + (double)budget/1048576.0,(double)store/1048576.0, + (long long)st.store_pos,(long long)st.store_spans,(double)st.store_bytes/1048576.0, + (double)st.store_read/1048576.0,(long long)st.store_kept, + (long long)st.deferred,(double)st.settle_read/1048576.0,(long long)st.compares,(double)st.cmp_bytes/1048576.0, + (long long)st.collisions,(long long)st.redo,(long long)ray_symgrp_entries(g), + (long long)st.rec_bytes,(long long)st.wb_bytes,(long long)st.adopted, + (long long)(ray_symimp_index_bytes(imp)/1024)); + fprintf(stderr,"parquet symgrp io:"); + pq_io_print("decode1",io0,io1,t0,t1); + pq_io_print("resolve",io1,io2,t1,t2); + pq_io_print("decode2",io2,io3,t2,t3); + fprintf(stderr,"\n"); + /* where decode2's time, faults and bytes go (the tasks' parts summed + * over the workers; the windows' load and settle on this thread) */ + static const char* parts[PQ_GS_N] = {"verdicts","walk","finish","load","settle"}; + fprintf(stderr,"parquet symgrp split:"); + for (int p = 0; p < PQ_GS_N; p++) + fprintf(stderr," %s=%.1fms/%lldflt/%.1fMBr/%.1fMBw",parts[p], + (double)atomic_load(&w.split[p][0])/1e6,(long long)atomic_load(&w.split[p][1]), + (double)atomic_load(&w.split[p][2])/1048576.0,(double)atomic_load(&w.split[p][3])/1048576.0); + fprintf(stderr,"\n"); + } +out: + for (int64_t i = 0; i < w.nws; i++) { + pq_gscratch* s = &w.ws[i]; + pq_dedup_free(&s->d); ray_free_raw(s->dmap); ray_free_raw(s->res); ray_free_raw(s->map); + ray_free_raw(s->wbuf); + if (s->vec) ray_release(s->vec); + } + ray_sys_free(w.ws); +} + +/* The import runs in passes, each decoding some columns' chunks from every + * row group in parallel. When memory is short next to the output it goes + * column by column (a pass is one column, or a few when the file has fewer + * row groups than the pool has workers): one column file is written at a + * time instead of all of them at once. Numeric and temporal columns go + * first and are closed as soon as their pass ends, their hash index built + * while the file is still in the page cache; symbol columns follow in + * passes of their own, smallest first, so the file domain only grows once + * the other columns are done. With memory to spare one pass takes every + * column, and the columns close and are indexed together after it, as the + * row-group import does. Symbol columns close with the domain, after its + * flush. */ 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 chunks = r->ngroups*r->ncols; + if (chunks > 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** errors = ray_calloc_raw((size_t)(chunks+1)*sizeof(*errors)); + int64_t* lo = ray_alloc_raw((size_t)(chunks+1)*sizeof(*lo)); + int64_t* hi = ray_alloc_raw((size_t)(chunks+1)*sizeof(*hi)); + int64_t* bytes = ray_calloc_raw((size_t)r->ncols*sizeof(*bytes)); + int64_t* vocab = ray_calloc_raw((size_t)r->ncols*sizeof(*vocab)); /* pq_vocab_bounds */ + uint8_t* donly = ray_calloc_raw((size_t)r->ncols); /* pq_vocab_bounds */ + uint8_t* pick = ray_calloc_raw((size_t)r->ncols); /* the direct ones of a grouped import */ + int64_t* order = ray_alloc_raw((size_t)r->ncols*sizeof(*order)); + _Atomic uint8_t* prefetched = NULL; + pq_column* spare = NULL; /* pq_direct_work.spare */ + int64_t nspare = 0; + ray_symgrp_t* sgrp = NULL; /* the grouped symbol import, or NULL */ + ray_symimp_t* simp = NULL; ray_t* err = NULL; - if (!offsets || !nulls || !locks || !errors) { err = ray_error("oom",NULL); goto done; } + pq_symflush_t symf = {NULL,false,(int)RAY_OK}; + ray_thread_t sym_thread = 0; + bool sym_running = false; + if (!offsets || !nulls || !locks || !errors || !lo || !hi || !bytes || !vocab || !donly || !pick || !order) { err = ray_error("oom",NULL); goto done; } 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; } @@ -1863,21 +2939,297 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { 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]); + bool ranges = pq_chunk_ranges(r,lo,hi,bytes); + /* numeric columns in schema order, then symbol columns by size */ + int64_t nnum = 0, n = 0; + for (int64_t c = 0; c < r->ncols; c++) if (writers[c].type != RAY_SYM) order[n++] = c; + nnum = n; + for (int64_t c = 0; c < r->ncols; c++) if (writers[c].type == RAY_SYM) { + int64_t j = n++; + for (; j > nnum && bytes[order[j-1]] > bytes[c]; j--) order[j] = order[j-1]; + order[j] = c; } - if (!err && ray_interrupted()) err = ray_error("cancel","parquet conversion interrupted"); + ray_pool_t* pool = ray_pool_get(); + int64_t workers = pool ? (int64_t)ray_pool_total_workers(pool) : 1; + /* The pass layout follows memory: physical RAM or the cgroup limit, + * the page cache the output competes for (not the heap budget of -m). + * Column by column pays off when the output does not fit it with room + * to spare: each column is written and indexed while it is hot, and + * only it is. With plenty of memory one pass over every column keeps + * all the decode work overlapped with the symbol domain's commits and + * wins. RAY_PQ_PASS_COLS forces columns per pass, symbol passes + * included (r->ncols: one pass). */ + int64_t out_bytes = 0; 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; + int64_t b = r->rows*(int64_t)(writers[c].type == RAY_SYM ? 4 : ray_elem_size(writers[c].type)); + out_bytes = b > INT64_MAX - out_bytes ? INT64_MAX : out_bytes + b; + } + int64_t ram = ray_sys_ram_limit(); + bool colwise = ram > 0 && ram / PQ_COLWISE_RATIO < out_bytes; + /* column by column: enough tasks in a pass for the pool, so a file of + * few row groups still takes several columns at once */ + int64_t width = !colwise ? r->ncols + : r->ngroups > 0 ? (2*workers + r->ngroups - 1)/r->ngroups : r->ncols; + if (width < 1) width = 1; + bool forced = false; + { + const char* e = getenv("RAY_PQ_PASS_COLS"); + if (e && *e && strtol(e,NULL,10) > 0) { width = strtol(e,NULL,10); colwise = width < r->ncols; forced = true; } + } + if (width > r->ncols) width = r->ncols; + bool trace = getenv("RAY_CSV_TRACE") != NULL; /* the converters' phase trace */ + spare = ray_calloc_raw((size_t)workers*sizeof(*spare)); /* best effort */ + if (spare) nspare = workers; + pq_task_msg emsg; /* the failed tasks' messages, a pass at a time */ + pq_task_msg_reset(&emsg); + pq_direct_work work = {r,writers,offsets,nulls,locks,errors,NULL,0,lo,hi,NULL,0,0,true,spare,nspare,false,&emsg}; + /* Starting each chunk's writeback as it is written spares one pass its + * final sync; column by column the passes end their files anyway and + * the extra I/O requests only slow the decode. */ + work.writeback = !colwise; +#if defined(DEBUG) + work.reverse = getenv("RAY_PQ_DIRECT_REVERSE") != NULL; /* the suite: positions not in task order */ +#endif + { + const char* e = getenv("RAY_PQ_PREFETCH"); + work.prefetch = (e && *e) ? strtol(e,NULL,10) : 2; + if (work.prefetch > 0 && ranges) { + prefetched = ray_calloc_raw((size_t)chunks+1); + if (prefetched) for (int64_t i = 0; i < chunks; i++) atomic_init(&prefetched[i],0); + work.prefetched = prefetched; + } + /* what the workers keep requested ahead together stays a small + * share of memory */ + int64_t budget = ray_heap_anon_watermark()/16/workers; + work.ahead_bytes = budget < ((int64_t)1 << 20) ? (int64_t)1 << 20 + : budget > ((int64_t)64 << 20) ? (int64_t)64 << 20 : budget; + } + /* Symbol columns: one by one, smallest first, while memory is short + * (the domain they share grows and is probed at random, and a column + * at a time keeps the rest of the working set small); together in one + * pass from half the output's bytes of memory, where their decode then + * overlaps. */ + int64_t sym_width = forced ? width : ram > 0 && ram >= out_bytes / 2 ? r->ncols - nnum : 1; + if (sym_width < 1) sym_width = 1; + /* The symbol columns go direct (each string probes the import + * dictionary) unless their strings would make it too big to probe at + * random: then grouped (table/symgrp.h), column by column. Decided from + * their chunks' uncompressed bytes against a quarter of memory (a chunk + * of no size counting as unbounded: pq_chunk_ranges), and + * then column by column: a column whose vocabulary (pq_vocab_bounds: + * what the direct import would hold for it, at most) is a small share + * of memory still goes direct, decoded once, smallest first while those + * columns' vocabularies stay within a sixteenth together. The direct + * columns go first (the dictionary's index serves only them), the + * grouped ones after them, which take the direct ones' strings into + * their own index (ray_symgrp_adopt). Only a column whose chunks are + * a dictionary page and ids (the encoding stats say so) goes direct so, + * its dictionaries interned in row-group order before the passes + * (pq_seed_dicts): its positions do not depend on the workers, as the + * grouped ones' do not. The import direct throughout (its text within a + * quarter of memory, or RAY_PQ_SYM_MODE=direct) gives positions in the + * order its tasks run, as it always has. + * RAY_PQ_SYM_MODE=direct|grouped decides for every column instead, and + * RAY_PQ_SYM_ORDER (rows|shards|freq|rowsflat) and RAY_PQ_SYM_GROUPS set + * the grouped import's order of new positions and hash groups. Debug + * builds: RAY_PQ_SYM_RAM sets the memory these decisions assume, and + * RAY_PQ_DIRECT_REVERSE runs the direct passes' row groups last to first. */ + pq_sym_mode mode = PQ_SYM_AUTO; + { + const char* e = getenv("RAY_PQ_SYM_MODE"); + if (e && !strcmp(e,"direct")) mode = PQ_SYM_DIRECT; + else if (e && !strcmp(e,"grouped")) mode = PQ_SYM_GROUPED; + } + int64_t sram = ram; +#if defined(DEBUG) + { + const char* e = getenv("RAY_PQ_SYM_RAM"); + if (e && *e && strtoll(e,NULL,10) > 0) sram = strtoll(e,NULL,10); + } +#endif + simp = nnum < r->ncols ? ray_sym_domain_import(writers[order[nnum]].dom) : NULL; + int64_t nd = r->ncols; /* order[nnum, nd): direct symbol columns, [nd, ncols): grouped */ + bool bounded = false; /* vocab[] filled (pq_vocab_bounds) */ + bool seed = false; /* direct columns of a grouped import: pq_seed_dicts */ + if (mode == PQ_SYM_AUTO && simp) { + int64_t text = 0; + for (int64_t i = nnum; i < r->ncols; i++) text = bytes[order[i]] > INT64_MAX - text ? INT64_MAX : text + bytes[order[i]]; + mode = sram > 0 && text > sram / 4 ? PQ_SYM_GROUPED : PQ_SYM_DIRECT; + if (mode == PQ_SYM_GROUPED) { pq_vocab_bounds(r,order,nnum,r->ncols,vocab,donly); bounded = true; } + if (mode == PQ_SYM_GROUPED) { + /* the direct ones (only columns whose chunks are dictionaries and + * ids: their dictionaries seeded in row-group order make their + * positions the workers' no matter), marked in pick[] (the + * bounds are never negative, saturating at INT64_MAX) */ + int64_t sum = 0, ndirect = 0; + for (;;) { + int64_t best = -1; + for (int64_t i = nnum; i < r->ncols; i++) { + int64_t c = order[i]; + if (!pick[c] && donly[c] && (best < 0 || vocab[c] < vocab[best])) best = c; + } + if (best < 0 || vocab[best] > sram / 64 || vocab[best] > sram / 16 - sum) break; + sum += vocab[best]; pick[best] = 1; ndirect++; + } + seed = ndirect > 0; + if (ndirect == r->ncols - nnum) mode = PQ_SYM_DIRECT; + else { + /* direct first, each part by size as before (a stable split) */ + int64_t at = nnum; + for (int64_t i = nnum; i < r->ncols; i++) { + int64_t c = order[i]; + if (!pick[c]) continue; + for (int64_t j = i; j > at; j--) order[j] = order[j-1]; + order[at++] = c; + } + nd = at; + } + } + } + if (mode == PQ_SYM_GROUPED && simp) { + ray_symgrp_order_t so = RAY_SYMGRP_ROWS; + const char* e = getenv("RAY_PQ_SYM_ORDER"); + if (e && !strcmp(e,"shards")) so = RAY_SYMGRP_SHARDS; + else if (e && !strcmp(e,"freq")) so = RAY_SYMGRP_FREQ; + else if (e && !strcmp(e,"rowsflat")) so = RAY_SYMGRP_ROWS_FLAT; + sgrp = ray_symgrp_new(simp,so); + if (!sgrp) { err = ray_error("oom",NULL); goto done; } + if (nd == r->ncols) nd = nnum; /* forced: every symbol column grouped */ + } else nd = r->ncols; + int64_t seeded = -1, seed0 = 0; /* the trace's: the dictionary's count after the seeding, and before */ + if (seed) { + int64_t ts = trace ? ray_profile_now_ns() : 0, entries = 0; + int64_t bad_col; + seed0 = ray_symimp_count(simp); + const char* se = pq_seed_dicts(r,order,nnum,nd,&entries,&bad_col); + if (se) { err = pq_col_error(r,se,bad_col); goto done; } + seeded = ray_symimp_count(simp); + if (trace) fprintf(stderr,"parquet symseed: cols=%lld groups=%lld entries=%lld ms=%.1f\n",(long long)(nd-nnum), + (long long)r->ngroups,(long long)entries,(double)(ray_profile_now_ns()-ts)/1e6); + } + if (trace && simp && !bounded) pq_vocab_bounds(r,order,nnum,r->ncols,vocab,donly); /* for the trace */ + if (trace && simp) + for (int64_t i = nnum; i < r->ncols; i++) { + ray_t* nm = ray_sym_str(r->schema[order[i]].name); + fprintf(stderr,"parquet symcol: col=%.*s text_mb=%.3f text_bytes=%lld vocab_mb=%.3f vocab_bytes=%lld dict_only=%d mode=%s\n", + (int)ray_str_len(nm),ray_str_ptr(nm),(double)bytes[order[i]]/1048576.0,(long long)bytes[order[i]], + (double)vocab[order[i]]/1048576.0,(long long)vocab[order[i]],(int)donly[order[i]],i < nd ? "direct" : "grouped"); + } + if (!sgrp && nnum < r->ncols && writers[order[nnum]].dom) { + symf.dom = writers[order[nnum]].dom; + if (ray_thread_create(&sym_thread,pq_symflush_fn,&symf) == RAY_OK) sym_running = true; + } + ray_symimp_stats_t ist; /* the import dictionary's counts, per pass */ + if (trace && symf.dom) ray_sym_domain_import_stats(symf.dom,&ist); + bool all = !colwise && !sgrp; + for (int64_t p = 0; p < r->ncols && !err; p += work.npass) { + int64_t wd = all ? r->ncols : p < nnum ? width : p < nd ? sym_width : 1; + int64_t lim = all ? r->ncols : p < nnum ? nnum : p < nd ? nd : r->ncols; + work.pass = order + p; + work.npass = lim - p < wd ? lim - p : wd; + int64_t tasks = r->ngroups*work.npass; + int64_t t0 = trace ? ray_profile_now_ns() : 0, t1 = 0; + if (sgrp && p >= nd) { + /* memory for the pass: what is left under the anon watermark */ + int64_t wm = ray_heap_anon_watermark(); + int64_t budget = wm > 0 ? wm - ray_heap_anon_committed() : (int64_t)1 << 30; + if (budget < ((int64_t)64 << 20)) budget = (int64_t)64 << 20; + /* hash groups: a group's index table (~24 B an entry, the + * column's rows bounding its new strings) within a quarter. The + * budget is the memory free when the pass starts, so the groups + * are too: under RAY_PQ_SYM_ORDER=shards, which numbers the new + * strings group by group, the positions depend on it (the + * default order does not) */ + int groups = 1; + const char* e = getenv("RAY_PQ_SYM_GROUPS"); + if (e && *e && strtol(e,NULL,10) > 0) groups = (int)strtol(e,NULL,10); + else { + int64_t need = (ray_symgrp_entries(sgrp) + r->rows) * 24; + while (groups < RAY_SYMGRP_MAX && need / groups > budget / 4) groups *= 2; + } + pq_sym_grouped(&work,sgrp,simp,work.pass[0],groups,budget,workers,trace); + } else if (tasks > 0) { + if (ray_pool_par_dispatch_ok(pool,tasks,2)) ray_pool_dispatch_n(pool,pq_write_direct_group,&work,(uint32_t)tasks); + else pq_write_direct_group(&work,0,0,tasks); + } + /* errors[0] even with no tasks: a grouped pass over a file of no row + * groups still runs its steps, and reports there */ + for (int64_t t = 0; t < (tasks > 0 ? tasks : 1); t++) if (errors[t]) { + if (!err) err = pq_task_msg_raise(&emsg,t,errors[t]); else ray_error_free(errors[t]); + errors[t] = NULL; + } + pq_task_msg_reset(&emsg); + if (!err && ray_interrupted()) err = ray_error("cancel","parquet conversion interrupted"); + if (!err && atomic_load_explicit(&symf.err,memory_order_acquire) != RAY_OK) + err = ray_error(ray_err_code_str((ray_err_t)atomic_load(&symf.err)),"parquet: cannot flush symbol file"); + if (err) break; + /* a seeded column's strings the seeding did not see (stats that + * leave out a PLAIN page): their positions are the workers' */ + if (trace && seeded >= 0 && p < nd && p + work.npass >= nd) + fprintf(stderr,"parquet symdirect: cols=%lld seeded=%lld seed_miss=%lld\n",(long long)(nd-nnum), + (long long)(seeded-seed0),(long long)(ray_symimp_count(simp)-seeded)); + if (trace) t1 = ray_profile_now_ns(); + for (int64_t i = 0; i < work.npass; i++) { + int64_t c = work.pass[i]; + writers[c].rows = r->rows; + writers[c].had_nulls = atomic_load_explicit(&nulls[c],memory_order_relaxed) != 0; + if (all || writers[c].type == RAY_SYM) continue; + ray_err_t e = ray_col_stream_close(&writers[c],false); + if (e != RAY_OK) { err = ray_error(ray_err_code_str(e),"parquet: column close failed"); break; } + ray_col_stream_hash_one(&writers[c]); + } + /* the workers' page and dictionary buffers grown past PQ_SPARE_MAX + * for this pass's columns go with the pass */ + for (int64_t i = 0; i < nspare; i++) { + if (spare[i].page_cap > PQ_SPARE_MAX) { ray_free_raw(spare[i].page); spare[i].page = NULL; spare[i].page_cap = 0; } + if (spare[i].dict_cap > PQ_SPARE_MAX) { ray_free_raw(spare[i].dict); spare[i].dict = NULL; spare[i].dict_cap = 0; } + } + if (trace && !err) { + ray_t* nm = ray_sym_str(r->schema[work.pass[0]].name); + fprintf(stderr,"parquet pass: first=%.*s cols=%lld %s decode=%.1fms close=%.1fms\n", + (int)ray_str_len(nm),ray_str_ptr(nm),(long long)work.npass, + writers[work.pass[0]].type == RAY_SYM ? "sym" : "num", + (double)(t1-t0)/1e6,(double)(ray_profile_now_ns()-t1)/1e6); + if (symf.dom && ray_sym_domain_import_stats(symf.dom,&ist) && ist.strings) + fprintf(stderr,"parquet symimp: strings=%lld dedup=%lld probes=%lld hits=%lld added=%lld" + " slots=%lld false_tags=%lld grows=%lld grow_mb=%.1f" + " entries=%lld rec_mb=%.1f tab_mb=%.1f offc_mb=%.1f\n", + (long long)ist.strings,(long long)ist.dedup,(long long)ist.probes, + (long long)ist.hits,(long long)ist.added,(long long)ist.slots, + (long long)ist.false_tags,(long long)ist.grows,(double)ist.grow_bytes/1048576.0, + (long long)ist.count,(double)ist.rec_bytes/1048576.0, + (double)ist.tab_bytes/1048576.0,(double)ist.off_bytes/1048576.0); + } + } + /* One pass: the columns finish side by side and their hash indexes are + * built in waves while the symbol file appender is still writing (its + * writeback can wait on the column data's); a symbol column's header + * takes the domain's final count, which no longer changes. The + * column-by-column passes have closed and indexed theirs already. */ + if (all && !err) { + int64_t tc = trace ? ray_profile_now_ns() : 0; + ray_err_t e = ray_col_stream_close_all(writers,r->ncols,false,NULL); + if (e != RAY_OK) err = ray_error(ray_err_code_str(e),"parquet: column close failed"); + else ray_col_stream_hash_all(writers,r->ncols,NULL); + if (trace) fprintf(stderr,"parquet phase: close+hash=%.1fms\n",(double)(ray_profile_now_ns()-tc)/1e6); + } + if (sym_running) { + atomic_store_explicit(&symf.stop,true,memory_order_release); + ray_thread_join(sym_thread); + if (!err && atomic_load(&symf.err) != RAY_OK) + err = ray_error(ray_err_code_str((ray_err_t)atomic_load(&symf.err)),"parquet: cannot flush symbol file"); } 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_free_raw(offsets); ray_free_raw(nulls); ray_free_raw(locks); ray_free_raw(errors); + ray_free_raw(lo); ray_free_raw(hi); ray_free_raw(bytes); ray_free_raw(vocab); ray_free_raw(donly); ray_free_raw(pick); ray_free_raw(order); + if (prefetched) ray_free_raw((void*)prefetched); + for (int64_t i = 0; i < nspare; i++) { + ray_free_raw(spare[i].page); ray_free_raw(spare[i].dict); ray_free_raw(spare[i].symbols); + } + ray_free_raw(spare); + ray_symgrp_free(sgrp); + return err; } ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types) { #ifdef RAY_FUZZING @@ -1899,7 +3251,13 @@ ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types 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); + /* The direct import (no STR column) builds the symbol file with the + * import dictionary: strings go straight into the mapped file. */ + bool str_cols = false; + for (int64_t k = 0; k < r->ncols; k++) + if (!r->schema[k].native_symbol && r->schema[k].type == RAY_STR) str_cols = true; + if (!str_cols) domain = ray_sym_domain_create_import(file); + if (!domain) domain = ray_sym_domain_open_or_create(file); if (!domain) { err = ray_error("oom",NULL); goto done; } if (ray_sym_domain_intern(domain,"",0) != 0) { err = pq_error("cannot initialize native symbol domain"); goto done; } } @@ -1914,6 +3272,8 @@ ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types } bool direct = true; for (int64_t c = 0; c < r->ncols; c++) if (writers[c].type == RAY_STR) direct = false; + bool trace = getenv("RAY_CSV_TRACE") != NULL; + int64_t tp = trace ? ray_profile_now_ns() : 0; if (direct) { err = pq_write_direct(r,writers); if (err) goto done; @@ -1948,21 +3308,29 @@ ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types } 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 + if (trace) { fprintf(stderr,"parquet phase: passes=%.1fms\n",(double)(ray_profile_now_ns()-tp)/1e6); tp = ray_profile_now_ns(); } + /* the direct import appended the symbols as they came: this writes + * what is left and syncs the file */ + if (domain) { e = ray_sym_domain_flush_append(domain,true); if (e != RAY_OK) goto io_fail; } + if (trace) { fprintf(stderr,"parquet phase: sym flush=%.1fms\n",(double)(ray_profile_now_ns()-tp)/1e6); tp = ray_profile_now_ns(); } + /* All columns are still under a private staging directory (the direct + * import has closed and indexed them already, but for the symbol + * columns of its column-by-column passes). Commit their final images + * together below, after the hash re-read of any column left. Every * 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 + * ingestion hash tables and string arena before any hash re-read of the * integer columns; reopening needs only the file-backed vocabulary. */ if (domain) { ray_sym_domain_release(domain); domain = NULL; for (int64_t c = 0; c < opened; c++) writers[c].dom = NULL; } + if (trace) { fprintf(stderr,"parquet phase: close=%.1fms\n",(double)(ray_profile_now_ns()-tp)/1e6); tp = ray_profile_now_ns(); } ray_col_stream_hash_all(writers,r->ncols,NULL); + if (trace) { fprintf(stderr,"parquet phase: hash=%.1fms\n",(double)(ray_profile_now_ns()-tp)/1e6); tp = ray_profile_now_ns(); } ray_t* schema = ray_vec_new(RAY_STR,r->ncols); if (!schema || RAY_IS_ERR(schema)) { err = schema ? schema : ray_error("oom",NULL); goto done; } for (int64_t c = 0; c < r->ncols; c++) { @@ -1984,6 +3352,7 @@ ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types e = ray_file_sync(fd); ray_file_close(fd); if (e != RAY_OK) goto io_fail; } + if (trace) { fprintf(stderr,"parquet phase: schema+sync=%.1fms\n",(double)(ray_profile_now_ns()-tp)/1e6); tp = ray_profile_now_ns(); } e = ray_file_sync_dir(file); if (e != RAY_OK) goto io_fail; err = pq_publish(staging,dir,r->rows); @@ -2256,20 +3625,22 @@ typedef struct { const uint32_t* gids; const pq_predicate* predicates; ray_t** errors; + pq_task_msg* emsg; /* the failed groups' messages */ } 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); + ray_parquet_t* r = pq_group_reader(w->parent,w->first+i,w->parent->nselected); 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; } + if (!r || !aggs) { w->errors[i] = ray_error("oom",NULL); pq_task_msg_note(w->emsg,i); 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); + if (w->errors[i]) pq_task_msg_note(w->emsg,i); ray_parquet_close(r); } } @@ -2283,13 +3654,15 @@ static ray_t* pq_aggregate_groups(ray_parquet_t* r, pq_aggregate* aggs, int64_t 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; } + pq_task_msg emsg; /* the failed groups' messages, a wave at a time */ 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}; + pq_task_msg_reset(&emsg); + pq_aggregate_work work = {r,first,n,np,aggs,states,gids,predicates,errors,&emsg}; 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 (errors[i]) { if (!err) err = pq_task_msg_raise(&emsg,i,errors[i]); else ray_error_free(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); diff --git a/src/lang/compile.c b/src/lang/compile.c index f37ccfb6f..3a54052d9 100644 --- a/src/lang/compile.c +++ b/src/lang/compile.c @@ -24,6 +24,8 @@ #include "lang/eval.h" #include "lang/env.h" #include "lang/nfo.h" +#include "table/sym.h" /* ray_read_sym — capture names */ +#include "core/block.h" /* ray_block_size — a literal's weight */ #include #include @@ -43,15 +45,28 @@ typedef struct { struct { int64_t sym_id; int32_t slot; } locals[256]; int32_t n_locals; + int32_t n_fixed; /* params: the slots that are always bound */ + bool dynamic_globals; /* a closure body: free names resolve at call + * time (OP_RESOLVE), never a builtin baked at + * compile time, since the template outlives + * any rebinding and any caller's frame */ int32_t max_locals; bool error; ray_t *lambda; /* the lambda being compiled (for 'self' resolution) */ ray_t *dbg_obj; /* I64 vector: pairs of [offset, span.id] */ int32_t trap_depth; /* open OP_TRAP frames in current lambda */ + int32_t depth; /* expression nesting; past the guard the lambda is + * left to the tree walker rather than the C stack */ + ray_t *deps; /* when set (an I64 vector): every call head looked + * up at compile time and the builtin it named (0 + * for anything else), the bindings the bytecode + * depends on (ray_compile_definition) */ } compiler_t; static void compile_expr(compiler_t *c, ray_t *ast); +static bool compile_fn_template(compiler_t *c, ray_t *ast); +static bool compile_lambda(ray_t *lambda, ray_t *capnames, bool dynamic_globals); static bool compiler_init(compiler_t *c) { memset(c, 0, sizeof(*c)); @@ -77,6 +92,7 @@ static void compiler_destroy(compiler_t *c) { if (c->consts[i]) ray_release(c->consts[i]); ray_release(c->consts_obj); ray_release(c->code_obj); + if (c->deps) { ray_release(c->deps); c->deps = NULL; } } /* ── Debug info helpers ── */ @@ -246,7 +262,7 @@ static bool ast_refs_locals(compiler_t *c, ray_t *ast); static bool sym_is_local_ref(compiler_t *c, int64_t id) { if (id == sf_self || id == sf_eval || id == sf_resolve) return true; for (int32_t i = c->n_locals - 1; i >= 0; i--) - if (c->locals[i].sym_id == id) return true; + if (c->locals[i].sym_id == id) return true; /* params, lets, captures */ return false; } static bool ast_refs_locals(compiler_t *c, ray_t *ast) { @@ -284,8 +300,14 @@ static void compile_list(compiler_t *c, ray_t *ast) { init_sf_syms(); + /* A local (parameter, let or capture) named like a special form or a + * builtin is the callee, as it is on the tree walker, where the name + * resolves through the scope frames first. */ + bool head_local = head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && + find_local(c, head->i64) >= 0; + /* Check for special forms by name (name ref = unflagged default) */ - if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED)) { + if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && !head_local) { int64_t sym_id = head->i64; /* (set name value) — bind in the global env. Compile the value @@ -489,33 +511,34 @@ static void compile_list(compiler_t *c, ray_t *ast) { return; } - /* (fn [params] body...) — nested lambda via dynamic eval */ + /* (fn [params] body...) — a closure template compiled once here + * and instantiated per evaluation (OP_MKCLOSURE); the dynamic + * eval below is the fallback when the literal cannot compile. */ if (sym_id == sf_fn && n >= 3) { - if (ast_refs_locals(c, ast)) { - ray_t *syms = ray_alloc((size_t)c->n_locals * sizeof(int64_t)); - if (!syms || RAY_IS_ERR(syms)) { c->error = true; return; } - syms->type = RAY_I64; - syms->len = c->n_locals; - int64_t *ids = (int64_t*)ray_data(syms); - for (int32_t i = 0; i < c->n_locals; i++) - ids[i] = c->locals[i].sym_id; - int32_t syms_idx = add_constant(c, syms); - ray_release(syms); - if (c->error) return; - emit_const(c, syms_idx); - emit(c, OP_SCOPE_BEGIN); - int32_t idx = add_constant(c, ast); - emit_const(c, idx); - emit(c, OP_CALLD); - emit(c, 0); - emit_const(c, syms_idx); - emit(c, OP_SCOPE_END); - return; - } + if (compile_fn_template(c, ast)) return; + if (c->error) return; + /* The literal captures the window, which binds the locals it + * mentions and nothing a caller of this frame had in scope. */ + bool refs = ast_refs_locals(c, ast); + int32_t nsyms = refs ? c->n_locals : 0; + ray_t *syms = ray_alloc((size_t)(nsyms > 0 ? nsyms : 1) * sizeof(int64_t)); + if (!syms || RAY_IS_ERR(syms)) { c->error = true; return; } + syms->type = RAY_I64; + syms->len = nsyms; + int64_t *ids = (int64_t*)ray_data(syms); + for (int32_t i = 0; i < nsyms; i++) + ids[i] = c->locals[i].sym_id; + int32_t syms_idx = add_constant(c, syms); + ray_release(syms); + if (c->error) return; + emit_const(c, syms_idx); + emit(c, OP_SCOPE_EVAL); int32_t idx = add_constant(c, ast); emit_const(c, idx); emit(c, OP_CALLD); emit(c, 0); + emit_const(c, syms_idx); + emit(c, OP_SCOPE_END); return; } @@ -565,7 +588,7 @@ static void compile_list(compiler_t *c, ray_t *ast) { } /* Self-recursive call: emit OP_CALLS (lean frame reuse, no fn object) */ - if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && + if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && !head_local && head->i64 == sf_self) { int64_t argc = n - 1; if (argc > 64) { c->error = true; return; } @@ -578,8 +601,20 @@ static void compile_list(compiler_t *c, ray_t *ast) { /* Look up head at compile time to determine call type */ ray_t *fn = NULL; - if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED)) - fn = ray_env_get(head->i64); + if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && !head_local) { + fn = c->dynamic_globals ? ray_env_get_global(head->i64) : ray_env_get_compiled(head->i64); + if (c->deps && !c->dynamic_globals) { + /* Only a builtin shapes the code (baked, a special form, the + * call opcode); any other value is called through OP_CALLF. */ + bool builtin = fn && (fn->type == RAY_UNARY || fn->type == RAY_BINARY || fn->type == RAY_VARY); + int64_t pair[2] = { head->i64, builtin ? (int64_t)(uintptr_t)fn : 0 }; + for (int k = 0; k < 2 && !c->error; k++) { + c->deps = ray_vec_append(c->deps, &pair[k]); + if (!c->deps || RAY_IS_ERR(c->deps)) { c->deps = NULL; c->error = true; } + } + if (c->error) return; + } + } /* Unrecognized special form: dynamic eval on the entire form. The * special form re-evaluates its argument ASTs via the tree walker, @@ -588,30 +623,25 @@ static void compile_list(compiler_t *c, ray_t *ast) { * at this point (plus self) into a scope frame around the eval, * and sync any let-updates back into the slots afterwards. */ if (fn && (fn->attrs & RAY_FN_SPECIAL_FORM)) { - /* Fast path: a form that mentions no local (the common - * globals-only case) needs no materialization — emit the bare - * dynamic eval exactly as before. */ - if (!ast_refs_locals(c, ast)) { - int32_t idx = add_constant(c, ast); - emit_const(c, idx); - emit(c, OP_CALLD); - emit(c, 0); - return; - } - - ray_t *syms = ray_alloc((size_t)c->n_locals * sizeof(int64_t)); + /* The window binds the locals the form mentions (none in the + * common globals-only case) and marks where the text's scope + * ends: a function the text calls, or a window of whoever called + * this frame, sees none of them (OP_SCOPE_EVAL). */ + bool refs = ast_refs_locals(c, ast); + int32_t nsyms = refs ? c->n_locals : 0; + ray_t *syms = ray_alloc((size_t)(nsyms > 0 ? nsyms : 1) * sizeof(int64_t)); if (!syms || RAY_IS_ERR(syms)) { c->error = true; return; } syms->type = RAY_I64; - syms->len = c->n_locals; + syms->len = nsyms; int64_t *ids = (int64_t*)ray_data(syms); - for (int32_t i = 0; i < c->n_locals; i++) + for (int32_t i = 0; i < nsyms; i++) ids[i] = c->locals[i].sym_id; /* slot i <-> ids[i] */ int32_t syms_idx = add_constant(c, syms); ray_release(syms); if (c->error) return; emit_const(c, syms_idx); - emit(c, OP_SCOPE_BEGIN); + emit(c, OP_SCOPE_EVAL); int32_t idx = add_constant(c, ast); emit_const(c, idx); emit(c, OP_CALLD); @@ -621,10 +651,33 @@ static void compile_list(compiler_t *c, ray_t *ast) { return; } + /* `eval` and `resolve` read names from text at run time: the tree + * walker that serves them resolves through the scope frames, so the + * call runs inside a window that binds this frame's locals, captures + * included, the way a dynamic special form does. */ + int32_t dyn_syms_idx = -1; + if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && !head_local && + (head->i64 == sf_eval || head->i64 == sf_resolve)) { + /* With no locals too: the window still marks where the text's + * scope ends, so a caller's window below it stays hidden. */ + ray_t *syms = ray_alloc((size_t)(c->n_locals > 0 ? c->n_locals : 1) * sizeof(int64_t)); + if (!syms || RAY_IS_ERR(syms)) { c->error = true; return; } + syms->type = RAY_I64; + syms->len = c->n_locals; + int64_t *ids = (int64_t*)ray_data(syms); + for (int32_t i = 0; i < c->n_locals; i++) ids[i] = c->locals[i].sym_id; + dyn_syms_idx = add_constant(c, syms); + ray_release(syms); + if (c->error) return; + } + /* General function call: compile head, args, then dispatch. * If head resolved to a builtin at compile time, emit LOADCONST - * instead of RESOLVE to skip the runtime hash lookup. */ - if (fn && (fn->type == RAY_UNARY || fn->type == RAY_BINARY || fn->type == RAY_VARY)) { + * instead of RESOLVE to skip the runtime hash lookup; a closure body + * resolves at call time instead (dynamic_globals). */ + bool baked = fn && !c->dynamic_globals && + (fn->type == RAY_UNARY || fn->type == RAY_BINARY || fn->type == RAY_VARY); + if (baked) { int32_t idx = add_constant(c, fn); emit_const(c, idx); } else { @@ -638,33 +691,64 @@ static void compile_list(compiler_t *c, ray_t *ast) { /* Record call-site span so errors point to the call expression, not the last arg */ EMIT_DBG(c, ast); - if (fn) { + /* The window opens after the arguments, so their code runs in this + * frame (a `let` or a `return` there is the frame's), and closes right + * after the call. */ + if (dyn_syms_idx >= 0) { + emit_const(c, dyn_syms_idx); + emit(c, OP_SCOPE_EVAL); + } + + bool emitted = false; + if (fn && !baked && c->dynamic_globals) { + /* A closure body resolved the callee above (OP_RESOLVE); while + * the name holds a builtin of the kind it holds now, the call + * takes the fast path, and the general call otherwise. */ + if (fn->type == RAY_UNARY && argc == 1) { emit(c, OP_CALL1R); emit(c, 1); emitted = true; } + else if (fn->type == RAY_BINARY && argc == 2) { emit(c, OP_CALL2R); emit(c, 2); emitted = true; } + else if (fn->type == RAY_VARY) { emit(c, OP_CALLNR); emit(c, (uint8_t)argc); emitted = true; } + } + if (!emitted && fn && (baked || fn->type == RAY_LAMBDA)) { switch (fn->type) { case RAY_UNARY: - if (argc == 1) { emit(c, OP_CALL1); return; } + if (argc == 1) { emit(c, OP_CALL1); emitted = true; } break; case RAY_BINARY: - if (argc == 2) { emit(c, OP_CALL2); return; } + if (argc == 2) { emit(c, OP_CALL2); emitted = true; } break; case RAY_VARY: emit(c, OP_CALLN); emit(c, (uint8_t)argc); - return; + emitted = true; + break; case RAY_LAMBDA: emit(c, OP_CALLF); emit(c, (uint8_t)argc); - return; + emitted = true; + break; default: break; } } - - emit(c, OP_CALLF); - emit(c, (uint8_t)argc); + if (!emitted) { + emit(c, OP_CALLF); + emit(c, (uint8_t)argc); + } + if (dyn_syms_idx >= 0) { + emit_const(c, dyn_syms_idx); + emit(c, OP_SCOPE_END); + } } /* ── Compile expression ── */ +static void compile_expr_at(compiler_t *c, ray_t *ast); static void compile_expr(compiler_t *c, ray_t *ast) { + if (c->error) return; + if (++c->depth > 2048) { c->error = true; c->depth--; return; } + compile_expr_at(c, ast); + c->depth--; +} +static void compile_expr_at(compiler_t *c, ray_t *ast) { if (c->error) return; if (!ast || RAY_IS_ERR(ast)) return; EMIT_DBG(c, ast); @@ -680,9 +764,22 @@ static void compile_expr(compiler_t *c, ray_t *ast) { return; } int32_t slot = find_local(c, ast->i64); - if (slot >= 0) { + if (slot >= 0 && slot < c->n_fixed) { emit(c, OP_LOADENV); emit(c, (uint8_t)slot); + } else if (slot >= 0) { + /* A `let` slot may still be empty when its `let` has not + * run; the tree walker then finds the global of that name + * (or raises a name error), so the load falls back to it. */ + int32_t idx = add_constant(c, ast); + emit(c, OP_LOADENVG); + emit(c, (uint8_t)slot); + emit(c, (uint8_t)(idx >> 8)); + emit(c, (uint8_t)(idx & 0xFF)); + } else if (ast->i64 == sf_self) { + /* `self` as a value is the running lambda, as the tree + * walker binds it in every call frame. */ + emit(c, OP_LOADSELF); } else { int32_t idx = add_constant(c, ast); if (idx < 256) { @@ -717,12 +814,393 @@ static void compile_expr(compiler_t *c, ray_t *ast) { } /* ── Public API ── */ +/* A closure compiles only when its captures have the shape the compiled + * loads assume: SYM keys and a LIST of values of the same length. Anything + * else (a deserialized closure with a typed value vector, say) stays on the + * tree walker, whose capture binding reports the type error. */ +static bool closure_shape_ok(ray_t *closure) { + if (!closure) return true; + if (closure->type != RAY_DICT) return false; + ray_t *keys = ray_dict_keys(closure); + ray_t *vals = ray_dict_vals(closure); + return keys && vals && keys->type == RAY_SYM && vals->type == RAY_LIST && keys->len == vals->len; +} + +/* Every symbol id mentioned anywhere in `ast` (atoms, sym vectors, lists, + * dicts), appended to the I64 vector *out without duplicates. *dynamic is + * set when the text mentions `eval` or `resolve`, which can reach a name + * that is not spelled out. */ +static bool ast_collect_syms_at(ray_t *ast, ray_t **out, bool *dynamic, int depth, int64_t *weight, + bool stop, int64_t *nodes); +/* The nodes a walk for a closure's names visits at most. A large constant + * is one node however many bytes it holds; only text shared over and over + * (a list nested in itself 2^22 times, say) reaches the budget, and the + * caller then treats the names as unknown and binds every capture. */ +enum { AST_NAME_NODES = 1 << 16 }; + +/* Every name `ast` mentions, for a closure's capture set. */ +static bool ast_collect_syms(ray_t *ast, ray_t **out, bool *dynamic) { + int64_t weight = 0, nodes = AST_NAME_NODES; + return ast_collect_syms_at(ast, out, dynamic, 0, &weight, false, &nodes); +} + +/* The bytes a value spliced into text holds whole: a table's columns, a + * lambda's parameters, body and captures, recursively. Shared children + * count each time they are reached (an overestimate), so the walk stops as + * soon as the count passes `cap`, the room left under the template bound: + * the work is bounded by the bound, whatever the value's shape, and so is + * the depth, since every level adds a header. */ +static int64_t ast_node_bytes(ray_t *v, int64_t cap); +static int64_t ast_value_bytes(ray_t *v, int64_t cap) { + if (!v || RAY_IS_ERR(v)) return 0; + if (cap < 0) return 1; + int64_t b; + if (v->type == RAY_LAMBDA) { + b = (int64_t)(sizeof(ray_t) + LAMBDA_SLOTS * sizeof(ray_t*)); + ray_t *parts[4] = { LAMBDA_PARAMS(v), LAMBDA_BODY(v), LAMBDA_CLOSURE(v), LAMBDA_CAPROWS(v) }; + for (int i = 0; i < 4 && b <= cap; i++) b += ast_value_bytes(parts[i], cap - b); + return b; + } + if (v->type == RAY_TABLE || v->type == RAY_DICT) { + ray_t **slots = (ray_t**)ray_data(v); + b = (int64_t)ray_block_size(v); + for (int i = 0; i < 2 && b <= cap; i++) b += ast_value_bytes(slots[i], cap - b); + return b; + } + if (v->type == RAY_LIST && !(v->attrs & RAY_ATTR_SLICE)) { + ray_t **elems = (ray_t**)ray_data(v); + b = (int64_t)ray_block_size(v); + for (int64_t i = 0; i < v->len && b <= cap; i++) b += ast_value_bytes(elems[i], cap - b); + return b; + } + return ast_node_bytes(v, cap); +} + +/* The bytes a text node holds: its header and payload, a string atom's + * or a string vector's characters, and the whole parent of a slice. A + * table or a lambda in the text is a constant the walk does not enter: + * it counts whole (ast_value_bytes). */ +static int64_t ast_node_bytes(ray_t *v, int64_t cap) { + if (v->type == RAY_TABLE || v->type == RAY_LAMBDA) + return ast_value_bytes(v, cap); + if (ray_is_atom(v)) { + int64_t b = (int64_t)ray_block_size(v); + if (v->type == -RAY_STR && !((v->slen >= 1 && v->slen <= 7) || (v->slen == 0 && !v->obj)) && v->obj) + b += ast_node_bytes(v->obj, cap); + else if (v->type == -RAY_GUID && v->obj) + b += ast_node_bytes(v->obj, cap); + return b; + } + if ((v->attrs & RAY_ATTR_SLICE) && v->slice_parent) return ast_node_bytes(v->slice_parent, cap); + int64_t b = (int64_t)ray_block_size(v); + if (v->type == RAY_STR && v->str_pool) b += (int64_t)ray_block_size(v->str_pool); + return b; +} + +/* `weight` accumulates the bytes the text holds (ast_node_bytes of every + * node), so a literal built around a large constant, a long string + * included, is not kept in a template table; nesting past 1024 levels is + * given up on (the literal then has no template and compiles when called). */ +/* `stop`: the walk serves only the template table, which will not keep a + * literal past its bound, so it gives up (false) once the weight passes it. */ +static bool ast_collect_syms_at(ray_t *ast, ray_t **out, bool *dynamic, int depth, int64_t *weight, + bool stop, int64_t *nodes) { + if (!ast || !*out) return false; + if (depth > 1024) return false; + if (nodes && --*nodes < 0) return false; + /* Past the template bound the exact weight does not matter. */ + *weight += ast_node_bytes(ast, RAY_CLOSURE_TMPL_MAX_BYTES - *weight); + if (stop && *weight > RAY_CLOSURE_TMPL_MAX_BYTES) return false; + if (ast->type == -RAY_SYM) { + int64_t id = ast->i64; + if (id == sf_eval || id == sf_resolve) *dynamic = true; + const int64_t *have = (const int64_t*)ray_data(*out); + for (int64_t i = 0; i < (*out)->len; i++) if (have[i] == id) return true; + *out = ray_vec_append(*out, &id); + return *out && !RAY_IS_ERR(*out); + } + if (ast->type == RAY_SYM) { + for (int64_t i = 0; i < ast->len; i++) { + int64_t id = ray_read_sym(ray_data(ast), i, RAY_SYM, ast->attrs); + const int64_t *have = (const int64_t*)ray_data(*out); + bool seen = false; + for (int64_t k = 0; k < (*out)->len; k++) if (have[k] == id) { seen = true; break; } + if (seen) continue; + *out = ray_vec_append(*out, &id); + if (!*out || RAY_IS_ERR(*out)) return false; + } + return true; + } + if (ast->type == RAY_LIST) { + ray_t **elems = (ray_t**)ray_data(ast); + for (int64_t i = 0; i < ast->len; i++) + if (!ast_collect_syms_at(elems[i], out, dynamic, depth + 1, weight, stop, nodes)) return false; + return true; + } + if (ast->type == RAY_DICT) { + ray_t **slots = (ray_t**)ray_data(ast); + return ast_collect_syms_at(slots[0], out, dynamic, depth + 1, weight, stop, nodes) && + ast_collect_syms_at(slots[1], out, dynamic, depth + 1, weight, stop, nodes); + } + return true; +} + +static bool syms_contain(ray_t *syms, int64_t id) { + if (!syms) return false; + const int64_t *ids = (const int64_t*)ray_data(syms); + for (int64_t i = 0; i < syms->len; i++) if (ids[i] == id) return true; + return false; +} + +/* The capture names a closure body can reach: the closure dict's keys that + * the body mentions (every key when the body uses eval or resolve), never + * `self`. A SYM vector the caller releases, or NULL for none. *failed is + * set when the body could not be walked (nesting past the walk's guard, + * more nodes than AST_NAME_NODES, or an allocation failure): NULL + * then means "unknown", not "none", and the + * body must not be compiled without its captures. */ +static ray_t *closure_capture_names(ray_t *lambda, bool *failed) { + *failed = false; + ray_t *closure = LAMBDA_CLOSURE(lambda); + if (!closure) return NULL; + ray_t *keys = ray_dict_keys(closure); + if (!keys || keys->len == 0) return NULL; + init_sf_syms(); + ray_t *mentioned = ray_vec_new(RAY_I64, 16); + if (!mentioned || RAY_IS_ERR(mentioned)) { *failed = true; return NULL; } + bool dynamic = false; + bool ok = ast_collect_syms(LAMBDA_BODY(lambda), &mentioned, &dynamic); + ray_t *names = ok ? ray_sym_vec_new(RAY_SYM_W64, keys->len) : NULL; + if (!names || RAY_IS_ERR(names)) *failed = true; + if (names && !RAY_IS_ERR(names)) { + int64_t *out = (int64_t*)ray_data(names); + names->len = 0; + for (int64_t i = 0; i < keys->len; i++) { + int64_t id = ray_read_sym(ray_data(keys), i, RAY_SYM, keys->attrs); + if (id == sf_self) continue; + if (dynamic || syms_contain(mentioned, id)) out[names->len++] = id; + } + } + if (mentioned) ray_release(mentioned); + if (names && RAY_IS_ERR(names)) names = NULL; + return names; +} + +/* A `fn` literal inside a compiled body becomes a template compiled once, + * here, against the enclosing locals its body mentions (all of them when + * the body uses eval or resolve); OP_MKCLOSURE then makes each closure + * share the template's bytecode and capture those slots. Returns false, + * without emitting, when the literal cannot be compiled this way; the + * caller then falls back to evaluating the literal through the tree + * walker. */ +static bool compile_fn_template_at(compiler_t *c, ray_t *ast); +/* Templates compile their nested literals at once, each level on the C + * stack; past this depth the literal falls back to the dynamic eval path, + * whose closures compile one level at a time when they are called. */ +static _Thread_local int g_template_depth = 0; +static bool compile_fn_template(compiler_t *c, ray_t *ast) { + if (g_template_depth >= 32) return false; + g_template_depth++; + bool ok = compile_fn_template_at(c, ast); + g_template_depth--; + return ok; +} +static bool compile_fn_template_at(compiler_t *c, ray_t *ast) { + ray_t **elems = (ray_t**)ray_data(ast); + int64_t n = ray_len(ast); + /* Parameters: a SYM vector; `[]` parses as an empty vector of another + * type and a list of symbol atoms can occur too, both normalized to a + * SYM vector here. */ + ray_t *params = elems[1]; + if (!params) return false; + bool own_params = false; + if (params->len == 0 && params->type != RAY_SYM && params->type > 0) { + ray_t *pv = ray_sym_vec_new(RAY_SYM_W64, 1); + if (!pv || RAY_IS_ERR(pv)) return false; + pv->len = 0; + params = pv; + own_params = true; + } else if (params->type == RAY_LIST) { + ray_t **pe = (ray_t**)ray_data(params); + for (int64_t i = 0; i < params->len; i++) + if (!pe[i] || pe[i]->type != -RAY_SYM) return false; + ray_t *pv = ray_sym_vec_new(RAY_SYM_W64, params->len > 0 ? params->len : 1); + if (!pv || RAY_IS_ERR(pv)) return false; + for (int64_t i = 0; i < params->len; i++) ((int64_t*)ray_data(pv))[i] = pe[i]->i64; + pv->len = params->len; + params = pv; + own_params = true; + } else if (params->type != RAY_SYM) { + return false; + } + for (int64_t i = 0; i < params->len; i++) + if (ray_sym_is_reserved(ray_read_sym(ray_data(params), i, RAY_SYM, params->attrs))) { + if (own_params) ray_release(params); + return false; + } + + ray_t *mentioned = ray_vec_new(RAY_I64, 16); + if (!mentioned || RAY_IS_ERR(mentioned)) { if (own_params) ray_release(params); return false; } + bool dynamic = false, ok = true; + int64_t tweight = 0, tnodes = AST_NAME_NODES; + for (int64_t i = 2; i < n && ok; i++) + ok = ast_collect_syms_at(elems[i], &mentioned, &dynamic, 0, &tweight, false, &tnodes); + if (!ok) { ray_release(mentioned); if (own_params) ray_release(params); return false; } + + /* Capture names and the enclosing slots they come from, in slot order. */ + ray_t *names = ray_sym_vec_new(RAY_SYM_W64, c->n_locals > 0 ? c->n_locals : 1); + ray_t *slots = ray_vec_new(RAY_I64, c->n_locals > 0 ? c->n_locals : 1); + if (!names || RAY_IS_ERR(names) || !slots || RAY_IS_ERR(slots)) { + ray_release(mentioned); + if (names && !RAY_IS_ERR(names)) ray_release(names); + if (slots && !RAY_IS_ERR(slots)) ray_release(slots); + if (own_params) ray_release(params); + return false; + } + names->len = 0; slots->len = 0; + for (int32_t i = 0; i < c->n_locals; i++) { + int64_t id = c->locals[i].sym_id; + if (id < 0 || id == sf_self) continue; + if (!dynamic && !syms_contain(mentioned, id)) continue; + bool dup = false; /* a name rebound to a later slot: keep the latest */ + for (int64_t k = 0; k < names->len; k++) + if (((int64_t*)ray_data(names))[k] == id) { ((int64_t*)ray_data(slots))[k] = c->locals[i].slot; dup = true; break; } + if (dup) continue; + ((int64_t*)ray_data(names))[names->len++] = id; + ((int64_t*)ray_data(slots))[slots->len++] = c->locals[i].slot; + } + ray_release(mentioned); + + ray_t *body = ray_alloc((size_t)(n - 2) * sizeof(ray_t*)); + ray_t *tmpl = ray_alloc(LAMBDA_SLOTS * sizeof(ray_t*)); + if (!body || RAY_IS_ERR(body) || !tmpl || RAY_IS_ERR(tmpl)) { + ray_release(names); ray_release(slots); + if (own_params) ray_release(params); + if (body && !RAY_IS_ERR(body)) { body->type = RAY_LIST; body->len = 0; ray_release(body); } + if (tmpl && !RAY_IS_ERR(tmpl)) { tmpl->type = RAY_LAMBDA; memset(ray_data(tmpl), 0, LAMBDA_SLOTS * sizeof(ray_t*)); ray_release(tmpl); } + return false; + } + body->type = RAY_LIST; + body->len = n - 2; + for (int64_t i = 2; i < n; i++) { ray_retain(elems[i]); ((ray_t**)ray_data(body))[i - 2] = elems[i]; } + tmpl->type = RAY_LAMBDA; + tmpl->attrs = 0; + tmpl->len = 0; + memset(ray_data(tmpl), 0, LAMBDA_SLOTS * sizeof(ray_t*)); + if (!own_params) ray_retain(params); /* a fresh vector is owned already */ + LAMBDA_PARAMS(tmpl) = params; + LAMBDA_BODY(tmpl) = body; + if (c->lambda && LAMBDA_NFO(c->lambda)) { ray_retain(LAMBDA_NFO(c->lambda)); LAMBDA_NFO(tmpl) = LAMBDA_NFO(c->lambda); } + + if (!compile_lambda(tmpl, names->len ? names : NULL, true)) { + ray_release(tmpl); ray_release(names); ray_release(slots); + return false; + } + int32_t tidx = add_constant(c, tmpl); + int32_t nidx = add_constant(c, names); + int32_t sidx = add_constant(c, slots); + ray_release(tmpl); ray_release(names); ray_release(slots); + if (c->error) return false; + emit_const(c, tidx); + emit_const(c, nidx); + emit_const(c, sidx); + emit(c, OP_MKCLOSURE); + return true; +} + +ray_t *ray_closure_capture_names(ray_t *lambda) { bool failed; return closure_capture_names(lambda, &failed); } + +/* Every symbol a body mentions (I64 vector, owned by the caller) and whether + * it uses eval or resolve; NULL on allocation failure, nesting past the + * walk's guard, or a weight past RAY_CLOSURE_TMPL_MAX_BYTES (the walk + * stops there: the template table would not keep the literal). */ +ray_t *ray_closure_mentioned_syms(ray_t *body, bool *dynamic, int64_t *weight) { + init_sf_syms(); + ray_t *mentioned = ray_vec_new(RAY_I64, 16); + if (!mentioned || RAY_IS_ERR(mentioned)) return NULL; + *dynamic = false; + *weight = 0; + if (!ast_collect_syms_at(body, &mentioned, dynamic, 0, weight, true, NULL)) { if (mentioned) ray_release(mentioned); return NULL; } + return mentioned; +} + +/* The capture names for a closure dict given a body's mentioned symbols + * (see ray_closure_mentioned_syms): the dict keys the body mentions, every + * key when `dynamic`, never `self`. A SYM vector or NULL for none. */ +ray_t *ray_closure_names_from(ray_t *closure, ray_t *mentioned, bool dynamic) { + if (!closure) return NULL; + ray_t *keys = ray_dict_keys(closure); + if (!keys || keys->len == 0) return NULL; + init_sf_syms(); + ray_t *names = ray_sym_vec_new(RAY_SYM_W64, keys->len); + if (!names || RAY_IS_ERR(names)) return NULL; + int64_t *out = (int64_t*)ray_data(names); + names->len = 0; + for (int64_t i = 0; i < keys->len; i++) { + int64_t id = ray_read_sym(ray_data(keys), i, RAY_SYM, keys->attrs); + if (id == sf_self) continue; + if (dynamic || syms_contain(mentioned, id)) out[names->len++] = id; + } + return names; +} +bool ray_closure_shape_ok(ray_t *closure) { return closure_shape_ok(closure); } +bool ray_compile_with_captures(ray_t *lambda, ray_t *capnames, bool closure_body) { return compile_lambda(lambda, capnames, closure_body); } + void ray_compile(ray_t *lambda) { if (LAMBDA_IS_COMPILED(lambda)) return; + if (!closure_shape_ok(LAMBDA_CLOSURE(lambda))) return; + bool walk_failed = false; + ray_t *names = closure_capture_names(lambda, &walk_failed); + /* A body the walk gave up on mentions captures it cannot list: bind + * every capture, as for a body that uses eval, or compiled without + * them its captured names would resolve as globals. When that does + * not compile either (more captures than a frame holds), the body + * stays on the tree walker. */ + if (walk_failed) { + names = ray_closure_names_from(LAMBDA_CLOSURE(lambda), NULL, true); + if (!names) { LAMBDA_NLOCALS(lambda) = -1; return; } + } + /* A closure body resolves its free names at call time; a lambda made + * with nothing captured keeps the builtins it names baked in. */ + if (!compile_lambda(lambda, names, LAMBDA_CLOSURE(lambda) != NULL)) + LAMBDA_NLOCALS(lambda) = -1; /* remembered: not compilable, no retry per call */ + if (names) ray_release(names); +} + +/* Compile `lambda` with `capnames` (a SYM vector, or NULL) bound as locals + * ahead of the body by one OP_BINDCAPS. A parameter shadows a capture of + * its name. False when the body cannot be compiled (the lambda stays on + * the tree walker). */ +static bool compile_lambda_deps(ray_t *lambda, ray_t *capnames, bool dynamic_globals, ray_t **deps); +static bool compile_lambda(ray_t *lambda, ray_t *capnames, bool dynamic_globals) { + return compile_lambda_deps(lambda, capnames, dynamic_globals, NULL); +} +/* Compile a lambda with nothing captured, as ray_compile does, and hand + * back in *deps (an I64 vector the caller releases) the call heads its + * code was shaped by: pairs of a symbol and the builtin it named then, or + * 0. Code compiled for the same text while every pair still holds is + * the code a fresh compile would produce. False when it does not + * compile (the lambda is then marked, as ray_compile marks it). */ +bool ray_compile_definition(ray_t *lambda, ray_t **deps) { + *deps = NULL; + if (LAMBDA_IS_COMPILED(lambda) || LAMBDA_CLOSURE(lambda)) return false; + if (!compile_lambda_deps(lambda, NULL, false, deps)) { + LAMBDA_NLOCALS(lambda) = -1; + return false; + } + return true; +} + +static bool compile_lambda_deps(ray_t *lambda, ray_t *capnames, bool dynamic_globals, ray_t **deps) { compiler_t c; - if (!compiler_init(&c)) return; + if (!compiler_init(&c)) return false; c.lambda = lambda; + c.dynamic_globals = dynamic_globals; + if (deps) { + c.deps = ray_vec_new(RAY_I64, 16); + if (!c.deps || RAY_IS_ERR(c.deps)) { c.deps = NULL; compiler_destroy(&c); return false; } + } /* Register params as locals */ ray_t *params_list = LAMBDA_PARAMS(lambda); @@ -731,6 +1209,42 @@ void ray_compile(ray_t *lambda) { for (int64_t i = 0; i < param_count; i++) { if (add_local(&c, param_ids[i]) < 0) { c.error = true; break; } } + /* Only the parameters are always bound. A capture slot can be empty + * (its `let` had not run when the closure was made), so it reads like + * a `let` slot: the global of that name, or a name error. */ + c.n_fixed = c.n_locals; + + /* A closure's captures are locals of its body, bound before it runs: + * a `let` of a captured name writes the same slot, a capture named + * like a builtin is the callee, and a window (OP_SCOPE_EVAL) binds + * them with the other locals. Only the names the body mentions take a + * slot (closure_capture_names / compile_fn_template), so a closure's + * recursion depth does not shrink with the bindings in scope. One + * OP_BINDCAPS binds them all, by name, from the closure dict. A frame + * holds 256 slots; a closure needing more stays on the tree walker. */ + if (!c.error && capnames && capnames->len > 0) { + ray_t *pairs = ray_alloc((size_t)capnames->len * 2 * sizeof(int64_t)); + if (!pairs || RAY_IS_ERR(pairs)) { c.error = true; } + else { + pairs->type = RAY_I64; + pairs->len = 0; + int64_t *pv = (int64_t*)ray_data(pairs); + for (int64_t i = 0; i < capnames->len && !c.error; i++) { + int64_t id = ray_read_sym(ray_data(capnames), i, RAY_SYM, capnames->attrs); + if (find_local(&c, id) >= 0) continue; /* a parameter shadows its capture */ + int32_t slot = add_local(&c, id); + if (slot < 0) { c.error = true; break; } + pv[pairs->len++] = id; + pv[pairs->len++] = slot; + } + if (!c.error && pairs->len > 0) { + int32_t idx = add_constant(&c, pairs); + if (idx < 0 || idx > 255) c.error = true; + else { emit(&c, OP_BINDCAPS); emit(&c, (uint8_t)idx); } + } + ray_release(pairs); + } + } /* Compile body expressions */ ray_t *body = LAMBDA_BODY(lambda); @@ -745,19 +1259,19 @@ void ray_compile(ray_t *lambda) { if (c.error) { if (c.dbg_obj) ray_release(c.dbg_obj); compiler_destroy(&c); - return; + return false; } /* Build bytecode vector */ ray_t *bc = ray_alloc(c.code_len); - if (!bc) { compiler_destroy(&c); return; } + if (!bc) { compiler_destroy(&c); return false; } bc->type = RAY_U8; bc->len = c.code_len; memcpy(ray_data(bc), c.code, c.code_len); /* Build constants list */ ray_t *consts = ray_alloc(c.n_consts * sizeof(ray_t *)); - if (!consts) { ray_release(bc); compiler_destroy(&c); return; } + if (!consts) { ray_release(bc); compiler_destroy(&c); return false; } consts->type = RAY_LIST; consts->len = c.n_consts; ray_t **cpool = (ray_t **)ray_data(consts); @@ -776,7 +1290,9 @@ void ray_compile(ray_t *lambda) { /* dbg_obj is now owned by the lambda, don't release it */ } + if (deps) { *deps = c.deps; c.deps = NULL; } compiler_destroy(&c); + return true; } ray_span_t ray_bc_dbg_get(ray_t* dbg, int32_t ip) { diff --git a/src/lang/env.c b/src/lang/env.c index 9fe76eee3..96917a3ed 100644 --- a/src/lang/env.c +++ b/src/lang/env.c @@ -28,6 +28,7 @@ #include "table/dict.h" #include "ops/temporal.h" #include "ops/linkop.h" +#include "ops/ops.h" /* ray_is_lazy, ray_lazy_materialize — lazy captures */ #include "mem/sys.h" #include #include @@ -103,6 +104,16 @@ static struct { int32_t count; } g_env; +/* What a name compiled code resolves stays the same while neither moves: + * the frame epoch (this thread's scope frames: a push, a pop, a binding, + * a frame's kind or flags) and the global epoch (any global written). + * ray_env_resolve_compiled caches its answers under the pair. */ +_Thread_local uint64_t g_frame_epoch = 1; +_Atomic uint64_t g_global_epoch = 1; +_Thread_local ray_resolve_cache_t g_resolve_cache[1 << RAY_RESOLVE_CACHE_BITS]; +static inline void env_frames_moved(void) { g_frame_epoch++; } +static inline void env_globals_moved(void) { atomic_fetch_add_explicit(&g_global_epoch, 1, memory_order_relaxed); } + /* ---- Local scope stack ---- */ /* The scope stack lives on the per-thread VM (core/runtime.h) — one @@ -140,27 +151,82 @@ int64_t ray_env_builtin_sym(const ray_t* fn) { * an inner query can bind a same-named column over an outer query column. * Query-local callers push a query frame before probing, so scanning every * frame still excludes the binding currently being installed. */ -ray_t* ray_env_get_lexical_local(int64_t sym_id) { +/* A query helper's call frame binds source columns on demand above + * `table_from`; those are the query's columns, not lexical locals. */ +static int32_t env_frame_lexical_count(const ray_scope_frame_t* f) { + return f->kind == RAY_SCOPE_CALL && f->table ? f->table_from : f->count; +} + +/* `in_callee`: the name is looked up for code a compiled frame's text + * calls (a helper body the planner inlines), so no eval window is its + * scope; otherwise the nearest window is, and none below it. */ +static ray_t* env_lexical_local_impl(int64_t sym_id, bool in_callee) { if (!__VM) return NULL; for (int32_t d = __VM->scope_depth - 1; d >= 0; d--) { ray_scope_frame_t* f = &__VM->scope_stack[d]; if (f->kind == RAY_SCOPE_QUERY) continue; - for (int32_t i = 0; i < f->count; i++) + if (f->lexical) in_callee = true; + if (f->eval_window && in_callee) continue; + int32_t n = env_frame_lexical_count(f); + for (int32_t i = 0; i < n; i++) if (f->keys[i] == sym_id) return f->vals[i]; + if (f->eval_window) in_callee = true; + if (f->kind == RAY_SCOPE_CALL) break; } return NULL; } +ray_t* ray_env_get_lexical_local(int64_t sym_id) { + return env_lexical_local_impl(sym_id, false); +} + +ray_t* ray_env_get_lexical_local_callee(int64_t sym_id) { + return env_lexical_local_impl(sym_id, true); +} + +int32_t ray_env_lexical_scope_depth(int64_t sym_id) { + if (!__VM) return -1; + for (int32_t d = __VM->scope_depth - 1; d >= 0; d--) { + ray_scope_frame_t* f = &__VM->scope_stack[d]; + if (f->kind == RAY_SCOPE_QUERY) continue; + int32_t n = env_frame_lexical_count(f); + for (int32_t i = 0; i < n; i++) + if (f->keys[i] == sym_id) return d + 1; + if (f->kind == RAY_SCOPE_CALL) break; + } + return -1; +} + bool ray_env_has_lexical_local(int64_t sym_id) { return ray_env_get_lexical_local(sym_id) != NULL; } ray_err_t ray_env_set_query_local(int64_t sym_id, ray_t* val) { return ray_env_has_lexical_local(sym_id) ? RAY_OK - : ray_env_set_local(sym_id, val); + : ray_env_set_local_rows(sym_id, val, 1); +} + +static _Thread_local uint32_t g_query_serial; + +uint32_t ray_env_query_serial(void) { + if (!__VM) return 0; + for (int32_t d = __VM->scope_depth - 1; d >= 0; d--) + if (__VM->scope_stack[d].kind == RAY_SCOPE_QUERY) return __VM->scope_stack[d].serial; + return 0; } ray_t* ray_env_capture_locals(void) { + return ray_env_capture_locals_rows(NULL, NULL); +} + +/* Cached `self` sym id for ray_env_scope_bind and the capture below — + * interned once per sym table generation; invalidated alongside the hook + * syms (env_reset_cached_syms). */ +static int64_t g_self_sym = -1; + +ray_t* ray_env_capture_locals_rows(ray_t** flags_out, uint32_t* serial_out) { + if (flags_out) *flags_out = NULL; + if (serial_out) *serial_out = 0; if (!__VM || __VM->scope_depth == 0) return NULL; int64_t capacity = 0; for (int32_t d = 0; d < __VM->scope_depth; d++) @@ -176,33 +242,83 @@ ray_t* ray_env_capture_locals(void) { } int64_t* key_ids = (int64_t*)ray_data(keys); + /* The captures' row provenance, relative to the innermost query: a + * binding below that query's frame is plain data for it. Most + * closures are made outside any query, so the flags are gathered in + * a small local buffer and become a vector only when one is set. */ + uint8_t fbuf[256]; + ray_t* flags = NULL; + uint8_t* fl = fbuf; + if (capacity > (int64_t)sizeof fbuf) { + flags = ray_vec_new(RAY_U8, capacity); + if (!flags || RAY_IS_ERR(flags)) { ray_release(keys); ray_release(vals); return flags ? flags : ray_error("oom", NULL); } + fl = (uint8_t*)ray_data(flags); + } + int64_t nflags = 0; + bool any_flag = false, outer = false; + if (g_self_sym < 0) g_self_sym = ray_sym_intern("self", 4); /* Top-to-bottom flattening preserves ordinary lexical lookup: the first - * occurrence of a name is the value visible at closure creation. */ + * occurrence of a name is the value visible at closure creation. `self` + * is never captured: inside the closure it is the closure itself. */ for (int32_t d = __VM->scope_depth - 1; d >= 0; d--) { ray_scope_frame_t* f = &__VM->scope_stack[d]; for (int32_t i = 0; i < f->count; i++) { - if (!f->vals[i]) continue; + if (!f->vals[i] || f->keys[i] == g_self_sym) continue; bool seen = false; for (int64_t k = 0; k < keys->len; k++) if (key_ids[k] == f->keys[i]) { seen = true; break; } if (seen) continue; key_ids[keys->len++] = f->keys[i]; + uint8_t r = outer ? 0 : f->rows[i]; + fl[nflags++] = r; + if (r) any_flag = true; + if (ray_is_lazy(f->vals[i])) { + /* A lazy handle is single-use: capture (and keep bound) the + * concrete value, or the closure's second call would read a + * handle its first call consumed. */ + env_frames_moved(); + ray_t* concrete = ray_lazy_materialize(f->vals[i]); /* consumes the frame's ref */ + if (!concrete || RAY_IS_ERR(concrete)) { + f->vals[i] = NULL; + ray_release(keys); ray_release(vals); if (flags) ray_release(flags); + return concrete ? concrete : ray_error("type", NULL); + } + f->vals[i] = concrete; + } vals = ray_list_append(vals, f->vals[i]); if (!vals || RAY_IS_ERR(vals)) { - ray_release(keys); + ray_release(keys); if (flags) ray_release(flags); return vals ? vals : ray_error("oom", NULL); } } + if (f->kind == RAY_SCOPE_QUERY) outer = true; + /* An eval window is the evaluated text's scope: what lies below it + * belongs to the caller of the code that evaluated the text. */ + if (f->kind == RAY_SCOPE_CALL || f->lexical || f->eval_window) break; } if (keys->len == 0) { ray_release(keys); ray_release(vals); + if (flags) ray_release(flags); return NULL; } - return ray_dict_new(keys, vals); + if (any_flag && flags_out && !flags) { + flags = ray_vec_new(RAY_U8, nflags); + if (!flags || RAY_IS_ERR(flags)) { ray_release(keys); ray_release(vals); return flags ? flags : ray_error("oom", NULL); } + memcpy(ray_data(flags), fbuf, (size_t)nflags); + } + if (flags) flags->len = nflags; + ray_t* capture = ray_dict_new(keys, vals); + if (capture && !RAY_IS_ERR(capture) && any_flag && flags_out) { + *flags_out = flags; + if (serial_out) *serial_out = ray_env_query_serial(); + } else if (flags) ray_release(flags); + return capture; } -ray_err_t ray_env_push_capture(ray_t* capture) { + + +ray_err_t ray_env_push_capture(ray_t* capture, ray_t* flags, uint32_t serial) { if (ray_env_push_scope() != RAY_OK) return RAY_ERR_OOM; if (!capture) return RAY_OK; if (capture->type != RAY_DICT) { @@ -217,9 +333,14 @@ ray_err_t ray_env_push_capture(ray_t* capture) { return RAY_ERR_TYPE; } ray_t** value_items = (ray_t**)ray_data(vals); + /* The captures' row flags apply only while the query frame the closure + * was made under is the innermost query; anywhere else they are data. */ + const uint8_t* fl = flags && flags->type == RAY_U8 && flags->len == keys->len && + serial && serial == ray_env_query_serial() + ? (const uint8_t*)ray_data(flags) : NULL; for (int64_t i = 0; i < keys->len; i++) { int64_t sym = ray_read_sym(ray_data(keys), i, RAY_SYM, keys->attrs); - ray_err_t err = ray_env_set_local(sym, value_items[i]); + ray_err_t err = ray_env_set_local_rows(sym, value_items[i], fl ? fl[i] : 0); if (err != RAY_OK) { ray_env_pop_scope(); return err; @@ -238,9 +359,7 @@ ray_err_t ray_env_push_capture(ray_t* capture) { static int64_t g_ipc_hook_syms[5] = {0}; static bool g_ipc_hook_syms_ready = false; -/* Cached `self` sym id for ray_env_scope_bind — interned once per sym - * table generation; invalidated alongside the hook syms below. */ -static int64_t g_self_sym = -1; +/* g_self_sym: see its declaration above ray_env_capture_locals_rows. */ static void ipc_hook_syms_ensure(void) { if (g_ipc_hook_syms_ready) return; @@ -266,6 +385,7 @@ int64_t ray_sym_ipc_hook(int idx) { } ray_err_t ray_env_init(void) { + env_globals_moved(); memset(&g_env, 0, sizeof(g_env)); __VM->scope_depth = 0; /* The IPC hook sym IDs are interned lazily on first probe via @@ -282,6 +402,7 @@ ray_err_t ray_env_init(void) { } void ray_env_destroy(void) { + env_globals_moved(); /* Pop any remaining scopes */ while (__VM->scope_depth > 0) ray_env_pop_scope(); for (int32_t i = 0; i < g_env.count; i++) { @@ -300,40 +421,119 @@ void ray_env_destroy(void) { /* Flat (non-dotted) lookup — scope stack top-down, then global env. * Returns NULL if not bound. Always used as the head-segment resolver * for dotted paths, and as the fast path for plain names. */ -static ray_t* env_lookup_flat(int64_t sym_id) { +static ray_err_t env_frame_bind(ray_scope_frame_t* f, int64_t sym_id, ray_t* val); +static ray_err_t env_frame_bind_rows(ray_scope_frame_t* f, int64_t sym_id, ray_t* val, uint8_t rows); +ray_t* ray_query_helper_value(int64_t sym); /* ops/query.c */ + +/* A lookup that reaches a query helper's call frame: a free name that is + * a source column binds, on first use, to what the query's own expressions + * see for it (the column, or the current row's cell); the frame owns that + * binding for the call, so a source column shadows a global of the same + * name here as it does in a body the planner inlines. Any other name + * falls through to the globals. The frame grows past RAY_FRAME_CAP on + * demand; only an allocation failure leaves the name unbound. */ +static ray_t* env_call_frame_value(ray_scope_frame_t* f, int64_t sym_id) { + if (!f->table) return NULL; + /* The query decides what the column means here: the row's cell, the + * group's rows or the whole column. Nothing below the frame is read, + * so a caller's locals stay hidden. */ + ray_t* v = ray_query_helper_value(sym_id); + if (!v) return NULL; + if (RAY_IS_ERR(v)) { ray_error_free(v); return NULL; } + ray_err_t err = env_frame_bind_rows(f, sym_id, v, 1); + ray_release(v); + return err == RAY_OK ? f->vals[f->count - 1] : NULL; +} + +/* A global by name. The table is a flat array of some hundreds of names, + * builtins first, so a scan per lookup cost a closure body, which + * resolves every builtin it names when it runs, more than the builtin's + * own work. A per-thread hint remembers where a name was found; it is + * only a hint, checked against the slot it names, so a rebinding, a new + * name or a deletion that moves the slots is seen at once. */ +static ray_t* env_global_lookup(int64_t sym_id) { + enum { HINT_BITS = 10 }; + static _Thread_local struct { int64_t sym; int32_t idx; } hint[1 << HINT_BITS]; + uint32_t h = (uint32_t)(((uint64_t)sym_id * UINT64_C(0x9E3779B97F4A7C15)) >> (64 - HINT_BITS)); + int32_t i = hint[h].idx; + int32_t n = g_env.count; + if (hint[h].sym == sym_id && i < n && g_env.keys[i] == sym_id) return g_env.vals[i]; + for (i = 0; i < n; i++) { + if (g_env.keys[i] != sym_id) continue; + hint[h].sym = sym_id; + hint[h].idx = i; + return g_env.vals[i]; + } + return NULL; +} + +/* `rows`, when given, is set when the value is a query source column (or + * its cell) read through a helper's call frame. `in_callee`: the lookup + * is made by compiled code, whose own names are slots, so an `eval` + * window on the stack belongs to a caller; the tree walker gets there + * once it passes a lambda call's frame (`lexical`). */ +static ray_t* env_lookup_flat_impl(int64_t sym_id, uint8_t* rows, bool in_callee) { /* FFI/embedding callers reach this on threads that never bound a VM * (cf. ray_env_get_local, already guarded). Such a thread has no * local scopes; global bindings must still resolve. */ if (__VM) { + /* Provenance is relative to the innermost query: a binding below + * that query's frame belongs to an outer context and is plain data + * for the inner one. */ + bool outer = false; for (int32_t d = __VM->scope_depth - 1; d >= 0; d--) { ray_scope_frame_t* f = &__VM->scope_stack[d]; + if (f->lexical) in_callee = true; + if (f->eval_window && in_callee) continue; for (int32_t i = 0; i < f->count; i++) { - if (f->keys[i] == sym_id) return f->vals[i]; + if (f->keys[i] != sym_id) continue; + if (rows) *rows = outer ? 0 : f->rows[i]; + return f->vals[i]; + } + /* The text's own window is the one nearest it; a window below + * belongs to whoever called the code that evaluated it. */ + if (f->eval_window) in_callee = true; + if (f->kind == RAY_SCOPE_QUERY) outer = true; + if (f->kind == RAY_SCOPE_CALL) { + ray_t* v = env_call_frame_value(f, sym_id); + if (v) { if (rows) *rows = outer ? 0 : 1; return v; } + break; } } } - for (int32_t i = 0; i < g_env.count; i++) { - if (g_env.keys[i] == sym_id) return g_env.vals[i]; - } - return NULL; + return env_global_lookup(sym_id); } + + ray_t* ray_env_get_local(int64_t sym_id) { if (!__VM) return NULL; for (int32_t d = __VM->scope_depth - 1; d >= 0; d--) { ray_scope_frame_t* f = &__VM->scope_stack[d]; for (int32_t i = 0; i < f->count; i++) if (f->keys[i] == sym_id) return f->vals[i]; + if (f->kind == RAY_SCOPE_CALL) break; } return NULL; } +static ray_t* env_get_impl(int64_t sym_id, bool in_callee); ray_t* ray_env_get(int64_t sym_id) { + return env_get_impl(sym_id, false); +} + +/* ray_env_get for a body being compiled: it is a callee of whatever is on + * the scope stack, so an `eval` window there is not its scope. */ +ray_t* ray_env_get_compiled(int64_t sym_id) { + return env_get_impl(sym_id, true); +} + +static ray_t* env_get_impl(int64_t sym_id, bool in_callee) { /* Flat lookup first — covers every non-dotted name AND every * reserved builtin like `.sys.gc` which is bound both flat (for * O(1) resolution + prefix enumeration) and inside the `.sys` * namespace dict (for REPL introspection). */ - ray_t* flat = env_lookup_flat(sym_id); + ray_t* flat = env_lookup_flat_impl(sym_id, NULL, in_callee); if (flat) return flat; if (!ray_sym_is_dotted(sym_id)) return NULL; @@ -349,7 +549,7 @@ ray_t* ray_env_get(int64_t sym_id) { int n = ray_sym_segs(sym_id, &segs); if (n < 2) return NULL; /* defensive — dotted bit without segments */ - ray_t* v = env_lookup_flat(segs[0]); + ray_t* v = env_lookup_flat_impl(segs[0], NULL, in_callee); for (int i = 1; v && i < n; i++) { v = ray_container_probe_sym(v, segs[i]); } @@ -365,11 +565,69 @@ ray_t* ray_env_get(int64_t sym_id) { * fresh result. Those fresh allocations are exactly why this function * has a different retain contract from ray_env_get. */ ray_t* ray_env_resolve(int64_t sym_id) { + return ray_env_resolve_rows(sym_id, NULL); +} + +static ray_t* env_resolve_impl(int64_t sym_id, uint8_t* rows, bool in_callee); +ray_t* ray_env_resolve_rows(int64_t sym_id, uint8_t* rows) { + return env_resolve_impl(sym_id, rows, false); +} + +/* A name compiled code resolves at run time (OP_RESOLVE): never a binding + * of an `eval` window, which belongs to a caller. */ +ray_t* ray_env_resolve_compiled(int64_t sym_id, uint8_t* rows) { + /* A name resolved under the same frame and global epochs resolves to + * the same binding: the frames and globals it was read from have not + * moved, so the value is still the one they hold (and alive). */ + ray_resolve_cache_t* rc = g_resolve_cache; + uint32_t h = ray_resolve_cache_slot(sym_id); + uint64_t ge = atomic_load_explicit(&g_global_epoch, memory_order_relaxed); + if (rc[h].sym == sym_id && rc[h].fe == g_frame_epoch && rc[h].ge == ge && rc[h].val) { + if (rows) *rows = rc[h].rows; + ray_retain(rc[h].val); + return rc[h].val; + } + /* Only plain frames to look through (a body called outside any query, + * from the top level or interpreted code): their bindings, eval windows + * passed by, then the global, without the general walk's query and + * call-frame cases. Anything else takes the general walk. */ + if (__VM) { + bool plain = true; + for (int32_t d = __VM->scope_depth - 1; d >= 0 && plain; d--) { + ray_scope_frame_t* f = &__VM->scope_stack[d]; + if (f->kind != RAY_SCOPE_LEXICAL) { plain = false; break; } + if (f->eval_window) continue; + for (int32_t i = 0; i < f->count; i++) { + if (f->keys[i] != sym_id) continue; + if (rows) *rows = f->rows[i]; + if (f->vals[i]) { + ray_retain(f->vals[i]); + rc[h].sym = sym_id; rc[h].fe = g_frame_epoch; rc[h].ge = ge; + rc[h].val = f->vals[i]; rc[h].rows = f->rows[i]; + } + return f->vals[i]; + } + } + if (plain) { + ray_t* v = env_global_lookup(sym_id); + if (v) { + if (rows) *rows = 0; + ray_retain(v); + rc[h].sym = sym_id; rc[h].fe = g_frame_epoch; rc[h].ge = ge; rc[h].val = v; rc[h].rows = 0; + return v; + } + } + } + return env_resolve_impl(sym_id, rows, true); +} + +static ray_t* env_resolve_impl(int64_t sym_id, uint8_t* rows, bool in_callee) { + if (rows) *rows = 0; /* Flat lookup first — short-circuits dotted reserved builtins * (`.sys.gc`, `.os.getenv`, …) that are additionally bound flat * alongside their namespace dict. Non-dotted names take the * same path. */ - ray_t* flat = env_lookup_flat(sym_id); + ray_t* flat = env_lookup_flat_impl(sym_id, rows, in_callee); if (flat) { ray_retain(flat); return flat; } if (!ray_sym_is_dotted(sym_id)) return NULL; @@ -380,7 +638,7 @@ ray_t* ray_env_resolve(int64_t sym_id) { /* `v` is either a borrowed env/container pointer (fresh=false) or a * fresh temporal-extract result (fresh=true). When switching between * the two we must release the previous fresh value to avoid leaks. */ - ray_t* v = env_lookup_flat(segs[0]); + ray_t* v = env_lookup_flat_impl(segs[0], rows, in_callee); bool fresh = false; for (int i = 1; v && i < n; i++) { @@ -429,6 +687,7 @@ ray_t* ray_env_resolve(int64_t sym_id) { break; } } + if (f->kind == RAY_SCOPE_CALL) break; } if (!fn) { for (int32_t k = 0; k < g_env.count; k++) { @@ -467,6 +726,7 @@ ray_t* ray_env_resolve(int64_t sym_id) { * cascade-up case in env_set_dotted where every dict in a dotted path was * emptied by the delete. */ static ray_err_t env_bind_global_impl(int64_t sym_id, ray_t* val, int is_user) { + env_globals_moved(); env_lock(); for (int32_t i = 0; i < g_env.count; i++) { if (g_env.keys[i] == sym_id) { @@ -523,8 +783,8 @@ static ray_err_t env_bind_global_user(int64_t sym_id, ray_t* val) { return env_bind_global_impl(sym_id, val, 1); } -static ray_err_t env_bind_local(int64_t sym_id, ray_t* val) { - ray_scope_frame_t* f = &__VM->scope_stack[__VM->scope_depth - 1]; +static ray_err_t env_frame_bind_rows(ray_scope_frame_t* f, int64_t sym_id, ray_t* val, uint8_t rows) { + env_frames_moved(); for (int32_t i = 0; i < f->count; i++) { if (f->keys[i] == sym_id) { if (val == NULL) { @@ -532,6 +792,7 @@ static ray_err_t env_bind_local(int64_t sym_id, ray_t* val) { for (int32_t j = i; j + 1 < f->count; j++) { f->keys[j] = f->keys[j + 1]; f->vals[j] = f->vals[j + 1]; + f->rows[j] = f->rows[j + 1]; } f->count--; return RAY_OK; @@ -539,6 +800,7 @@ static ray_err_t env_bind_local(int64_t sym_id, ray_t* val) { if (f->vals[i]) ray_release(f->vals[i]); ray_retain(val); f->vals[i] = val; + f->rows[i] = rows; return RAY_OK; } } @@ -547,26 +809,76 @@ static ray_err_t env_bind_local(int64_t sym_id, ray_t* val) { int32_t new_cap = f->cap * 2; int64_t* nk = (int64_t*)ray_sys_alloc(sizeof(int64_t) * (size_t)new_cap); ray_t** nv = (ray_t**)ray_sys_alloc(sizeof(ray_t*) * (size_t)new_cap); - if (!nk || !nv) { + uint8_t* nr = (uint8_t*)ray_sys_alloc((size_t)new_cap); + if (!nk || !nv || !nr) { if (nk) ray_sys_free(nk); if (nv) ray_sys_free(nv); + if (nr) ray_sys_free(nr); return RAY_ERR_OOM; } memcpy(nk, f->keys, sizeof(int64_t) * (size_t)f->count); memcpy(nv, f->vals, sizeof(ray_t*) * (size_t)f->count); + memcpy(nr, f->rows, (size_t)f->count); if (f->keys != f->keys_inline) ray_sys_free(f->keys); if (f->vals != f->vals_inline) ray_sys_free(f->vals); + if (f->rows != f->rows_inline) ray_sys_free(f->rows); f->keys = nk; f->vals = nv; + f->rows = nr; f->cap = new_cap; } f->keys[f->count] = sym_id; ray_retain(val); f->vals[f->count] = val; + f->rows[f->count] = rows; f->count++; return RAY_OK; } +static ray_err_t env_frame_bind(ray_scope_frame_t* f, int64_t sym_id, ray_t* val) { + return env_frame_bind_rows(f, sym_id, val, 0); +} + +static ray_err_t env_bind_local(int64_t sym_id, ray_t* val) { + return env_frame_bind(&__VM->scope_stack[__VM->scope_depth - 1], sym_id, val); +} + +ray_err_t ray_env_set_local_rows(int64_t sym_id, ray_t* val, uint8_t rows) { + if (!__VM || ray_sym_is_dotted(sym_id) || __VM->scope_depth <= 0) return ray_env_set_local(sym_id, val); + if (ray_sym_is_reserved(sym_id) && !ray_sym_is_ipc_hook(sym_id)) return RAY_ERR_RESERVED; + return env_frame_bind_rows(&__VM->scope_stack[__VM->scope_depth - 1], sym_id, val, rows); +} + +/* The provenance flag of the binding a plain name resolves to (query and + * call frames included, globals excluded), or -1 when it is not bound. */ +int ray_env_binding_rows(int64_t sym_id) { + if (!__VM) return -1; + bool outer = false; + for (int32_t d = __VM->scope_depth - 1; d >= 0; d--) { + ray_scope_frame_t* f = &__VM->scope_stack[d]; + for (int32_t i = 0; i < f->count; i++) + if (f->keys[i] == sym_id) return outer ? 0 : f->rows[i]; + if (f->kind == RAY_SCOPE_QUERY) outer = true; + if (f->kind == RAY_SCOPE_CALL) break; + } + return -1; +} + +/* Inside a helper called from a query: a call frame is met before any + * query frame. A nested query's own frame ends the helper's reach. */ +bool ray_env_in_query_helper(bool* named) { + if (!__VM) return false; + for (int32_t d = __VM->scope_depth - 1; d >= 0; d--) { + ray_scope_frame_t* f = &__VM->scope_stack[d]; + if (f->kind == RAY_SCOPE_QUERY) return false; + if (f->kind == RAY_SCOPE_CALL && f->table) { + if (named) *named = f->named != 0; + return true; + } + } + return false; +} + /* Dotted-path write. base_lookup(head_sym) returns the current binding in * the scope we are writing to (global or local frame), or NULL. bind_fn * rebinds the new top-level dict in that same scope. Walks the existing @@ -680,11 +992,8 @@ static ray_err_t env_set_dotted(int64_t sym_id, ray_t* val, } /* Scope-specific base lookups used by env_set_dotted. */ -static ray_t* lookup_global(int64_t sym_id) { - for (int32_t i = 0; i < g_env.count; i++) { - if (g_env.keys[i] == sym_id) return g_env.vals[i]; - } - return NULL; +ray_t* ray_env_get_global(int64_t sym_id) { + return env_global_lookup(sym_id); } static ray_t* lookup_top_frame(int64_t sym_id) { @@ -711,7 +1020,7 @@ bool ray_sym_is_reserved(int64_t sym_id) { ray_err_t ray_env_bind(int64_t sym_id, ray_t* val) { if (ray_sym_is_dotted(sym_id)) { - return env_set_dotted(sym_id, val, lookup_global, env_bind_global); + return env_set_dotted(sym_id, val, ray_env_get_global, env_bind_global); } return env_bind_global(sym_id, val); } @@ -731,7 +1040,7 @@ ray_err_t ray_env_set(int64_t sym_id, ray_t* val) { * flip, env_bind_global would also be reached via ray_env_bind below * and the slot would carry user=0 — leaving it out of .qdb. */ if (ray_sym_is_dotted(sym_id)) - return env_set_dotted(sym_id, val, lookup_global, env_bind_global_user); + return env_set_dotted(sym_id, val, ray_env_get_global, env_bind_global_user); return env_bind_global_user(sym_id, val); } @@ -743,10 +1052,47 @@ static ray_err_t env_push_scope(uint8_t kind) { f->cap = RAY_FRAME_CAP; f->count = 0; f->kind = kind; + f->lexical = 0; + f->eval_window = 0; + f->rows = f->rows_inline; + f->named = 0; + f->table = NULL; + f->table_from = 0; + f->serial = 0; + if (kind == RAY_SCOPE_QUERY) { + if (++g_query_serial == 0) ++g_query_serial; /* never 0 */ + f->serial = g_query_serial; + } __VM->scope_depth++; return RAY_OK; } +ray_err_t ray_env_push_call_scope(ray_t* table, bool named) { + ray_err_t err = env_push_scope(RAY_SCOPE_CALL); + if (err != RAY_OK) return err; + ray_env_mark_call_scope(table, named); + return RAY_OK; +} + +void ray_env_mark_call_scope(ray_t* table, bool named) { + env_frames_moved(); + ray_scope_frame_t* f = &__VM->scope_stack[__VM->scope_depth - 1]; + f->kind = RAY_SCOPE_CALL; + f->named = named; + f->table = table; + f->table_from = f->count; +} + + +/* Mark the frame `below` levels under the top one as a lexical boundary + * for closure capture (see ray_scope_frame_t.lexical). */ +void ray_env_mark_lexical_scope(int32_t below) { + if (!__VM) return; + env_frames_moved(); + int32_t d = __VM->scope_depth - 1 - below; + if (d >= 0) __VM->scope_stack[d].lexical = 1; +} + ray_err_t ray_env_push_scope(void) { return env_push_scope(RAY_SCOPE_LEXICAL); } @@ -757,6 +1103,7 @@ ray_err_t ray_env_push_query_scope(void) { void ray_env_pop_scope(void) { if (__VM->scope_depth <= 0) return; + env_frames_moved(); __VM->scope_depth--; ray_scope_frame_t* f = &__VM->scope_stack[__VM->scope_depth]; for (int32_t i = 0; i < f->count; i++) { @@ -764,11 +1111,25 @@ void ray_env_pop_scope(void) { } if (f->keys != f->keys_inline) ray_sys_free(f->keys); if (f->vals != f->vals_inline) ray_sys_free(f->vals); + if (f->rows != f->rows_inline) ray_sys_free(f->rows); + f->serial = 0; f->keys = f->keys_inline; f->vals = f->vals_inline; + f->rows = f->rows_inline; f->cap = RAY_FRAME_CAP; f->count = 0; f->kind = RAY_SCOPE_LEXICAL; + f->named = 0; + f->table = NULL; + f->table_from = 0; +} + +/* The top frame is a compiled frame's window around `eval` or `resolve` + * (see ray_scope_frame_t.eval_window). */ +void ray_env_mark_eval_window(void) { + env_frames_moved(); + if (__VM && __VM->scope_depth > 0) + __VM->scope_stack[__VM->scope_depth - 1].eval_window = 1; } /* Materialize compiled-lambda locals into a fresh scope frame — the @@ -779,7 +1140,7 @@ void ray_env_pop_scope(void) { * let-locals whose initializer hasn't executed yet: in the tree walker * they wouldn't be bound at this point either, so they're skipped. */ ray_err_t ray_env_scope_bind(const int64_t* syms, int32_t n, ray_t** slots, - ray_t* self_obj) { + const uint8_t* rows, ray_t* self_obj) { ray_err_t err = ray_env_push_scope(); if (err != RAY_OK) return err; if (self_obj) { @@ -788,7 +1149,7 @@ ray_err_t ray_env_scope_bind(const int64_t* syms, int32_t n, ray_t** slots, } for (int32_t i = 0; i < n; i++) { if (!slots[i]) continue; - ray_err_t e = ray_env_set_local(syms[i], slots[i]); + ray_err_t e = ray_env_set_local_rows(syms[i], slots[i], rows ? rows[i] : 0); if (e != RAY_OK && e != RAY_ERR_RESERVED) { ray_env_pop_scope(); return e; diff --git a/src/lang/env.h b/src/lang/env.h index 5054a155c..70e7e92e0 100644 --- a/src/lang/env.h +++ b/src/lang/env.h @@ -43,6 +43,8 @@ static inline const char* ray_fn_name(const ray_t* fn) { ray_err_t ray_env_init(void); void ray_env_destroy(void); ray_t* ray_env_get(int64_t sym_id); +/* Borrowed flat global binding, ignoring local/query frames. */ +ray_t* ray_env_get_global(int64_t sym_id); ray_t* ray_env_get_local(int64_t sym_id); /* User-facing binder. Refuses any name starting with `.` — that root is @@ -140,6 +142,43 @@ int64_t ray_env_builtin_sym(const ray_t* fn); /* Local scope stack for lexical binding (let, do, lambda) */ ray_err_t ray_env_push_scope(void); +void ray_env_mark_lexical_scope(int32_t below); +/* A named-call boundary: lookups below it see only `table`'s columns + * (NULL for none) and then the globals. */ +ray_err_t ray_env_push_call_scope(ray_t* table, bool named); +/* Turn the top frame into a call boundary (its current bindings stay + * ordinary locals; source columns bind above them). */ +void ray_env_mark_call_scope(ray_t* table, bool named); +/* True inside a helper called from a query (a call frame above the + * query's frames); `named` reports whether it was called by name. */ +bool ray_env_in_query_helper(bool* named); +/* Bind a local with a row-provenance flag (0 no, 1 rows, 2 unknown). */ +ray_err_t ray_env_set_local_rows(int64_t sym_id, ray_t* val, uint8_t rows); +/* Provenance flag of the binding `sym_id` resolves to, or -1 if unbound. */ +int ray_env_binding_rows(int64_t sym_id); + +/* ray_env_resolve, also reporting through `rows` whether the value is a + * query source column (or its cell) read through a helper's call frame. */ +ray_t* ray_env_resolve_rows(int64_t sym_id, uint8_t* rows); +/* ray_env_resolve_rows for a name compiled code resolves at run time: an + * `eval` window on the scope stack belongs to a caller and is passed by. */ +ray_t* ray_env_resolve_compiled(int64_t sym_id, uint8_t* rows); +/* ray_env_resolve_compiled's per-thread answers, valid while this thread's + * frame epoch and the global epoch are those they were cached under; the + * VM reads them inline before calling it. */ +#define RAY_RESOLVE_CACHE_BITS 8 +typedef struct { int64_t sym; uint64_t fe, ge; ray_t* val; uint8_t rows; } ray_resolve_cache_t; +extern _Thread_local uint64_t g_frame_epoch; +extern _Atomic uint64_t g_global_epoch; +extern _Thread_local ray_resolve_cache_t g_resolve_cache[1 << RAY_RESOLVE_CACHE_BITS]; +static inline uint32_t ray_resolve_cache_slot(int64_t sym_id) { + return (uint32_t)(((uint64_t)sym_id * UINT64_C(0x9E3779B97F4A7C15)) >> (64 - RAY_RESOLVE_CACHE_BITS)); +} +/* ray_env_get for the compiler: an `eval` window on the scope stack belongs + * to a caller of the body being compiled and is passed by. */ +ray_t* ray_env_get_compiled(int64_t sym_id); +/* Mark the top scope frame as a compiled frame's `eval`/`resolve` window. */ +void ray_env_mark_eval_window(void); ray_err_t ray_env_push_query_scope(void); void ray_env_pop_scope(void); int32_t ray_env_scope_depth(void); @@ -148,10 +187,20 @@ int32_t ray_env_scope_depth(void); bool ray_env_query_scope_above(int32_t depth); ray_err_t ray_env_set_local(int64_t sym_id, ray_t* val); ray_t* ray_env_get_lexical_local(int64_t sym_id); +/* The same for a body an `eval` window's text calls: every window is + * passed by (see ray_scope_frame_t.eval_window). */ +ray_t* ray_env_get_lexical_local_callee(int64_t sym_id); bool ray_env_has_lexical_local(int64_t sym_id); +int32_t ray_env_lexical_scope_depth(int64_t sym_id); ray_err_t ray_env_set_query_local(int64_t sym_id, ray_t* val); ray_t* ray_env_capture_locals(void); -ray_err_t ray_env_push_capture(ray_t* capture); +/* The same, also returning the captures' row flags (RAY_U8, owned, NULL + * when none is set) and the serial of the innermost query frame (0 if + * none): the flags are meaningful only under that frame. */ +ray_t* ray_env_capture_locals_rows(ray_t** flags, uint32_t* serial); +ray_err_t ray_env_push_capture(ray_t* capture, ray_t* flags, uint32_t serial); +/* Serial of the innermost query frame, 0 outside queries. */ +uint32_t ray_env_query_serial(void); /* Compiled-lambda local materialization (OP_SCOPE_BEGIN / OP_SCOPE_END). * bind: push a fresh frame and bind syms[i] -> slots[i] (NULL slots — @@ -161,7 +210,7 @@ ray_err_t ray_env_push_capture(ray_t* capture); * sync: write the frame's (possibly let-updated) values back into the * slots, then pop the frame. */ ray_err_t ray_env_scope_bind(const int64_t* syms, int32_t n, ray_t** slots, - ray_t* self_obj); + const uint8_t* rows, ray_t* self_obj); void ray_env_scope_sync(const int64_t* syms, int32_t n, ray_t** slots); #endif /* RAY_ENV_H */ diff --git a/src/lang/eval.c b/src/lang/eval.c index a5f1d89c3..3a939c5b1 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -42,6 +42,7 @@ #include "core/qlog.h" /* ray_qlog_enabled — arm capture for query logging */ #include "store/serde.h" /* ray_serde_size — result footprint for spans */ #include "table/sym.h" +#include "store/col.h" /* ray_col_want_rows — gather read-ahead */ #include "mem/heap.h" #include "core/pool.h" #include "mem/sys.h" @@ -54,6 +55,30 @@ #include #include #include + +/* Row provenance of the value the most recent ray_eval returned: 1 derived + * from the active query's rows (a query frame's column binding, a helper's + * source column, a row-wise builtin over one, a compiled helper's result), + * 0 not, -1 unknown (an interpreted closure's result). Read by the caller + * right after the ray_eval that produced it. */ +static _Thread_local int8_t g_eval_rows = -1; + +/* Tri-state combination: a row operand makes the result rows; otherwise an + * unknown operand makes it unknown. */ +static inline int8_t rows_join(int8_t a, int8_t b) { + if (a == 1 || b == 1) return 1; + if (a < 0 || b < 0) return -1; + return 0; +} +/* The VM's encoding of the same: 0 no, 1 rows, 2 unknown. */ +static inline uint8_t vrows_join(uint8_t a, uint8_t b) { + if (a == 1 || b == 1) return 1; + if (a == 2 || b == 2) return 2; + return 0; +} +static inline uint8_t vrows_from(int8_t r) { return r < 0 ? 2 : (uint8_t)r; } +static inline int8_t vrows_to(uint8_t r) { return r == 2 ? -1 : (int8_t)r; } + #include #include #include @@ -278,6 +303,20 @@ static ray_t* try_sum_affine_expr(ray_t* expr, int* handled) { * (__VM->raise_val) — it must survive the unwind across any number of * bytecode invocations on this thread's stack. */ +/* The marker ray_return_fn raises: an error whose code is "return". The + * value travels in __VM->return_val; ray_take_return turns both back into + * the value at a lambda's call boundary. */ +static inline bool is_return_marker(ray_t* e) { + return e && RAY_IS_ERR(e) && e->slen == 6 && memcmp(e->sdata, "return", 6) == 0; +} +static ray_t* ray_take_return(ray_t* marker) { + ray_error_free(marker); + ray_t* val = __VM->return_val; + __VM->return_val = NULL; + if (!val) { val = RAY_NULL_OBJ; ray_retain(val); } + return val; +} + /* (raise value) — raise an error with the given value */ ray_t* ray_raise_fn(ray_t* val) { if (__VM->raise_val) ray_release(__VM->raise_val); @@ -297,6 +336,10 @@ ray_t* ray_raise_fn(ray_t* val) { * ((fn [data] (try (raise "x") data)) 123) -> 123 * * Borrows both `handler` and `err_val`; returns a new owned ref. */ +static ray_t* call_lambda_impl(ray_t* lambda, ray_t** call_args, int64_t argc, + bool query, uint64_t row_args, bool named, + int8_t* out_rows); + ray_t* ray_try_handle(ray_t* handler, ray_t* err_val) { if (handler->type == RAY_LAMBDA || handler->type == RAY_UNARY) return call_fn1(handler, err_val); /* borrows err_val */ @@ -304,6 +347,21 @@ ray_t* ray_try_handle(ray_t* handler, ray_t* err_val) { return handler; /* fallback value */ } +/* ray_try_handle that also reports the handler value's row provenance: + * a lambda handler's result flag, -1 (unknown) for a builtin, and + * `fallback_rows` for a plain fallback value. */ +static ray_t* try_handle_rows(ray_t* handler, ray_t* err_val, int8_t fallback_rows, int8_t* rows) { + *rows = -1; + if (handler->type == RAY_LAMBDA) { + ray_t* args[1] = { err_val }; + return call_lambda_impl(handler, args, 1, ray_active_query_table() != NULL, 0, true, rows); + } + if (handler->type == RAY_UNARY) return call_fn1(handler, err_val); + *rows = fallback_rows; + ray_retain(handler); + return handler; +} + /* (try expr handler) — evaluate expr; on error, dispatch the (evaluated) * handler via ray_try_handle (callable → invoked with the error value; * otherwise returned as a fallback value). @@ -311,11 +369,17 @@ ray_t* ray_try_handle(ray_t* handler, ray_t* err_val) { ray_t* ray_try_fn(ray_t* expr, ray_t* handler_expr) { ray_t* result = ray_eval(expr); if (!RAY_IS_ERR(result)) return result; + if (is_return_marker(result)) return result; /* a `return` is not an error */ /* Get error value (set by raise, or default for runtime errors) */ ray_t* err_val = __VM->raise_val; __VM->raise_val = NULL; if (!err_val) err_val = make_i64(0); + /* The caught error itself goes no further: errors are not refcounted, + * so ray_release would leave it allocated. Nor does the trace its + * unwind recorded. */ + ray_error_free(result); + ray_clear_error_trace(); /* Evaluate handler expression (in the current scope) */ ray_t* handler = ray_eval(handler_expr); @@ -324,9 +388,13 @@ ray_t* ray_try_fn(ray_t* expr, ray_t* handler_expr) { return handler; } - ray_t* handler_result = ray_try_handle(handler, err_val); + /* A lambda handler reports its result's provenance; a fallback value + * keeps the one its expression had (g_eval_rows after evaluating it). */ + int8_t handler_rows = -1; + ray_t* handler_result = try_handle_rows(handler, err_val, g_eval_rows, &handler_rows); ray_release(err_val); ray_release(handler); + g_eval_rows = handler_rows; return handler_result; } @@ -1480,6 +1548,8 @@ typedef struct { char* dst; const int64_t* idx; uint8_t esz; + int64_t rows; /* src's rows when each task reads ahead (gbi_want); 0 otherwise */ + int64_t row_end; /* one past the last row idx lists */ } gbi_ctx_t; static void gbi_fill_fn(void* ctxp, uint32_t wid, int64_t start, int64_t end) { @@ -1488,16 +1558,40 @@ static void gbi_fill_fn(void* ctxp, uint32_t wid, int64_t start, int64_t end) { const char* src = c->src; char* dst = c->dst; const int64_t* idx = c->idx; - switch (c->esz) { - case 8: for (int64_t i = start; i < end; i++) memcpy(dst + i*8, src + idx[i]*8, 8); break; - case 4: for (int64_t i = start; i < end; i++) memcpy(dst + i*4, src + idx[i]*4, 4); break; - case 2: for (int64_t i = start; i < end; i++) memcpy(dst + i*2, src + idx[i]*2, 2); break; - case 1: for (int64_t i = start; i < end; i++) dst[i] = src[idx[i]]; break; - case 16: for (int64_t i = start; i < end; i++) memcpy(dst + i*16, src + idx[i]*16, 16); break; - default: for (int64_t i = start; i < end; i++) memcpy(dst + i*c->esz, src + idx[i]*c->esz, c->esz); break; + /* the task's rows may span more than one read-ahead window: report + * them as the copy goes */ + for (int64_t lo = start; lo < end; lo += 1024) { + int64_t hi = end - lo < 1024 ? end : lo + 1024; + if (c->rows) ray_pool_scan_col_at(src, c->rows, idx[lo], c->row_end); + switch (c->esz) { + case 8: for (int64_t i = lo; i < hi; i++) memcpy(dst + i*8, src + idx[i]*8, 8); break; + case 4: for (int64_t i = lo; i < hi; i++) memcpy(dst + i*4, src + idx[i]*4, 4); break; + case 2: for (int64_t i = lo; i < hi; i++) memcpy(dst + i*2, src + idx[i]*2, 2); break; + case 1: for (int64_t i = lo; i < hi; i++) dst[i] = src[idx[i]]; break; + case 16: for (int64_t i = lo; i < hi; i++) memcpy(dst + i*16, src + idx[i]*16, 16); break; + default: for (int64_t i = lo; i < hi; i++) memcpy(dst + i*c->esz, src + idx[i]*c->esz, c->esz); break; + } } } +/* Reading a cold mapped column at scattered rows waits on one page fault + * at a time. When `idx` lists rows of a column registered for scan + * read-ahead (core/pool.c) in order, with about a row per page of their + * stretch or more, each task of the parallel gather keeps the rows past its + * own requested, paced with the gather; else the pages of the rows are + * requested up front (ray_col_want_rows). */ +static void gbi_want(gbi_ctx_t* gc, ray_t* vec, const int64_t* idx, int64_t n, bool par) { + if (!ray_pool_scan_on()) return; + int64_t lo = n > 0 ? idx[0] : -1, hi = n > 0 ? idx[n - 1] : -1; + if (par && lo >= 0 && lo <= hi && hi < vec->len && + (hi - lo + 1) * gc->esz / 4096 <= n && ray_pool_scan_holds(gc->src, vec->len)) { + gc->rows = vec->len; + gc->row_end = hi + 1; + return; + } + ray_col_want_rows(vec, idx, n); +} + /* Reorder vector elements by an index array */ ray_t* gather_by_idx(ray_t* vec, int64_t* idx, int64_t n) { int8_t type = vec->type; @@ -1533,7 +1627,9 @@ ray_t* gather_by_idx(ray_t* vec, int64_t* idx, int64_t n) { .dst = (char*)ray_data(result), .idx = idx, .esz = esz }; ray_pool_t* gpool = ray_pool_get(); - if (gbi_par_ok(gpool, n)) + bool par = gbi_par_ok(gpool, n); + gbi_want(&gc, vec, idx, n, par); /* scattered rows of a cold mapped column */ + if (par) ray_pool_dispatch(gpool, gbi_fill_fn, &gc, n); else gbi_fill_fn(&gc, 0, 0, n); @@ -1575,7 +1671,9 @@ ray_t* gather_by_idx(ray_t* vec, int64_t* idx, int64_t n) { .dst = (char*)ray_data(result), .idx = idx, .esz = esz }; ray_pool_t* gpool = ray_pool_get(); - if (gbi_par_ok(gpool, n)) + bool par = gbi_par_ok(gpool, n); + gbi_want(&gc, vec, idx, n, par); /* scattered rows of a cold mapped column */ + if (par) ray_pool_dispatch(gpool, gbi_fill_fn, &gc, n); else gbi_fill_fn(&gc, 0, 0, n); @@ -1881,11 +1979,12 @@ ray_t* ray_let_fn(ray_t* name_obj, ray_t* val_expr) { return ray_error("type", "let: name must be a symbol, got %s", ray_type_name(name_obj->type)); ray_t* val = ray_eval(val_expr); if (RAY_IS_ERR(val)) return val; + uint8_t rows = vrows_from(g_eval_rows); /* the local keeps its value's provenance */ /* Materialize lazy handles before binding */ if (ray_is_lazy(val)) val = ray_lazy_materialize(val); if (RAY_IS_ERR(val)) return val; - ray_err_t err = ray_env_set_local(name_obj->i64, val); + ray_err_t err = ray_env_set_local_rows(name_obj->i64, val, rows); if (err != RAY_OK) { ray_release(val); return ray_error(ray_err_code_str(err), NULL); } return val; } @@ -1895,6 +1994,9 @@ ray_t* ray_cond_fn(ray_t** args, int64_t n) { if (n < 2) return ray_error("domain", "if: expected at least 2 args (cond then), got %lld", (long long)n); ray_t* cond = ray_eval(args[0]); if (RAY_IS_ERR(cond)) return cond; + /* A vector condition tested whole: the expression may have needed + * row-by-row evaluation (see the opaque by: key). */ + if (!ray_is_atom(cond)) __VM->rows_cond++; /* Materialize lazy handles before testing truthiness */ if (ray_is_lazy(cond)) cond = ray_lazy_materialize(cond); @@ -2046,6 +2148,257 @@ ray_t* ray_times_fn(ray_t** args, int64_t n) { /* (fn [params...] body...) — create a lambda object. * Stores params list and body expressions in data area. */ +/* Sym ID of "self" for call_lambda's frame. It belongs to the current sym + * table: runtime destroy tears the table down and the next runtime can give + * "self" a different ID, so ray_lang_destroy resets it, as ray_compile_reset + * does for the compiler's special-form IDs. A stale ID bound the lambda under + * a name that was no longer "self", shadowing whatever variable owned it. */ +static int64_t g_call_self_sym = -1; + +/* Closures made by interpreted code (the top level, a lambda that could not + * compile, a literal inside a special form the compiler hands to the tree + * walker) share one compiled template per literal and capture set, as + * closures made by compiled code share theirs (OP_MKCLOSURE): the body's + * bytecode depends only on which captured names it mentions. The entry + * retains the literal's parameter and body nodes, so their addresses stay + * its own while it lives; a literal is matched by them and by its capture + * names. A lambda that is query text (LAMBDA_CAPQ) stays interpreted and + * never comes here. */ +enum { CLOSURE_TMPL_SLOTS = 256, CLOSURE_TMPL_MAX_BODY = 8 }; +typedef struct { + ray_t* params; /* the literal's parameter node */ + ray_t* body[CLOSURE_TMPL_MAX_BODY]; /* every body node: a literal built + * for eval can share first and last nodes with another + * and differ in the middle */ + int64_t nbody; + ray_t* mentioned; /* the symbols the body mentions (I64 vector) */ + bool dynamic; /* the body uses eval or resolve: every capture counts */ + bool failed; /* the body did not compile: its closures stay interpreted */ + ray_t* names; /* capture names (SYM vector) or NULL */ + ray_t* tmpl; /* the compiled template, or NULL when `failed` */ + int64_t bytes; /* what the literal's text holds (ray_closure_mentioned_syms) */ + ray_t* deps; /* a definition's entry (nothing captured, builtins + * baked on its first call): the call heads its code + * depends on (ray_compile_definition); NULL for a + * closure's */ +} closure_tmpl_t; +/* The entries keep their literals' text alive after every closure made + * from them is gone, so the table is bounded by bytes: a literal holding + * more than CLOSURE_TMPL_MAX_BYTES is not kept, and older entries make + * room once the table holds CLOSURE_TMPL_BUDGET. */ +enum { CLOSURE_TMPL_MAX_BYTES = RAY_CLOSURE_TMPL_MAX_BYTES, CLOSURE_TMPL_BUDGET = 1024 * 1024 }; +static _Thread_local closure_tmpl_t g_closure_tmpl[CLOSURE_TMPL_SLOTS]; +static _Thread_local uint32_t g_closure_tmpl_next; +static _Thread_local uint64_t g_closure_tmpl_epoch; +static _Thread_local int64_t g_closure_tmpl_bytes; /* sum of the entries' bytes */ + +static void closure_tmpl_drop(closure_tmpl_t* e) { + g_closure_tmpl_bytes -= e->bytes; + if (e->params) ray_release(e->params); + for (int64_t i = 0; i < e->nbody && i < CLOSURE_TMPL_MAX_BODY; i++) if (e->body[i]) ray_release(e->body[i]); + if (e->mentioned) ray_release(e->mentioned); + if (e->names) ray_release(e->names); + if (e->tmpl) ray_release(e->tmpl); + if (e->deps) ray_release(e->deps); + memset(e, 0, sizeof *e); +} + +/* The runtime is going away with everything the entries retain: release + * them (called by the thread destroying it, before the heap goes). */ +static void closure_tmpl_reset(void) { + for (int i = 0; i < CLOSURE_TMPL_SLOTS; i++) closure_tmpl_drop(&g_closure_tmpl[i]); + g_closure_tmpl_next = 0; + g_closure_tmpl_epoch = 0; + g_closure_tmpl_bytes = 0; +} + +/* Another thread's table after the runtime it filled it under was + * destroyed and a new one created: its objects are gone with that + * runtime's heap, so the entries are forgotten, not released. */ +static void closure_tmpl_forget(void) { + memset(g_closure_tmpl, 0, sizeof g_closure_tmpl); + g_closure_tmpl_next = 0; + g_closure_tmpl_bytes = 0; +} + +/* Does `closure`'s capture set, filtered by the entry's mentioned symbols, + * spell the entry's names? Walks the dict keys once, allocating nothing. */ +static bool closure_entry_names_match(const closure_tmpl_t* e, ray_t* closure) { + int64_t want = e->names ? e->names->len : 0; + if (!closure) return want == 0; + ray_t* keys = ray_dict_keys(closure); + if (!keys) return want == 0; + const int64_t* ment = e->mentioned ? (const int64_t*)ray_data(e->mentioned) : NULL; + int64_t nment = e->mentioned ? e->mentioned->len : 0; + int64_t at = 0; + for (int64_t i = 0; i < keys->len; i++) { + int64_t id = ray_read_sym(ray_data(keys), i, RAY_SYM, keys->attrs); + if (id == g_call_self_sym) continue; + bool counts = e->dynamic; + for (int64_t k = 0; !counts && k < nment; k++) counts = ment[k] == id; + if (!counts) continue; + if (at >= want || ray_read_sym(ray_data(e->names), at, RAY_SYM, e->names->attrs) != id) return false; + at++; + } + return at == want; +} + +static void closure_share_from(ray_t* lambda, ray_t* tmpl) { + if (LAMBDA_BC(tmpl)) { ray_retain(LAMBDA_BC(tmpl)); LAMBDA_BC(lambda) = LAMBDA_BC(tmpl); } + if (LAMBDA_CONSTS(tmpl)) { ray_retain(LAMBDA_CONSTS(tmpl)); LAMBDA_CONSTS(lambda) = LAMBDA_CONSTS(tmpl); } + if (LAMBDA_DBG(tmpl)) { ray_retain(LAMBDA_DBG(tmpl)); LAMBDA_DBG(lambda) = LAMBDA_DBG(tmpl); } + LAMBDA_NLOCALS(lambda) = LAMBDA_NLOCALS(tmpl); + lambda->attrs |= RAY_FN_COMPILED; +} + +static void closure_share_template(ray_t* lambda) { + ray_t* body = LAMBDA_BODY(lambda); + ray_t* params = LAMBDA_PARAMS(lambda); + /* A lambda with nothing captured is a definition: it compiles on its + * first call and bakes the builtins it names then, so a function + * rebound between its evaluation and that call, or a dict it reaches + * a function through, is the one it calls. A shared template would + * have baked them when the literal was evaluated. */ + if (!LAMBDA_CLOSURE(lambda)) return; + if (!body || body->type != RAY_LIST || body->len == 0 || !params) return; + if (body->len > CLOSURE_TMPL_MAX_BODY) return; /* compiles when called */ + if (g_closure_tmpl_epoch != ray_sym_epoch()) { + if (g_closure_tmpl_epoch) closure_tmpl_forget(); + g_closure_tmpl_epoch = ray_sym_epoch(); + } + ray_t** bn = (ray_t**)ray_data(body); + /* The literal's nodes first: a known literal's mentioned symbols are + * in its entries, so the capture names cost a pass over the dict keys + * rather than a walk of the body. */ + if (g_call_self_sym < 0) g_call_self_sym = ray_sym_intern("self", 4); + for (int i = 0; i < CLOSURE_TMPL_SLOTS; i++) { + closure_tmpl_t* e = &g_closure_tmpl[i]; + if ((!e->tmpl && !e->failed) || e->deps || e->params != params || e->nbody != body->len) continue; + bool same = true; + for (int64_t k = 0; k < body->len && same; k++) same = e->body[k] == bn[k]; + if (same && closure_entry_names_match(e, LAMBDA_CLOSURE(lambda))) { + if (e->failed) LAMBDA_NLOCALS(lambda) = -1; /* known not to compile */ + else closure_share_from(lambda, e->tmpl); + return; + } + } + /* A new literal, or a known one with another capture set. */ + bool dynamic = false; + int64_t weight = 0; + ray_t* mentioned = ray_closure_mentioned_syms(body, &dynamic, &weight); + if (!mentioned) return; + if (weight > CLOSURE_TMPL_MAX_BYTES) { + /* A literal built around a large constant is not kept: the table + * would hold the constant alive after its closures are gone. */ + ray_release(mentioned); + return; + } + ray_t* names = ray_closure_names_from(LAMBDA_CLOSURE(lambda), mentioned, dynamic); + ray_t* tmpl = ray_alloc(LAMBDA_SLOTS * sizeof(ray_t*)); + if (!tmpl || RAY_IS_ERR(tmpl)) { if (names) ray_release(names); ray_release(mentioned); return; } + tmpl->type = RAY_LAMBDA; + tmpl->attrs = 0; + tmpl->len = 0; + memset(ray_data(tmpl), 0, LAMBDA_SLOTS * sizeof(ray_t*)); + ray_retain(params); LAMBDA_PARAMS(tmpl) = params; + ray_retain(body); LAMBDA_BODY(tmpl) = body; + if (LAMBDA_NFO(lambda)) { ray_retain(LAMBDA_NFO(lambda)); LAMBDA_NFO(tmpl) = LAMBDA_NFO(lambda); } + /* A closure body: its free names resolve when it runs, as the tree + * walker resolves them, so one template serves every closure of the + * literal whatever is rebound in between. */ + bool compiled = ray_compile_with_captures(tmpl, names, true); + if (!compiled) { + /* Not compilable: the closure stays interpreted, and the entry + * remembers that so later closures from the literal skip the + * attempt. */ + ray_release(tmpl); + tmpl = NULL; + LAMBDA_NLOCALS(lambda) = -1; + } + closure_tmpl_t* e = &g_closure_tmpl[g_closure_tmpl_next++ % CLOSURE_TMPL_SLOTS]; + closure_tmpl_drop(e); + /* Make room within the budget, oldest entries first. */ + for (uint32_t k = 0; k < CLOSURE_TMPL_SLOTS && g_closure_tmpl_bytes + weight > CLOSURE_TMPL_BUDGET; k++) + closure_tmpl_drop(&g_closure_tmpl[(g_closure_tmpl_next + k) % CLOSURE_TMPL_SLOTS]); + ray_retain(params); e->params = params; + for (int64_t k = 0; k < body->len; k++) { ray_retain(bn[k]); e->body[k] = bn[k]; } + e->nbody = body->len; + e->mentioned = mentioned; /* owned */ + e->dynamic = dynamic; + e->failed = !compiled; + e->bytes = weight; + g_closure_tmpl_bytes += weight; + e->names = names; /* owned, may be NULL */ + e->tmpl = tmpl; /* owned, NULL when failed */ + if (compiled) closure_share_from(lambda, tmpl); +} + +/* A lambda with nothing captured compiles on its first call and bakes the + * builtins it names then. Another lambda of the same literal reuses that + * bytecode when, at its own first call, every call head the code was + * shaped by still names the builtin it named (or still names none): + * compiling afresh would produce the same code. The table bounds what + * it keeps as for closures. */ +static bool definition_deps_hold(ray_t* deps) { + const int64_t* d = (const int64_t*)ray_data(deps); + for (int64_t i = 0; i + 1 < deps->len; i += 2) { + ray_t* fn = ray_env_get_compiled(d[i]); + bool builtin = fn && (fn->type == RAY_UNARY || fn->type == RAY_BINARY || fn->type == RAY_VARY); + if ((builtin ? (int64_t)(uintptr_t)fn : 0) != d[i + 1]) return false; + } + return true; +} + +static void definition_compile(ray_t* lambda) { + ray_t* body = LAMBDA_BODY(lambda); + ray_t* params = LAMBDA_PARAMS(lambda); + if (!body || body->type != RAY_LIST || body->len == 0 || !params || + body->len > CLOSURE_TMPL_MAX_BODY) { ray_compile(lambda); return; } + if (g_closure_tmpl_epoch != ray_sym_epoch()) { + if (g_closure_tmpl_epoch) closure_tmpl_forget(); + g_closure_tmpl_epoch = ray_sym_epoch(); + } + ray_t** bn = (ray_t**)ray_data(body); + for (int i = 0; i < CLOSURE_TMPL_SLOTS; i++) { + closure_tmpl_t* e = &g_closure_tmpl[i]; + if (!e->deps || e->params != params || e->nbody != body->len) continue; + bool same = true; + for (int64_t k = 0; k < body->len && same; k++) same = e->body[k] == bn[k]; + if (!same) continue; + if (definition_deps_hold(e->deps)) { closure_share_from(lambda, e->tmpl); return; } + closure_tmpl_drop(e); /* a head was rebound: this literal compiles afresh */ + break; + } + bool dynamic = false; + int64_t weight = 0; + ray_t* mentioned = ray_closure_mentioned_syms(body, &dynamic, &weight); + if (!mentioned || weight > CLOSURE_TMPL_MAX_BYTES) { + if (mentioned) ray_release(mentioned); + ray_compile(lambda); + return; + } + ray_t* deps = NULL; + if (!ray_compile_definition(lambda, &deps)) { ray_release(mentioned); return; } + closure_tmpl_t* e = &g_closure_tmpl[g_closure_tmpl_next++ % CLOSURE_TMPL_SLOTS]; + closure_tmpl_drop(e); + for (uint32_t k = 0; k < CLOSURE_TMPL_SLOTS && g_closure_tmpl_bytes + weight > CLOSURE_TMPL_BUDGET; k++) + closure_tmpl_drop(&g_closure_tmpl[(g_closure_tmpl_next + k) % CLOSURE_TMPL_SLOTS]); + ray_retain(params); e->params = params; + for (int64_t k = 0; k < body->len; k++) { ray_retain(bn[k]); e->body[k] = bn[k]; } + e->nbody = body->len; + e->mentioned = mentioned; /* owned */ + e->bytes = weight; + g_closure_tmpl_bytes += weight; + ray_retain(lambda); e->tmpl = lambda; /* its bytecode is the template's */ + e->deps = deps; /* owned */ +} + +/* Compile a lambda on its first call (see lambda_wants_compile). */ +static void lambda_compile(ray_t* lambda) { + if (LAMBDA_CLOSURE(lambda)) ray_compile(lambda); + else definition_compile(lambda); +} + ray_t* ray_fn(ray_t** args, int64_t n) { if (n < 2) return ray_error("domain", "fn: expected at least 2 args (params body), got %lld", (long long)n); /* args[0] = param vector (list of name symbols), args[1..n-1] = body exprs */ @@ -2082,18 +2435,25 @@ ray_t* ray_fn(ray_t** args, int64_t n) { } } - ray_t* closure = ray_env_capture_locals(); + ray_t* caprows = NULL; + uint32_t capq = 0; + ray_t* closure = ray_env_capture_locals_rows(&caprows, &capq); if (closure && RAY_IS_ERR(closure)) return closure; - - /* Create lambda object with space for 8 slots: - * [0] params, [1] body, [2] bytecode, [3] constants, [4] n_locals, - * [5] nfo (source location), [6] dbg (debug metadata), [7] closure. */ - ray_t* lambda = ray_alloc(8 * sizeof(ray_t*)); - if (!lambda) { ray_release(closure); return ray_error("oom", NULL); } + /* A lambda made inside a query is query text: it keeps the query's + * literal rule by running on the tree walker, so it is never compiled. + * The serial of the query frame marks it. */ + if (!capq) capq = ray_env_query_serial(); + + /* Create lambda object (layout in eval.h): params, body, bytecode, + * constants, n_locals, nfo, dbg, closure, capture row flags, query. */ + ray_t* lambda = ray_alloc(LAMBDA_SLOTS * sizeof(ray_t*)); + if (!lambda) { ray_release(closure); if (caprows) ray_release(caprows); return ray_error("oom", NULL); } lambda->type = RAY_LAMBDA; lambda->attrs = 0; lambda->len = 0; - memset(ray_data(lambda), 0, 8 * sizeof(ray_t*)); + memset(ray_data(lambda), 0, LAMBDA_SLOTS * sizeof(ray_t*)); + LAMBDA_CAPROWS(lambda) = caprows; /* owned */ + LAMBDA_CAPQ(lambda) = capq; /* Store params list */ ray_retain(params_list); @@ -2131,6 +2491,11 @@ ray_t* ray_fn(ray_t** args, int64_t n) { LAMBDA_DBG(lambda) = NULL; LAMBDA_CLOSURE(lambda) = closure; + /* Share the literal's compiled template unless the lambda is query text + * or has a closure the compiler cannot bind (the compiler's own gate). */ + if (!capq && ray_closure_shape_ok(closure)) + closure_share_template(lambda); + return lambda; } @@ -2193,24 +2558,58 @@ static void add_eval_error_frame(ray_t* nfo, ray_t* node) { /* Execute compiled bytecode for a lambda. */ static ray_t* vm_exec(ray_t* lambda, ray_t** call_args, int64_t argc); +static ray_t* vm_exec_rows(ray_t* lambda, ray_t** call_args, int64_t argc, + uint64_t row_args, uint8_t* out_rows); -/* Sym ID of "self" for call_lambda's frame. It belongs to the current sym - * table: runtime destroy tears the table down and the next runtime can give - * "self" a different ID, so ray_lang_destroy resets it, as ray_compile_reset - * does for the compiler's special-form IDs. A stale ID bound the lambda under - * a name that was no longer "self", shadowing whatever variable owned it. */ -static int64_t g_call_self_sym = -1; -/* Call a lambda: compile on first call, then execute bytecode. */ -ray_t* call_lambda(ray_t* lambda, ray_t** call_args, int64_t argc) { - /* Lazy compilation on first call */ - if (!LAMBDA_CLOSURE(lambda) && !LAMBDA_IS_COMPILED(lambda)) { - ray_compile(lambda); - } +/* Inside a helper called from a query (a call frame above the query's + * frames). Literal symbols keep bytecode's meaning in a helper called by + * name; a lambda written inline in the query is query text and follows the + * column rule. */ +bool ray_eval_query_helper_active(void) { + return ray_env_in_query_helper(NULL); +} + +bool ray_eval_query_helper_literals(void) { + bool named = false; + return ray_env_in_query_helper(&named) && named; +} - /* If compilation succeeded, run bytecode; otherwise fall back to tree-walk */ +/* Ordinary calls use bytecode; query fallback interprets the retained AST + * so concat can distinguish column parameters from bound collections. */ +/* Whether a call should compile the lambda first. A lambda made inside a + * query (LAMBDA_CAPQ set and no bytecode) is query text and keeps the + * query's literal rule on the tree walker, so it never compiles; a closure + * made by compiled code (OP_MKCLOSURE) is born compiled, sharing its + * literal's bytecode. Everything else compiles on its first call. */ +static inline bool lambda_wants_compile(ray_t* lambda) { + /* NLOCALS -1 marks a body that did not compile: it stays on the tree + * walker without another attempt per call. */ + return !LAMBDA_IS_COMPILED(lambda) && !LAMBDA_CAPQ(lambda) && LAMBDA_NLOCALS(lambda) != -1; +} + +static ray_t* call_lambda_impl(ray_t* lambda, ray_t** call_args, int64_t argc, + bool query, uint64_t row_args, bool named, + int8_t* out_rows) { + if (out_rows) *out_rows = -1; + /* A lambda called inside a named helper's body is that body's text. */ + if (query && !named) named = ray_eval_query_helper_literals(); + /* Lazy compilation (see lambda_wants_compile); a closure's captures + * become locals of its body (OP_BINDCAPS). */ + if (lambda_wants_compile(lambda)) + lambda_compile(lambda); if (LAMBDA_IS_COMPILED(lambda)) { - return vm_exec(lambda, call_args, argc); + if (!query) return vm_exec(lambda, call_args, argc); + /* Row provenance rides on the VM stack. The call frame hides the + * query's aliases and locals; source columns stay visible through + * its table, then the globals, as in a body the planner inlines. */ + if (ray_env_push_call_scope(ray_query_helper_table(), named) != RAY_OK) + return ray_error("oom", NULL); + uint8_t result_rows = 0; + ray_t* result = vm_exec_rows(lambda, call_args, argc, row_args, &result_rows); + ray_env_pop_scope(); + if (out_rows) *out_rows = vrows_to(result_rows); + return result; } /* Fallback: tree-walking interpreter */ @@ -2223,12 +2622,19 @@ ray_t* call_lambda(ray_t* lambda, ray_t** call_args, int64_t argc) { return ray_error("arity", "expected %" PRId64 " args, got %" PRId64, param_count, argc); bool has_closure = LAMBDA_CLOSURE(lambda) != NULL; - if (has_closure && ray_env_push_capture(LAMBDA_CLOSURE(lambda)) != RAY_OK) + if (has_closure && ray_env_push_capture(LAMBDA_CLOSURE(lambda), LAMBDA_CAPROWS(lambda), + LAMBDA_CAPQ(lambda)) != RAY_OK) return ray_error("oom", NULL); + if (query && has_closure) ray_env_mark_call_scope(ray_query_helper_table(), named); if (ray_env_push_scope() != RAY_OK) { if (has_closure) ray_env_pop_scope(); return ray_error("oom", NULL); } + /* Closures made inside the body capture down to this call's frames + * (its captures and parameters), never the caller's locals. */ + ray_env_mark_lexical_scope(has_closure ? 1 : 0); + + if (query && !has_closure) ray_env_mark_call_scope(ray_query_helper_table(), named); /* Bind 'self' to the current lambda for recursion */ if (g_call_self_sym < 0) g_call_self_sym = ray_sym_intern("self", 4); @@ -2236,27 +2642,59 @@ ray_t* call_lambda(ray_t* lambda, ray_t** call_args, int64_t argc) { int64_t* param_ids = (int64_t*)ray_data(params_list); for (int64_t i = 0; i < param_count && i < argc; i++) { - (void)ray_env_set_local(param_ids[i], call_args[i]); + ray_t* arg = call_args[i]; + if (arg && ray_is_lazy(arg)) { + /* A lazy handle is single-use: bind the concrete value, as the + * bytecode VM does when it loads a lazy parameter. */ + ray_retain(arg); + arg = ray_lazy_materialize(arg); + if (!arg || RAY_IS_ERR(arg)) { + ray_env_pop_scope(); + if (has_closure) ray_env_pop_scope(); + return arg ? arg : ray_error("type", NULL); + } + } + /* Parameters carry the arguments' row provenance into the body. */ + uint8_t rows = query && i < 64 ? (uint8_t)((row_args >> i) & 1) : 0; + (void)ray_env_set_local_rows(param_ids[i], arg, rows); + if (arg != call_args[i]) ray_release(arg); } int64_t body_count = ray_len(body); ray_t** body_exprs = (ray_t**)ray_data(body); ray_t* result = NULL; + __VM->lambda_depth++; for (int64_t i = 0; i < body_count; i++) { if (result) ray_release(result); result = ray_eval(body_exprs[i]); if (RAY_IS_ERR(result)) { + if (is_return_marker(result)) { + /* (return x) somewhere in this statement: the body ends here + * with x, as it does when compiled. */ + result = ray_take_return(result); + g_eval_rows = -1; + break; + } + __VM->lambda_depth--; ray_env_pop_scope(); if (has_closure) ray_env_pop_scope(); return result; } } + __VM->lambda_depth--; + if (out_rows) *out_rows = g_eval_rows; /* the body's last value's provenance */ ray_env_pop_scope(); if (has_closure) ray_env_pop_scope(); return result; } +ray_t* call_lambda(ray_t* lambda, ray_t** call_args, int64_t argc) { + if (lambda_wants_compile(lambda)) lambda_compile(lambda); + if (LAMBDA_IS_COMPILED(lambda)) return vm_exec(lambda, call_args, argc); + return call_lambda_impl(lambda, call_args, argc, false, 0, false, NULL); +} + /* ══════════════════════════════════════════ * Stack-based VM executor (computed goto, frame-based) * ══════════════════════════════════════════ */ @@ -2270,6 +2708,110 @@ ray_t* call_lambda(ray_t* lambda, ray_t** call_args, int64_t argc) { * allocates a private ray_exec_t per invocation and leaves __VM alone. */ static ray_t* vm_exec(ray_t* lambda, ray_t** call_args, int64_t argc) { + return vm_exec_rows(lambda, call_args, argc, 0, NULL); +} + +/* Whether a builtin keeps row provenance: the planner lowers it row by + * row, so its result over a column-derived operand is column-derived. + * Cached by object for one symbol-table epoch: the builtin objects live + * as long as the runtime, and a re-init frees and reallocates them. */ +static bool vm_fn_rowwise(const ray_t* fn_obj) { + static _Thread_local struct { const ray_t* fn; bool rowwise; } cache[64]; + static _Thread_local uint64_t epoch; + if (epoch != ray_sym_epoch() || !epoch) { + memset(cache, 0, sizeof cache); + epoch = ray_sym_epoch(); + } + size_t h = ((uintptr_t)fn_obj >> 4) & 63; + if (cache[h].fn == fn_obj) return cache[h].rowwise; + const char* name = ray_fn_name(fn_obj); + bool rowwise = ray_query_rowwise_builtin(ray_sym_intern(name, strlen(name))); + cache[h].fn = fn_obj; + cache[h].rowwise = rowwise; + return rowwise; +} + +/* Control forms return one of their operands, so the operand's provenance + * is the form's; every other special form builds a new value. */ +static bool form_inherits_rows(const ray_t* head) { + static const char* const forms[] = { "if", "do", "let", "set", "and", "or", "try" }; + const char* name = ray_fn_name(head); + for (size_t i = 0; i < sizeof forms / sizeof *forms; i++) + if (strcmp(name, forms[i]) == 0) return true; + return false; +} + +static bool vm_text_value(const ray_t* v) { + return v->type == RAY_SYM || v->type == RAY_STR || v->type == -RAY_SYM || v->type == -RAY_STR; +} + +/* A binary builtin applied by compiled code. Consumes `left` and `right`; + * `left_rows`/`right_rows` are their row-provenance flags and `*out_rows` + * receives the result's. Returns an owned result or error. */ +static ray_t* vm_call_binary(ray_t* fn_obj, ray_t* left, ray_t* right, + uint8_t left_rows, uint8_t right_rows, uint8_t* out_rows) { + ray_binary_fn fn = (ray_binary_fn)(uintptr_t)fn_obj->i64; + ray_t *result; + *out_rows = 0; + /* Materialise lazy args for non-lazy-aware fns; ray_lazy_materialize + * consumes the owned ref it is given. */ + if (!(fn_obj->attrs & RAY_FN_LAZY_AWARE)) { + if (left && ray_is_lazy(left)) { + left = ray_lazy_materialize(left); + if (!left || RAY_IS_ERR(left)) { ray_release(right); return left ? left : ray_error("type", NULL); } + } + if (right && ray_is_lazy(right)) { + right = ray_lazy_materialize(right); + if (!right || RAY_IS_ERR(right)) { ray_release(left); return right ? right : ray_error("type", NULL); } + } + } + RAY_ASSERT_VALUE(left); RAY_ASSERT_VALUE(right); + if (RAY_UNLIKELY(RAY_IS_NULL(left) || RAY_IS_NULL(right))) { + result = (fn == (ray_binary_fn)ray_eq_fn || fn == (ray_binary_fn)ray_neq_fn) + ? fn(left, right) : ray_error("type", NULL); + } else if (fn == ray_concat_fn && (left_rows == 1 || right_rows == 1) && + vm_text_value(left) && vm_text_value(right) && + (left_rows == 1 || ray_is_atom(left)) && (right_rows == 1 || ray_is_atom(right))) { + /* Query text concat: a column's cells joined row by row, as the + * planner does for the query's own expressions. Without row data + * among the operands, a call inside a function keeps ordinary + * collection semantics; a bound vector never has row provenance. */ + result = ray_concat_text_fn(left, right, + (left->type == -RAY_STR && left_rows == 1) || + (right->type == -RAY_STR && right_rows == 1), + (uint8_t)((left_rows == 1 ? 1 : 0) | (right_rows == 1 ? 2 : 0))); + *out_rows = 1; + /* Fast path: atoms have negative type — skip collection check entirely. + * Only call is_collection when at least one arg has type >= 0 (vector/list). */ + } else { + uint8_t joined = vrows_join(left_rows, right_rows); + if ((fn_obj->attrs & RAY_FN_ATOMIC) && (left->type >= 0 || right->type >= 0)) + result = atomic_map_binary_op(fn, RAY_FN_OPCODE(fn_obj), left, right); + else + result = fn(left, right); + *out_rows = joined && vm_fn_rowwise(fn_obj) ? joined : 0; + } + ray_release(left); + ray_release(right); + return result; +} + +/* `row_args` bit i: parameter i is derived from the rows of the active + * query. The flag rides on vm.rows beside every stack slot: loads and + * stores copy it, a builtin the planner lowers row by row keeps it, + * anything else clears it, and `concat` consults it to choose between + * text and collection semantics. `out_rows` receives the result's flag. + * + * The dispatch loop starts on a page boundary: where its handlers fall + * relative to fetch and branch-predictor boundaries moved its speed when + * code in an unrelated object grew or shrank. How much depends on the + * machine: on one box an 896-byte shift cost 5-10% on VM-bound loops; a + * second measurement saw under 2% on the same loops and 4-6% on others. */ +#if defined(__GNUC__) || defined(__clang__) +__attribute__((aligned(4096))) +#endif +static ray_t* vm_exec_rows(ray_t* lambda, ray_t** call_args, int64_t argc, + uint64_t row_args, uint8_t* out_rows) { /* Computed goto dispatch table */ static void *dispatch[OP__COUNT] = { [OP_RET] = &&op_ret, @@ -2297,6 +2839,14 @@ static ray_t* vm_exec(ray_t* lambda, ray_t** call_args, int64_t argc) { [OP_SCOPE_END] = &&op_scope_end, [OP_TRYH] = &&op_tryh, [OP_FORCE] = &&op_force, + [OP_BINDCAPS] = &&op_bindcaps, + [OP_LOADSELF] = &&op_loadself, + [OP_MKCLOSURE] = &&op_mkclosure, + [OP_LOADENVG] = &&op_loadenvg, + [OP_SCOPE_EVAL] = &&op_scope_eval, + [OP_CALL1R] = &&op_call1r, + [OP_CALL2R] = &&op_call2r, + [OP_CALLNR] = &&op_callnr, }; /* Arity check before allocating VM state */ @@ -2317,7 +2867,11 @@ static ray_t* vm_exec(ray_t* lambda, ray_t** call_args, int64_t argc) { ray_t *vm_block = ray_alloc(sizeof(ray_exec_t)); if (!vm_block || RAY_IS_ERR(vm_block)) return ray_error("oom", NULL); ray_exec_t *vmp = (ray_exec_t *)ray_data(vm_block); - memset(vmp, 0, sizeof(ray_exec_t)); + /* Only the header needs clearing: every stack, return and trap slot is + * written before it is read, and the locals are set below. Zeroing + * the whole block cost more than a small call's body. */ + vmp->sp = 0; vmp->fp = 0; vmp->rp = 0; vmp->tp = 0; vmp->fn = NULL; + __VM->lambda_depth++; #define vm (*vmp) @@ -2328,11 +2882,16 @@ static ray_t* vm_exec(ray_t* lambda, ray_t** call_args, int64_t argc) { vm.fp = 0; vm.sp = n_locals; - /* Bind parameters into local slots */ + /* Bind parameters into local slots; the other locals start empty */ int64_t param_count = ray_len(LAMBDA_PARAMS(lambda)); for (int64_t i = 0; i < param_count && i < argc; i++) { ray_retain(call_args[i]); vm.ps[i] = call_args[i]; + vm.rows[i] = i < 64 ? (uint8_t)((row_args >> i) & 1) : 0; + } + for (int32_t i = (int32_t)(param_count < argc ? param_count : argc); i < n_locals; i++) { + vm.ps[i] = NULL; + vm.rows[i] = 0; } uint8_t *code = (uint8_t *)ray_data(LAMBDA_BC(lambda)); @@ -2341,10 +2900,13 @@ static ray_t* vm_exec(ray_t* lambda, ray_t** call_args, int64_t argc) { ray_t *vm_err_obj = NULL; #define DISPATCH() goto *dispatch[code[ip++]] -#define PUSH(v) do { if (vm.sp >= VM_STACK_SIZE) goto vm_error_limit; vm.ps[vm.sp++] = (v); } while(0) +#define PUSH(v) do { if (vm.sp >= VM_STACK_SIZE) goto vm_error_limit; vm.rows[vm.sp] = 0; vm.ps[vm.sp++] = (v); } while(0) +#define PUSHR(v,r) do { if (vm.sp >= VM_STACK_SIZE) goto vm_error_limit; vm.rows[vm.sp] = (uint8_t)(r); vm.ps[vm.sp++] = (v); } while(0) #define POP() (vm.ps[--vm.sp]) +#define POPPED_ROWS() (vm.rows[vm.sp]) /* flag of the value POP() just returned */ #define PEEK() (vm.ps[vm.sp - 1]) #define LOCAL(s) (vm.ps[vm.fp + (s)]) +#define LROWS(s) (vm.rows[vm.fp + (s)]) DISPATCH(); @@ -2385,15 +2947,17 @@ op_loadenv: { } if (val) ray_retain(val); else val = make_i64(0); - PUSH(val); + PUSHR(val, LROWS(slot)); DISPATCH(); } op_storeenv: { uint8_t slot = code[ip++]; ray_t *val = POP(); + uint8_t val_rows = POPPED_ROWS(); if (LOCAL(slot)) ray_release(LOCAL(slot)); LOCAL(slot) = val; + LROWS(slot) = val_rows; DISPATCH(); } @@ -2408,21 +2972,33 @@ op_pop: { op_dup: { ray_t *val = PEEK(); ray_retain(val); - PUSH(val); + PUSHR(val, vm.rows[vm.sp - 1]); DISPATCH(); } op_resolve: { uint8_t idx = code[ip++]; ray_t *name_obj = cpool[idx]; - ray_t *val = ray_env_resolve(name_obj->i64); + uint8_t val_rows = 0; /* set when a query helper reads a source column */ + { + /* The answer cached for this name while nothing it was read from + * has moved (ray_env_resolve_compiled). */ + ray_resolve_cache_t *e = &g_resolve_cache[ray_resolve_cache_slot(name_obj->i64)]; + if (e->sym == name_obj->i64 && e->fe == g_frame_epoch && e->val && + e->ge == atomic_load_explicit(&g_global_epoch, memory_order_relaxed)) { + ray_retain(e->val); + PUSHR(e->val, e->rows); + DISPATCH(); + } + } + ray_t *val = ray_env_resolve_compiled(name_obj->i64, &val_rows); if (!val) goto vm_error_name; /* env_resolve returns an owned ref (rc >= 1); no extra retain needed. * It can also return a real error (e.g. nyi from a parted-target link * deref inside the dotted walker) — surface that as a VM error rather * than pushing it onto the stack as if it were a normal value. */ if (RAY_IS_ERR(val)) { vm_err_obj = val; goto vm_error; } - PUSH(val); + PUSHR(val, val_rows); DISPATCH(); } @@ -2430,10 +3006,11 @@ op_resolve_w: { uint16_t idx = (uint16_t)((code[ip] << 8) | code[ip + 1]); ip += 2; ray_t *name_obj = cpool[idx]; - ray_t *val = ray_env_resolve(name_obj->i64); + uint8_t val_rows = 0; + ray_t *val = ray_env_resolve_compiled(name_obj->i64, &val_rows); if (!val) goto vm_error_name; if (RAY_IS_ERR(val)) { vm_err_obj = val; goto vm_error; } - PUSH(val); + PUSHR(val, val_rows); DISPATCH(); } @@ -2488,14 +3065,25 @@ op_jmpf: { int16_t offset = (int16_t)((code[ip] << 8) | code[ip + 1]); ip += 2; ray_t *cond = POP(); + if (cond && !ray_is_atom(cond)) __VM->rows_cond++; /* a vector tested whole */ int truthy = is_truthy(cond); ray_release(cond); if (!truthy) ip += offset; DISPATCH(); } +op_call1r: + /* A builtin a closure body resolved when it ran: OP_CALL1 while the + * name still holds a unary builtin, the general call (which reads + * the argument count operand) otherwise, the generic null included, + * since the general call applies the tree walker's null rule. */ + if (RAY_UNLIKELY(!vm.ps[vm.sp - 2] || vm.ps[vm.sp - 2]->type != RAY_UNARY || + RAY_IS_NULL(vm.ps[vm.sp - 1]))) + goto op_callf; + ip++; op_call1: { ray_t *arg = POP(); + uint8_t arg_rows = POPPED_ROWS(); ray_t *fn_obj = POP(); if (RAY_UNLIKELY(fn_is_restricted(fn_obj))) { ray_release(arg); @@ -2524,16 +3112,24 @@ op_call1: { result = atomic_map_unary(fn, arg); else result = fn(arg); + uint8_t result_rows = arg_rows && vm_fn_rowwise(fn_obj) ? arg_rows : 0; ray_release(arg); ray_release(fn_obj); if (RAY_IS_ERR(result)) { vm_err_obj = result; goto vm_error; } - PUSH(result); + PUSHR(result, result_rows); DISPATCH(); } -op_call2: { +op_call2r: { + /* OP_CALL2 for a resolved binary builtin, with the same rows in and + * out as a baked call; the general call when the name holds anything + * else. */ + if (RAY_UNLIKELY(!vm.ps[vm.sp - 3] || vm.ps[vm.sp - 3]->type != RAY_BINARY)) goto op_callf; + ip++; ray_t *right = POP(); + uint8_t right_rows = POPPED_ROWS(); ray_t *left = POP(); + uint8_t left_rows = POPPED_ROWS(); ray_t *fn_obj = POP(); if (RAY_UNLIKELY(fn_is_restricted(fn_obj))) { ray_release(left); @@ -2542,53 +3138,52 @@ op_call2: { vm_err_obj = ray_error("access", "restricted"); goto vm_error; } - ray_binary_fn fn = (ray_binary_fn)(uintptr_t)fn_obj->i64; - ray_t *result; - /* Materialise lazy args for non-lazy-aware fns. - * left/right are owned refs (POPped from VM stack); ray_lazy_materialize - * consumes them internally — no extra ray_release needed after the call. */ - if (!(fn_obj->attrs & RAY_FN_LAZY_AWARE)) { - if (left && ray_is_lazy(left)) { - left = ray_lazy_materialize(left); /* consumes owned ref */ - if (!left || RAY_IS_ERR(left)) { - ray_release(right); ray_release(fn_obj); - vm_err_obj = left ? left : ray_error("type", NULL); - goto vm_error; - } - } - if (right && ray_is_lazy(right)) { - right = ray_lazy_materialize(right); /* consumes owned ref */ - if (!right || RAY_IS_ERR(right)) { - ray_release(left); ray_release(fn_obj); - vm_err_obj = right ? right : ray_error("type", NULL); - goto vm_error; - } - } + uint8_t result_rows = 0; + ray_t *result = vm_call_binary(fn_obj, left, right, left_rows, right_rows, &result_rows); + ray_release(fn_obj); + if (RAY_IS_ERR(result)) { vm_err_obj = result; goto vm_error; } + PUSHR(result, result_rows); + DISPATCH(); +} + +op_call2: { + ray_t *right = POP(); + uint8_t right_rows = POPPED_ROWS(); + ray_t *left = POP(); + uint8_t left_rows = POPPED_ROWS(); + ray_t *fn_obj = POP(); + if (RAY_UNLIKELY(fn_is_restricted(fn_obj))) { + ray_release(left); + ray_release(right); + ray_release(fn_obj); + vm_err_obj = ray_error("access", "restricted"); + goto vm_error; } - RAY_ASSERT_VALUE(left); RAY_ASSERT_VALUE(right); - if (RAY_UNLIKELY(RAY_IS_NULL(left) || RAY_IS_NULL(right))) { - result = (fn == (ray_binary_fn)ray_eq_fn || fn == (ray_binary_fn)ray_neq_fn) - ? fn(left, right) : ray_error("type", NULL); - /* Fast path: atoms have negative type — skip collection check entirely. - * Only call is_collection when at least one arg has type >= 0 (vector/list). */ - } else if ((fn_obj->attrs & RAY_FN_ATOMIC) && (left->type >= 0 || right->type >= 0)) - result = atomic_map_binary_op(fn, RAY_FN_OPCODE(fn_obj), left, right); - else - result = fn(left, right); - ray_release(left); - ray_release(right); + uint8_t result_rows = 0; + ray_t *result = vm_call_binary(fn_obj, left, right, left_rows, right_rows, &result_rows); ray_release(fn_obj); if (RAY_IS_ERR(result)) { vm_err_obj = result; goto vm_error; } - PUSH(result); + PUSHR(result, result_rows); DISPATCH(); } +op_callnr: { + /* OP_CALLN for a resolved variadic builtin; the general call when the + * name holds anything else. */ + uint8_t nr = code[ip]; + if (RAY_UNLIKELY(nr > 64 || !vm.ps[vm.sp - 1 - nr] || vm.ps[vm.sp - 1 - nr]->type != RAY_VARY)) goto op_callf; + goto op_calln; +} + op_calln: { uint8_t n = code[ip++]; if (n > 64) goto vm_error; ray_t *fn_args[64]; - for (int32_t i = n - 1; i >= 0; i--) + uint8_t args_rows = 0; + for (int32_t i = n - 1; i >= 0; i--) { fn_args[i] = POP(); + args_rows = vrows_join(args_rows, POPPED_ROWS()); + } ray_t *fn_obj = POP(); if (RAY_UNLIKELY(fn_is_restricted(fn_obj))) { for (int32_t i = 0; i < n; i++) ray_release(fn_args[i]); @@ -2602,11 +3197,12 @@ op_calln: { if (err) { ray_release(fn_obj); vm_err_obj = err; goto vm_error; } } ray_t *result = fn(fn_args, n); + uint8_t result_rows = args_rows && vm_fn_rowwise(fn_obj) ? args_rows : 0; for (int32_t i = 0; i < n; i++) ray_release(fn_args[i]); ray_release(fn_obj); if (RAY_IS_ERR(result)) { vm_err_obj = result; goto vm_error; } - PUSH(result); + PUSHR(result, result_rows); DISPATCH(); } @@ -2614,14 +3210,22 @@ op_callf: { uint8_t n = code[ip++]; if (n > 64) goto vm_error; ray_t *fn_args[64]; - for (int32_t i = n - 1; i >= 0; i--) + uint8_t arg_rows[64]; + uint8_t args_any = 0; + uint64_t args_bits = 0; + for (int32_t i = n - 1; i >= 0; i--) { fn_args[i] = POP(); + arg_rows[i] = POPPED_ROWS(); + args_any = vrows_join(args_any, arg_rows[i]); + if (arg_rows[i] == 1) args_bits |= UINT64_C(1) << i; + } ray_t *fn_obj = POP(); - /* Compiled lambda: push frame, switch to callee bytecode */ + /* Compiled lambda: push frame, switch to callee bytecode. A lambda + * made inside a query stays on the tree walker (see call_lambda_impl). */ if (fn_obj->type == RAY_LAMBDA) { - if (!LAMBDA_IS_COMPILED(fn_obj)) - ray_compile(fn_obj); + if (lambda_wants_compile(fn_obj)) + lambda_compile(fn_obj); if (LAMBDA_IS_COMPILED(fn_obj)) { /* All checks before any VM state mutation. @@ -2654,10 +3258,14 @@ op_callf: { /* Bind parameters */ int64_t bind = pcnt < n ? pcnt : n; - for (int64_t i = 0; i < bind; i++) + for (int64_t i = 0; i < bind; i++) { LOCAL(i) = fn_args[i]; /* transfer ownership from args */ - for (int32_t i = (int32_t)bind; i < callee_locals; i++) + LROWS(i) = arg_rows[i]; + } + for (int32_t i = (int32_t)bind; i < callee_locals; i++) { LOCAL(i) = NULL; + LROWS(i) = 0; + } for (int64_t i = bind; i < n; i++) ray_release(fn_args[i]); /* excess args */ @@ -2675,6 +3283,7 @@ op_callf: { /* Non-lambda or uncompiled: dispatch by type */ { ray_t *result; + int8_t lambda_rows = -1; switch (fn_obj->type) { case RAY_UNARY: if (fn_is_restricted(fn_obj)) { for (int32_t i = 0; i < n; i++) ray_release(fn_args[i]); result = ray_error("access", "restricted"); break; } @@ -2707,7 +3316,15 @@ op_callf: { fn_args[0] = ray_lazy_materialize(fn_args[0]); /* consumes owned ref */ if (!fn_args[0] || RAY_IS_ERR(fn_args[0])) { result = fn_args[0] ? fn_args[0] : ray_error("type", NULL); fn_args[0] = NULL; break; } } - result = unary(fn_args[0]); + /* The generic null: only nil?, type and ser take it, as on the + * tree walker and in OP_CALL1. */ + if (RAY_UNLIKELY(RAY_IS_NULL(fn_args[0]))) + result = (unary == (ray_unary_fn)ray_nil_fn || unary == (ray_unary_fn)ray_type_fn || + unary == (ray_unary_fn)ray_ser_fn) ? unary(fn_args[0]) : ray_error("type", NULL); + else if ((fn_obj->attrs & RAY_FN_ATOMIC) && fn_args[0] && fn_args[0]->type >= 0) + result = atomic_map_unary(unary, fn_args[0]); + else + result = unary(fn_args[0]); ray_release(fn_args[0]); unary_done: break; @@ -2727,9 +3344,17 @@ op_callf: { if (!fn_args[1] || RAY_IS_ERR(fn_args[1])) { result = fn_args[1] ? fn_args[1] : ray_error("type", NULL); ray_release(fn_args[0]); fn_args[0] = NULL; fn_args[1] = NULL; break; } } } - result = ((ray_binary_fn)(uintptr_t)fn_obj->i64)(fn_args[0], fn_args[1]); - ray_release(fn_args[0]); - ray_release(fn_args[1]); + /* The same path as OP_CALL2: the elementwise map for an atomic + * builtin, the query text rule for concat, the row provenance + * join. A closure body reaches here for every builtin it names, + * since it resolves them when it runs. */ + { + uint8_t bin_rows = 0; + result = vm_call_binary(fn_obj, fn_args[0], fn_args[1], + (uint8_t)(args_bits & 1), (uint8_t)((args_bits >> 1) & 1), &bin_rows); + fn_args[0] = fn_args[1] = NULL; /* consumed */ + lambda_rows = bin_rows ? 1 : 0; /* reported below as the result's flag */ + } break; case RAY_VARY: if (fn_is_restricted(fn_obj)) { for (int32_t i = 0; i < n; i++) ray_release(fn_args[i]); result = ray_error("access", "restricted"); break; } @@ -2740,18 +3365,26 @@ op_callf: { result = ((ray_vary_fn)(uintptr_t)fn_obj->i64)(fn_args, n); for (int32_t i = 0; i < n; i++) ray_release(fn_args[i]); break; - case RAY_LAMBDA: - result = call_lambda(fn_obj, fn_args, n); + case RAY_LAMBDA: { + /* An uncompiled lambda (a closure): interpreted, with the + * arguments' row provenance when a query is active. */ + bool in_query = ray_active_query_table() != NULL; + result = call_lambda_impl(fn_obj, fn_args, n, in_query, args_bits, true, &lambda_rows); for (int32_t i = 0; i < n; i++) ray_release(fn_args[i]); break; + } default: for (int32_t i = 0; i < n; i++) ray_release(fn_args[i]); result = ray_error("type", "apply: head is not callable, got %s", ray_type_name(fn_obj->type)); break; } + uint8_t result_rows = fn_obj->type == RAY_LAMBDA ? vrows_from(lambda_rows) + : fn_obj->type == RAY_BINARY ? (uint8_t)(lambda_rows == 1) + : args_any && (fn_obj->type == RAY_UNARY || fn_obj->type == RAY_VARY) && + vm_fn_rowwise(fn_obj) ? args_any : 0; ray_release(fn_obj); if (RAY_IS_ERR(result)) { vm_err_obj = result; goto vm_error; } - PUSH(result); + PUSHR(result, result_rows); DISPATCH(); } } @@ -2774,8 +3407,10 @@ op_calls: { vm.fp = vm.sp - argc; /* Extend stack for extra locals beyond params (let bindings etc.) */ - for (int32_t i = argc; i < n_locals; i++) + for (int32_t i = argc; i < n_locals; i++) { + vm.rows[vm.sp] = 0; vm.ps[vm.sp++] = NULL; + } ip = 0; DISPATCH(); @@ -2790,7 +3425,7 @@ op_calld: { ray_t *result = ray_eval(ast); ray_release(ast); if (RAY_IS_ERR(result)) { vm_err_obj = result; goto vm_error; } - PUSH(result); + PUSHR(result, vrows_from(g_eval_rows)); DISPATCH(); } /* n>0: build call list and eval */ @@ -2815,15 +3450,17 @@ op_calld: { ray_t *result = ray_eval(call_list); ray_release(call_list); if (RAY_IS_ERR(result)) { vm_err_obj = result; goto vm_error; } - PUSH(result); + PUSHR(result, vrows_from(g_eval_rows)); DISPATCH(); } op_ret: { ray_t *result; + uint8_t result_rows = 0; bool from_stack = (vm.sp > vm.fp + n_locals); if (from_stack) { result = POP(); + result_rows = POPPED_ROWS(); ray_retain(result); /* prevent free during cleanup if aliased in locals */ } else { result = RAY_NULL_OBJ; @@ -2834,13 +3471,14 @@ op_ret: { ray_t *v = vm.ps[--vm.sp]; if (v) ray_release(v); } - /* Undo protective retain — POP's reference is the caller's ownership */ if (from_stack) ray_release(result); if (vm.rp == 0) { /* Top-level return */ + if (out_rows) *out_rows = result_rows; ray_release(vm.fn); + __VM->lambda_depth--; #undef vm ray_free(vm_block); return result; /* caller owns the POP'd reference */ @@ -2860,7 +3498,7 @@ op_ret: { n_locals = LAMBDA_NLOCALS(vm.fn); } /* Self-call (fn==NULL): vm.fn/code/cpool/n_locals are already correct */ - PUSH(result); + PUSHR(result, result_rows); DISPATCH(); } @@ -2890,11 +3528,170 @@ op_tryh: { * is invoked with the error; any other value is the fallback result. */ ray_t* err_val = POP(); ray_t* handler = POP(); - ray_t* result = ray_try_handle(handler, err_val); /* borrows both */ + uint8_t handler_rows = POPPED_ROWS(); + int8_t result_rows = -1; + ray_t* result = try_handle_rows(handler, err_val, vrows_to(handler_rows), &result_rows); /* borrows both */ ray_release(err_val); ray_release(handler); if (RAY_IS_ERR(result)) { vm_err_obj = result; goto vm_error; } - PUSH(result); + PUSHR(result, vrows_from(result_rows)); + DISPATCH(); +} + +op_bindcaps: { + /* The closure's captures become local slots (the compiled closure's + * prologue): cpool[idx] holds (name, slot) pairs; each name is looked + * up in the closure dict. A name the dict lacks (a `let` that had not + * run when the closure was made) leaves its slot empty, so a read of + * it falls back to the global, as on the tree walker. The capture's + * row flag applies while the query frame the closure was made under + * is the innermost one. */ + uint8_t idx = code[ip++]; + ray_t *pairs = cpool[idx]; + ray_t *cap = LAMBDA_CLOSURE(vm.fn); + ray_t *ckeys = cap && cap->type == RAY_DICT ? ray_dict_keys(cap) : NULL; + ray_t *cvals = cap && cap->type == RAY_DICT ? ray_dict_vals(cap) : NULL; + if (!pairs || pairs->type != RAY_I64) goto vm_error_name; + if (cap && (!ckeys || !cvals || ckeys->type != RAY_SYM || cvals->type != RAY_LIST || ckeys->len != cvals->len)) + goto vm_error_name; + int64_t ncap = ckeys ? ckeys->len : 0; + ray_t *flags = LAMBDA_CAPROWS(vm.fn); + bool live = flags && flags->len == ncap && LAMBDA_CAPQ(vm.fn) && + LAMBDA_CAPQ(vm.fn) == ray_env_query_serial(); + const int64_t *pv = (const int64_t*)ray_data(pairs); + for (int64_t i = 0, guess = 0; i + 1 < pairs->len; i += 2, guess++) { + int64_t name = pv[i], slot = pv[i + 1]; + int64_t at = -1; + if (guess < ncap && ray_read_sym(ray_data(ckeys), guess, RAY_SYM, ckeys->attrs) == name) at = guess; + for (int64_t k = 0; at < 0 && k < ncap; k++) + if (ray_read_sym(ray_data(ckeys), k, RAY_SYM, ckeys->attrs) == name) at = k; + if (LOCAL(slot)) { ray_release(LOCAL(slot)); LOCAL(slot) = NULL; } + LROWS(slot) = 0; + if (at < 0) continue; + ray_t *val = ((ray_t**)ray_data(cvals))[at]; + if (!val) continue; + ray_retain(val); + LOCAL(slot) = val; + LROWS(slot) = live ? ((uint8_t*)ray_data(flags))[at] : 0; + } + DISPATCH(); +} + +op_mkclosure: { + /* Stack: [.., template, names, slots]. A closure of the template: + * it shares the template's bytecode, constants, debug map and locals + * count, and captures the current frame's slots named by `names`, with + * their row flags, which apply while the innermost query frame is the + * one of now. A slot still empty (its `let` has not run) is not + * captured, as the tree walker would not bind it either; a lazy slot + * is materialized first, into the slot too: a lazy handle is single-use + * (materializing frees its graph in place), and the dict would hold a + * dead handle after the closure's first call. Rayfall text does not + * reach here with one (call sites materialize lazy arguments), but a + * caller of the C API can. */ + ray_t *slots = POP(); + ray_t *names = POP(); + ray_t *tmpl = POP(); + if (!tmpl || tmpl->type != RAY_LAMBDA || !names || names->type != RAY_SYM || + !slots || slots->type != RAY_I64 || names->len != slots->len) { + ray_release(slots); ray_release(names); ray_release(tmpl); + goto vm_error; + } + int64_t ncap = names->len; + ray_t *keys = ray_sym_vec_new(RAY_SYM_W64, ncap > 0 ? ncap : 1); + ray_t *vals = ray_list_new(ncap > 0 ? ncap : 1); + ray_t *flags = ray_vec_new(RAY_U8, ncap > 0 ? ncap : 1); + ray_t *lam = ray_alloc(LAMBDA_SLOTS * sizeof(ray_t*)); + if (!keys || RAY_IS_ERR(keys) || !vals || RAY_IS_ERR(vals) || !flags || RAY_IS_ERR(flags) || !lam || RAY_IS_ERR(lam)) { + if (keys && !RAY_IS_ERR(keys)) ray_release(keys); + if (vals && !RAY_IS_ERR(vals)) ray_release(vals); + if (flags && !RAY_IS_ERR(flags)) ray_release(flags); + if (lam && !RAY_IS_ERR(lam)) { lam->type = -RAY_I64; ray_release(lam); } + ray_release(slots); ray_release(names); ray_release(tmpl); + vm_err_obj = ray_error("oom", NULL); + goto vm_error; + } + keys->len = 0; flags->len = 0; + bool any_flag = false; + for (int64_t i = 0; i < ncap; i++) { + int64_t slot = ((const int64_t*)ray_data(slots))[i]; + if (slot < 0 || slot >= n_locals) continue; + ray_t *v = LOCAL(slot); + if (!v) continue; + if (ray_is_lazy(v)) { + v = ray_lazy_materialize(v); /* consumes the slot's ref */ + LOCAL(slot) = v && !RAY_IS_ERR(v) ? v : NULL; + if (!v || RAY_IS_ERR(v)) { + ray_release(keys); ray_release(vals); ray_release(flags); + lam->type = -RAY_I64; ray_release(lam); + ray_release(slots); ray_release(names); ray_release(tmpl); + vm_err_obj = v ? v : ray_error("type", NULL); + goto vm_error; + } + } + ((int64_t*)ray_data(keys))[keys->len++] = ray_read_sym(ray_data(names), i, RAY_SYM, names->attrs); + vals = ray_list_append(vals, v); + uint8_t r = LROWS(slot) == 1 ? 1 : 0; + ((uint8_t*)ray_data(flags))[flags->len++] = r; + if (r) any_flag = true; + } + lam->type = RAY_LAMBDA; + lam->attrs = tmpl->attrs; + lam->len = 0; + memset(ray_data(lam), 0, LAMBDA_SLOTS * sizeof(ray_t*)); + ray_retain(LAMBDA_PARAMS(tmpl)); LAMBDA_PARAMS(lam) = LAMBDA_PARAMS(tmpl); + ray_retain(LAMBDA_BODY(tmpl)); LAMBDA_BODY(lam) = LAMBDA_BODY(tmpl); + if (LAMBDA_BC(tmpl)) { ray_retain(LAMBDA_BC(tmpl)); LAMBDA_BC(lam) = LAMBDA_BC(tmpl); } + if (LAMBDA_CONSTS(tmpl)) { ray_retain(LAMBDA_CONSTS(tmpl)); LAMBDA_CONSTS(lam) = LAMBDA_CONSTS(tmpl); } + if (LAMBDA_NFO(tmpl)) { ray_retain(LAMBDA_NFO(tmpl)); LAMBDA_NFO(lam) = LAMBDA_NFO(tmpl); } + if (LAMBDA_DBG(tmpl)) { ray_retain(LAMBDA_DBG(tmpl)); LAMBDA_DBG(lam) = LAMBDA_DBG(tmpl); } + LAMBDA_NLOCALS(lam) = LAMBDA_NLOCALS(tmpl); + if (keys->len > 0) { + LAMBDA_CLOSURE(lam) = ray_dict_new(keys, vals); /* consumes both */ + if (!LAMBDA_CLOSURE(lam) || RAY_IS_ERR(LAMBDA_CLOSURE(lam))) { + LAMBDA_CLOSURE(lam) = NULL; ray_release(flags); ray_release(lam); + ray_release(slots); ray_release(names); ray_release(tmpl); + vm_err_obj = ray_error("oom", NULL); + goto vm_error; + } + } else { ray_release(keys); ray_release(vals); } + if (any_flag) { LAMBDA_CAPROWS(lam) = flags; LAMBDA_CAPQ(lam) = ray_env_query_serial(); } + else ray_release(flags); + ray_release(slots); ray_release(names); ray_release(tmpl); + PUSHR(lam, 0); + DISPATCH(); +} + +op_loadenvg: { + /* A `let` slot that may still be empty: the local when bound, else + * the global of that name (a name error when there is none), as the + * tree walker resolves a name whose `let` has not run. */ + uint8_t slot = code[ip++]; + uint16_t idx = (uint16_t)((code[ip] << 8) | code[ip + 1]); + ip += 2; + ray_t *val = LOCAL(slot); + if (val) { + if (ray_is_lazy(val)) { + val = ray_lazy_materialize(val); + if (!val || RAY_IS_ERR(val)) { vm_err_obj = val ? val : ray_error("type", NULL); LOCAL(slot) = NULL; goto vm_error; } + LOCAL(slot) = val; + } + ray_retain(val); + PUSHR(val, LROWS(slot)); + DISPATCH(); + } + ray_t *name_obj = cpool[idx]; + uint8_t val_rows = 0; + val = ray_env_resolve_compiled(name_obj->i64, &val_rows); + if (!val) goto vm_error_name; + if (RAY_IS_ERR(val)) { vm_err_obj = val; goto vm_error; } + PUSHR(val, val_rows); + DISPATCH(); +} + +op_loadself: { + ray_retain(vm.fn); + PUSHR(vm.fn, 0); DISPATCH(); } @@ -2902,24 +3699,35 @@ op_force: { /* Materialize a lazy TOS so a let-bound local holds a concrete, * reusable value (a lazy handle is single-use). */ ray_t* v = POP(); + uint8_t v_rows = POPPED_ROWS(); if (v && ray_is_lazy(v)) { v = ray_lazy_materialize(v); /* consumes; concrete or error */ if (!v || RAY_IS_ERR(v)) { vm_err_obj = v ? v : ray_error("type", NULL); goto vm_error; } } - PUSH(v); + PUSHR(v, v_rows); DISPATCH(); } +op_scope_eval: op_scope_begin: { /* Stack: [.., syms_vec] — materialize the live locals (slot i holds * the value of syms[i]) plus self into a fresh scope frame so the * OP_CALLD that follows can resolve them via the tree walker. */ + bool eval_window = code[ip - 1] == OP_SCOPE_EVAL; ray_t *syms = POP(); + /* The locals' row provenance travels with the bindings, so the tree + * walker inside the window sees it as it sees any local's. */ ray_err_t err = ray_env_scope_bind((const int64_t*)ray_data(syms), (int32_t)syms->len, - &vm.ps[vm.fp], vm.fn); + &vm.ps[vm.fp], &vm.rows[vm.fp], vm.fn); ray_release(syms); if (err != RAY_OK) goto vm_error_limit; + /* An eval window serves the evaluated text: a lambda that text calls + * resolves its free names past it (ray_env_resolve_compiled). */ + if (eval_window) ray_env_mark_eval_window(); + /* A closure's captures sit in local slots (bound by the prologue), so + * the window binds them with the other locals, and nothing from the + * caller's frames can stand in for one. */ DISPATCH(); } @@ -2927,8 +3735,14 @@ op_scope_end: { /* Stack: [.., calld_result, syms_vec] — sync the frame back into the * slots and pop it; the dynamic eval's result stays on the stack. */ ray_t *syms = POP(); + /* A local rebound inside the window has unknown provenance: clear its + * flag, as for any value the VM did not derive itself. */ + ray_t *before[256]; /* a frame has at most 256 slots (compile.c add_local) */ + int64_t nsync = syms->len < 256 ? syms->len : 256; + for (int64_t i = 0; i < nsync; i++) before[i] = LOCAL(i); ray_env_scope_sync((const int64_t*)ray_data(syms), (int32_t)syms->len, &vm.ps[vm.fp]); + for (int64_t i = 0; i < nsync; i++) if (LOCAL(i) != before[i]) LROWS(i) = 2; ray_release(syms); DISPATCH(); } @@ -2957,6 +3771,22 @@ op_scope_end: { vm_err_detail = NULL; vm_error_cleanup: { + /* A `return` evaluated by the tree walker inside this frame (a window + * around a special form) arrives as the return marker: it is this + * frame's return, not an error. Traps armed in this frame and the + * window's scope frames go with it. */ + if (vm_err_obj && is_return_marker(vm_err_obj)) { + ray_t *rv = ray_take_return(vm_err_obj); + vm_err_obj = NULL; + while (vm.tp > 0 && vm.ts[vm.tp - 1].rp >= vm.rp) { + vm.tp--; + ray_release(vm.ts[vm.tp].fn); + } + while (ray_env_scope_depth() > scope_base) + ray_env_pop_scope(); + PUSHR(rv, 0); + goto op_ret; + } /* Check for trap frame */ if (vm.tp > 0) { vm.tp--; @@ -2982,20 +3812,20 @@ vm_error_cleanup: { /* Get error value. If __VM->raise_val is set, a user (raise x) * just ran — its value is the real payload the handler must - * see. vm_err_obj is the generic error-sentinel returned - * from ray_raise_fn (or a VM-detected error like arity); - * release it if we picked __VM->raise_val. For VM-only errors, - * __VM->raise_val stays NULL and vm_err_obj is used. */ - ray_t *err_val; - if (__VM->raise_val) { - if (vm_err_obj) ray_release(vm_err_obj); - err_val = __VM->raise_val; - } else { - err_val = vm_err_obj; - } - vm_err_obj = NULL; + * see. Otherwise the handler gets 0, as ray_try_fn gives it for + * a runtime error. vm_err_obj, the error itself (the sentinel + * ray_raise_fn returns, or a builtin's or the VM's own), goes no + * further: errors are not refcounted, so ray_release would leave + * it allocated. */ + ray_t *err_val = __VM->raise_val; __VM->raise_val = NULL; if (!err_val) err_val = make_i64(0); + if (vm_err_obj) { + if (RAY_IS_ERR(vm_err_obj)) ray_error_free(vm_err_obj); + else ray_release(vm_err_obj); + } + vm_err_obj = NULL; + ray_clear_error_trace(); /* frames an inner call's unwind recorded */ /* Restore context and push error value */ ray_release(vm.fn); @@ -3029,6 +3859,7 @@ vm_error_cleanup: { if (vm.rs[i].fn) ray_release(vm.rs[i].fn); for (int32_t i = 0; i < vm.tp; i++) ray_release(vm.ts[i].fn); + __VM->lambda_depth--; #undef vm ray_free(vm_block); if (vm_err_obj) @@ -3040,9 +3871,12 @@ vm_error_cleanup: { #undef DISPATCH #undef PUSH +#undef PUSHR #undef POP +#undef POPPED_ROWS #undef PEEK #undef LOCAL +#undef LROWS #undef vm } @@ -3319,7 +4153,8 @@ static void ray_register_builtins(void) { /* Collection operations */ register_unary("distinct", RAY_FN_NONE | RAY_FN_LAZY_AWARE, ray_distinct_fn); - register_binary("in", RAY_FN_NONE, ray_in_fn); + register_binary("in", RAY_FN_NONE, ray_in_eval_fn); + register_binary("not-in", RAY_FN_NONE, ray_not_in_fn); register_binary("except", RAY_FN_NONE, ray_except_fn); register_binary("union", RAY_FN_NONE, ray_union_fn); register_binary("sect", RAY_FN_NONE, ray_sect_fn); @@ -3724,6 +4559,7 @@ ray_err_t ray_lang_init(void) { void ray_lang_destroy(void) { if (__VM && __VM->raise_val) { ray_release(__VM->raise_val); __VM->raise_val = NULL; } + closure_tmpl_reset(); /* Reset global Datalog rule storage */ ray_dl_reset_rules(); ray_env_destroy(); @@ -3791,6 +4627,7 @@ ray_t* ray_eval(ray_t* obj) { } ray_t* ret; + int8_t rows = -1; /* provenance of ret; published as g_eval_rows at out: */ /* Direct-builtin profiling span: opened just before the head-dispatch * switch below (for UNARY/BINARY/VARY builtins), closed at `out:`. @@ -3818,7 +4655,8 @@ ray_t* ray_eval(ray_t* obj) { if (name_str) ray_release(name_str); } - ray_t* val = ray_env_resolve(obj->i64); + uint8_t val_rows = 0; /* a query's column binding, or a helper's */ + ray_t* val = ray_env_resolve_rows(obj->i64, &val_rows); if (!val) { ray_t* ns = ray_sym_str(obj->i64); if (ns) { @@ -3835,6 +4673,7 @@ ray_t* ray_eval(ray_t* obj) { * it directly rather than treating it as a found value. */ if (RAY_IS_ERR(val)) { ret = val; goto out; } /* env_resolve hands back an owned ref; no extra retain. */ + rows = vrows_to(val_rows); ret = val; goto out; } /* Literal symbol (ATTR_QUOTED set). Inside a query, a literal that @@ -3842,24 +4681,27 @@ ray_t* ray_eval(ray_t* obj) { * consult ONLY the active query table's column set — never the env * scope chain — so a literal never captures a lambda/let local, and * the rule fires only while a query is active (ray_active_query_table - * is NULL otherwise). A literal naming no column returns itself. */ - if (obj->type == -RAY_SYM) { + * is NULL otherwise). A literal naming no column returns itself. + * Named helper bodies keep bytecode's literal semantics; an inline + * lambda is query text, and a nested query re-enables its own + * column-name interpretation. */ + if (obj->type == -RAY_SYM && !ray_eval_query_helper_literals()) { /* The column — or, during a per-row evaluation, its cell in the * current row (ray_active_query_literal). */ ray_t* v = ray_active_query_literal(obj->i64); - if (v) { ret = v; goto out; } + if (v) { ret = v; rows = 1; goto out; } } ray_retain(obj); - ret = obj; goto out; + ret = obj; rows = 0; goto out; } /* Non-list vectors (incl. RAY_DICT/RAY_TABLE): return themselves — * dict literals are self-evaluating; values stay unevaluated. Use * the (dict ...) builtin for evaluated construction. */ - if (obj->type != RAY_LIST) { ray_retain(obj); ret = obj; goto out; } + if (obj->type != RAY_LIST) { ray_retain(obj); ret = obj; rows = 0; goto out; } /* Empty list */ - if (ray_len(obj) == 0) { ray_retain(obj); ret = obj; goto out; } + if (ray_len(obj) == 0) { ray_retain(obj); ret = obj; rows = 0; goto out; } /* List: evaluate first element, dispatch by type */ ray_t** elems = (ray_t**)ray_data(obj); @@ -3946,10 +4788,15 @@ ray_t* ray_eval(ray_t* obj) { if (fn_is_restricted(head)) { ray_release(head); ret = ray_error("access", "restricted"); goto out; } ray_unary_fn fn = (ray_unary_fn)(uintptr_t)head->i64; ray_binary_fn fn2 = unary_binary_overload(fn); + /* Row provenance follows a builtin the planner lowers row by row. */ + bool rowwise = ray_active_query_table() && vm_fn_rowwise(head); if (n == 3 && fn2) { ray_t* left = ray_eval(elems[1]); + int8_t left_rows = g_eval_rows; if (!left || RAY_IS_ERR(left)) { ray_release(head); ret = left ? left : ray_error("type", NULL); goto out; } ray_t* right = ray_eval(elems[2]); + int8_t right_rows = g_eval_rows; + rows = rowwise ? rows_join(left_rows, right_rows) : 0; ray_release(head); if (!right || RAY_IS_ERR(right)) { ray_release(left); ret = right ? right : ray_error("type", NULL); goto out; } if (ray_is_lazy(left)) { @@ -3974,7 +4821,7 @@ ray_t* ray_eval(ray_t* obj) { if (handled) { ray_release(head); ret = fast ? fast : ray_error("type", NULL); - goto out; + rows = 0; goto out; } } if (fn == (ray_unary_fn)ray_count_fn) { @@ -3983,10 +4830,11 @@ ray_t* ray_eval(ray_t* obj) { if (handled) { ray_release(head); ret = fast ? fast : ray_error("type", NULL); - goto out; + rows = 0; goto out; } } ray_t* arg = ray_eval(elems[1]); + rows = rowwise ? g_eval_rows : 0; ray_release(head); if (arg && RAY_IS_ERR(arg)) { ret = arg; goto out; } /* Materialise lazy arg for non-lazy-aware fns. @@ -4015,15 +4863,21 @@ ray_t* ray_eval(ray_t* obj) { ray_binary_fn fn = (ray_binary_fn)(uintptr_t)head->i64; uint8_t fn_attrs = head->attrs; if (fn_attrs & RAY_FN_SPECIAL_FORM) { + bool inherits = form_inherits_rows(head); ray_release(head); - ret = fn(elems[1], elems[2]); goto out; + ret = fn(elems[1], elems[2]); + rows = inherits ? g_eval_rows : 0; + goto out; } + bool rowwise = ray_active_query_table() && vm_fn_rowwise(head); ray_t* left = ray_eval(elems[1]); + int8_t left_rows = g_eval_rows; if (left && RAY_IS_ERR(left)) { ray_release(head); ret = left; goto out; } ray_t* right = ray_eval(elems[2]); + int8_t right_rows = g_eval_rows; if (right && RAY_IS_ERR(right)) { ray_release(head); if (left) ray_release(left); ret = right; goto out; @@ -4066,8 +4920,34 @@ ray_t* ray_eval(ray_t* obj) { uint16_t fn_opcode = RAY_FN_OPCODE(head); ray_release(head); ray_t* result; + rows = rowwise ? rows_join(left_rows, right_rows) : 0; if ((fn_attrs & RAY_FN_ATOMIC) && (is_collection(left) || is_collection(right))) result = atomic_map_binary_op(fn, fn_opcode, left, right); + else if (fn == ray_concat_fn && ray_active_query_table() && + (left->type == RAY_SYM || left->type == RAY_STR || + left->type == -RAY_SYM || left->type == -RAY_STR) && + (right->type == RAY_SYM || right->type == RAY_STR || + right->type == -RAY_SYM || right->type == -RAY_STR)) { + /* Row by row, a column's cell is an atom: it still carries + * the column's row provenance, and a STR cell its type. An + * interpreted helper's result has unknown provenance; its + * syntax decides. In the query's own expression two scalar + * text operands join; inside a function a call without row + * data among its operands keeps collection semantics. */ + bool lr = left_rows >= 0 ? left_rows > 0 : ray_query_expr_reads_rows(elems[1]); + bool rr = right_rows >= 0 ? right_rows > 0 : ray_query_expr_reads_rows(elems[2]); + bool scalar_ok = !ray_eval_query_helper_active() || lr || rr; + if (scalar_ok && (ray_is_atom(left) || lr) && (ray_is_atom(right) || rr)) { + result = ray_concat_text_fn(left, right, + (left->type == -RAY_STR && lr) || + (right->type == -RAY_STR && rr), + (uint8_t)((lr ? 1 : 0) | (rr ? 2 : 0))); + rows = lr || rr; + } else { + result = fn(left, right); + rows = 0; + } + } else result = fn(left, right); ray_release(left); @@ -4078,14 +4958,21 @@ ray_t* ray_eval(ray_t* obj) { if (fn_is_restricted(head)) { ray_release(head); ret = ray_error("access", "restricted"); goto out; } ray_vary_fn fn = (ray_vary_fn)(uintptr_t)head->i64; if (head->attrs & RAY_FN_SPECIAL_FORM) { + /* A control form returns one of its operands; any other + * form (a query, a table op) builds a new value. */ + bool inherits = form_inherits_rows(head); ray_release(head); - ret = fn(elems + 1, n - 1); goto out; + ret = fn(elems + 1, n - 1); + rows = inherits ? g_eval_rows : 0; + goto out; } int64_t argc = n - 1; if (argc > 64) { ray_release(head); ret = ray_error("domain", "call: too many args, max 64, got %lld", (long long)argc); goto out; } ray_t* args[64]; + int8_t any_rows = 0; for (int64_t i = 0; i < argc; i++) { args[i] = ray_eval(elems[i + 1]); + any_rows = rows_join(any_rows, g_eval_rows); if (!args[i] || RAY_IS_ERR(args[i])) { ray_t* err = (!args[i]) ? ray_error("type", NULL) : args[i]; for (int64_t j = 0; j < i; j++) ray_release(args[j]); @@ -4093,6 +4980,8 @@ ray_t* ray_eval(ray_t* obj) { ret = err; goto out; } } + rows = fn == ray_return_fn ? any_rows + : any_rows && ray_active_query_table() && vm_fn_rowwise(head) ? any_rows : 0; if (!(head->attrs & RAY_FN_LAZY_AWARE)) { ray_t* err = materialize_owned_args(args, argc); if (err) { ray_release(head); ret = err; goto out; } @@ -4106,8 +4995,10 @@ ray_t* ray_eval(ray_t* obj) { int64_t argc = n - 1; if (argc > 64) { ray_release(head); ret = ray_error("domain", "call: too many args, max 64, got %lld", (long long)argc); goto out; } ray_t* args[64]; + int8_t arg_rows[64]; for (int64_t i = 0; i < argc; i++) { args[i] = ray_eval(elems[i + 1]); + arg_rows[i] = g_eval_rows; if (!args[i] || RAY_IS_ERR(args[i])) { ray_t* err = (!args[i]) ? ray_error("type", NULL) : args[i]; for (int64_t j = 0; j < i; j++) ray_release(args[j]); @@ -4115,7 +5006,18 @@ ray_t* ray_eval(ray_t* obj) { ret = err; goto out; } } - ray_t* result = call_lambda(head, args, argc); + bool query = ray_active_query_table() != NULL; + uint64_t row_args = 0; + /* The arguments' evaluation says whether they are row data; only + * an interpreted helper's result needs the syntactic analysis. */ + if (query) for (int64_t i = 0; i < argc; i++) { + bool r = arg_rows[i] >= 0 ? arg_rows[i] > 0 : ray_query_expr_reads_rows(elems[i + 1]); + if (r) row_args |= UINT64_C(1) << i; + } + bool named = elems[0]->type == -RAY_SYM && !(elems[0]->attrs & ATTR_QUOTED); + int8_t result_rows = -1; + ray_t* result = call_lambda_impl(head, args, argc, query, row_args, named, &result_rows); + rows = result_rows; for (int64_t i = 0; i < argc; i++) ray_release(args[i]); ray_release(head); if (RAY_IS_ERR(result)) @@ -4155,6 +5057,7 @@ ray_t* ray_eval(ray_t* obj) { } } } + g_eval_rows = rows; __VM->eval_depth--; /* End-of-top-level-expression cleanup hook. Every path that * entered ray_eval — REPL, IPC, ray_eval_str, file mode — exits diff --git a/src/lang/eval.h b/src/lang/eval.h index 0cfab1d0d..655063ee5 100644 --- a/src/lang/eval.h +++ b/src/lang/eval.h @@ -96,6 +96,28 @@ enum { * push handler as a fallback value */ OP_FORCE, /* materialize TOS if it is a lazy handle (so a * let-bound local holds a concrete, reusable value) */ + OP_BINDCAPS, /* bind the closure's captures to local slots: + * cpool[operand] is an I64 vector of (name, slot) + * pairs; each name is looked up in the closure dict + * and its value stored into the slot (a name the dict + * lacks leaves the slot empty). The prologue of every + * compiled closure */ + OP_LOADSELF, /* push the running lambda (bare `self` as a value) */ + OP_MKCLOSURE, /* pop slots (I64), names (SYM), template (LAMBDA): + * push a closure sharing the template's bytecode, + * capturing the current frame's named slots */ + OP_LOADENVG, /* push local slot (1 byte) or, when the slot is still + * empty (a `let` that has not run), the global named + * by cpool[2-byte index], as the tree walker would */ + OP_SCOPE_EVAL, /* OP_SCOPE_BEGIN for the windows compiled code opens + * around text it hands to the tree walker (eval, a + * dynamic special form, a fn literal): the frame + * binds the locals for that text only, not for what + * it calls, and ends its scope */ + OP_CALL1R, /* OP_CALL1 / OP_CALL2 / OP_CALLN, each with an argc */ + OP_CALL2R, /* operand, for a builtin a closure body resolves when */ + OP_CALLNR, /* it runs: the fast call while the name holds a builtin + * of that kind, OP_CALLF's general call otherwise */ OP__COUNT }; @@ -112,7 +134,11 @@ enum { * data[5] = ray_t* nfo (source location info, NULL if absent) * data[6] = ray_t* dbg (debug metadata, NULL if absent) * data[7] = ray_t* closure (captured lexical locals, NULL if empty) + * data[8] = ray_t* caprows (RAY_U8 row flag per capture, or NULL) + * data[9] = uint32_t capq (serial of the query frame the closure was + * made under, 0 if none; never serialized) */ +#define LAMBDA_SLOTS 10 #define RAY_FN_COMPILED 0x40 /* lambda has been compiled to bytecode */ @@ -124,6 +150,8 @@ enum { #define LAMBDA_NFO(lam) (((ray_t**)ray_data(lam))[5]) #define LAMBDA_DBG(lam) (((ray_t**)ray_data(lam))[6]) #define LAMBDA_CLOSURE(lam) (((ray_t**)ray_data(lam))[7]) +#define LAMBDA_CAPROWS(lam) (((ray_t**)ray_data(lam))[8]) +#define LAMBDA_CAPQ(lam) (*((uint32_t*)&((ray_t**)ray_data(lam))[9])) #define LAMBDA_IS_COMPILED(lam) ((lam)->attrs & RAY_FN_COMPILED) @@ -163,6 +191,7 @@ typedef struct { ray_t *fn; /* current lambda */ int32_t tp; /* trap stack pointer */ ray_t *ps[VM_STACK_SIZE]; /* program stack */ + uint8_t rows[VM_STACK_SIZE]; /* ps[i] is derived from query rows */ vm_ctx_t rs[VM_STACK_SIZE]; /* return stack */ vm_trap_t ts[VM_TRAP_SIZE]; /* trap frames */ } ray_exec_t; @@ -181,6 +210,23 @@ ray_t* ray_eval_str(const char* source); /* Compile a lambda's body to bytecode. Called lazily on first invocation. */ void ray_compile(ray_t* lambda); +/* ray_compile for a lambda with nothing captured, also handing back the + * bindings its code depends on (see compile.c). */ +bool ray_compile_definition(ray_t* lambda, ray_t** deps); +/* The most bytes a literal's text may hold for the template table to keep + * it (eval.c), and where the compiler's weight count may stop. */ +#define RAY_CLOSURE_TMPL_MAX_BYTES ((int64_t)64 * 1024) +/* The capture names a closure's body can reach (its dict keys the body + * mentions; all of them under eval/resolve), as a SYM vector or NULL. */ +ray_t* ray_closure_capture_names(ray_t* lambda); +ray_t* ray_closure_mentioned_syms(ray_t* body, bool* dynamic, int64_t* weight); +ray_t* ray_closure_names_from(ray_t* closure, ray_t* mentioned, bool dynamic); +/* The closure dict shape the compiled capture binding assumes: NULL, or SYM + * keys with a LIST of values of the same length. */ +bool ray_closure_shape_ok(ray_t* closure); +/* Compile `lambda` with `capnames` bound as locals ahead of the body; false + * when the body cannot be compiled. */ +bool ray_compile_with_captures(ray_t* lambda, ray_t* capnames, bool closure_body); /* Reset compiler cached state (call from ray_lang_destroy). */ void ray_compile_reset(void); @@ -277,6 +323,13 @@ ray_t* ray_apply_fn(ray_t** args, int64_t n); /* Collection */ ray_t* ray_distinct_fn(ray_t* x); ray_t* ray_in_fn(ray_t* val, ray_t* vec); +ray_t* ray_in_eval_fn(ray_t* val, ray_t* vec); +/* Query text concat; str_out: a STR atom operand is a STR column's cell. + * rows_mask bit 0 / bit 1: a / b is a column's cell, so a null one is the + * empty text the vector kernel sees, not the null literal that nulls the + * result. */ +ray_t* ray_concat_text_fn(ray_t* a, ray_t* b, bool str_out, uint8_t rows_mask); +ray_t* ray_not_in_fn(ray_t* val, ray_t* vec); ray_t* ray_except_fn(ray_t* vec1, ray_t* vec2); ray_t* ray_union_fn(ray_t* vec1, ray_t* vec2); ray_t* ray_sect_fn(ray_t* vec1, ray_t* vec2); @@ -372,4 +425,7 @@ ray_t* ray_raise_fn(ray_t* val); ray_t* ray_try_fn(ray_t* expr, ray_t* handler_expr); +bool ray_eval_query_helper_active(void); +bool ray_eval_query_helper_literals(void); + #endif /* RAY_EVAL_H */ diff --git a/src/lang/internal.h b/src/lang/internal.h index 405060def..f85fc1085 100644 --- a/src/lang/internal.h +++ b/src/lang/internal.h @@ -96,6 +96,22 @@ static inline int is_numeric(ray_t* x) { x->type == -RAY_U8 || x->type == -RAY_BOOL; } +/* The class of a null of type tag `t` (either sign): two nulls are equal + * when their classes are, as two values are — the same type, or any two + * numerics (is_numeric: 1 equals 1i, so 0Nl equals 0Ni). A symbol null, + * the empty string, a temporal null and the untyped null each stand + * apart. atom_eq and the membership hash set both ask this. */ +static inline int8_t ray_null_class(int8_t t) { + if (t < 0) t = (int8_t)-t; + switch (t) { + case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: + case RAY_F64: case RAY_F32: + return RAY_I64; + default: + return t; + } +} + /* Check if an atom is a temporal type */ static inline int is_temporal(ray_t* x) { return x->type == -RAY_DATE || x->type == -RAY_TIME || x->type == -RAY_TIMESTAMP; diff --git a/src/mem/arena.c b/src/mem/arena.c index cc2e6e0b1..7fe63346d 100644 --- a/src/mem/arena.c +++ b/src/mem/arena.c @@ -40,9 +40,25 @@ typedef struct ray_arena_chunk { /* Arena header */ struct ray_arena { ray_arena_chunk_t* chunks; /* linked list of all chunks (head = current) */ - size_t chunk_size; /* default chunk capacity */ + size_t chunk_size; /* capacity of the next chunk */ }; +/* Chunks double from the arena's initial size up to ARENA_CHUNK_MAX, so a + * large arena (the string atoms of a domain with millions of entries) is a + * few big chunks. Chunks come from ray_sys_alloc, which spills blocks of + * 1 MiB or more to a file past the anonymous watermark; a stream of small + * chunks would stay in RAM however far past it the arena grew (#712). */ +#define ARENA_CHUNK_MAX ((size_t)16 << 20) + +/* Capacity of the next chunk for a request of `need` bytes. */ +static size_t arena_next_cap(ray_arena_t* arena, size_t need) { + size_t cap = arena->chunk_size; + if (arena->chunk_size < ARENA_CHUNK_MAX) + arena->chunk_size = arena->chunk_size * 2 < ARENA_CHUNK_MAX + ? arena->chunk_size * 2 : ARENA_CHUNK_MAX; + return need > cap ? ARENA_ALIGN_UP(need) : cap; +} + /* Chunk data starts at aligned offset after the header */ static inline char* chunk_data(ray_arena_chunk_t* c) { size_t hdr = ARENA_ALIGN_UP(sizeof(ray_arena_chunk_t)); @@ -87,10 +103,7 @@ ray_t* ray_arena_alloc(ray_arena_t* arena, size_t nbytes) { ray_arena_chunk_t* c = arena->chunks; if (c->used + block_size > c->cap) { - size_t new_cap = arena->chunk_size; - if (block_size > new_cap) new_cap = ARENA_ALIGN_UP(block_size); - - ray_arena_chunk_t* nc = arena_new_chunk(new_cap); + ray_arena_chunk_t* nc = arena_new_chunk(arena_next_cap(arena, block_size)); if (!nc) return NULL; nc->next = arena->chunks; @@ -121,9 +134,7 @@ void* ray_arena_alloc_raw(ray_arena_t* arena, size_t nbytes) { size_t block_size = ARENA_ALIGN_UP(nbytes); ray_arena_chunk_t* c = arena->chunks; if (c->used + block_size > c->cap) { - size_t new_cap = arena->chunk_size; - if (block_size > new_cap) new_cap = ARENA_ALIGN_UP(block_size); - ray_arena_chunk_t* nc = arena_new_chunk(new_cap); + ray_arena_chunk_t* nc = arena_new_chunk(arena_next_cap(arena, block_size)); if (!nc) return NULL; nc->next = arena->chunks; arena->chunks = nc; @@ -182,9 +193,7 @@ bool ray_arena_reserve(ray_arena_t* arena, size_t bytes) { if (bytes == 0) return true; ray_arena_chunk_t* c = arena->chunks; if (c && (c->cap - c->used) >= bytes) return true; - size_t new_cap = arena->chunk_size; - if (bytes > new_cap) new_cap = ARENA_ALIGN_UP(bytes); - ray_arena_chunk_t* nc = arena_new_chunk(new_cap); + ray_arena_chunk_t* nc = arena_new_chunk(arena_next_cap(arena, bytes)); if (!nc) return false; nc->next = arena->chunks; arena->chunks = nc; diff --git a/src/mem/heap.c b/src/mem/heap.c index 4d6634923..0b20ed13d 100644 --- a/src/mem/heap.c +++ b/src/mem/heap.c @@ -32,11 +32,14 @@ #include "sys.h" #include "core/platform.h" #include "core/timer.h" /* ray_time_now_ms — idle-decay clock */ +#include "core/pool.h" /* ray_pool_each_worker_heap — maintenance targets */ +#include "core/runtime.h" /* ray_sys_mem_flush — a cgroup's statistics flushed */ #include "table/sym.h" #include "table/domain.h" #include "lang/eval.h" #include "store/hnsw.h" #include "store/csr.h" +#include "store/part.h" #include "ops/idxop.h" #include #include /* getenv */ @@ -335,18 +338,44 @@ void ray_mem_trace_end(ray_mem_trace_t* out) { atomic_store_explicit(&g_mem_trace_active, 0, memory_order_release); } -/* Anonymous (RAM-resident) pool + direct bytes we have committed. File-backed - * spill mappings are NOT counted (they can be evicted to disk, never OOM-kill). - * 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. */ +/* Anonymous (RAM-resident) pool, direct and sys bytes we have committed. + * File-backed spill mappings are NOT counted (they can be evicted to disk, + * never OOM-kill). When a new anon mapping would push this past the + * watermark, it is routed to a spill file instead — or, when no spill file can + * be made, to RAM anyway: this never rejects work, it just picks disk over + * RAM. A spill mapping is MAP_SHARED: after fork() parent and child share + * it instead of each having a copy, so a child that keeps running rayforce + * code must not write blocks the parent spilled. */ static _Atomic(int64_t) g_anon_committed = 0; -static _Atomic(int64_t) g_anon_watermark = 0; /* 0 = default to ray_sys_ram_limit() */ +static _Atomic(int64_t) g_anon_watermark = 0; /* 0 = the default (heap_anon_watermark) */ static _Atomic(int64_t) g_anon_peak = 0; /* high-water of g_anon_committed */ +/* What has been mapped, for ray_heap_relieve to learn what a statement did: + * the number of anonymous mappings and the bytes of the direct and sys blocks + * among them — sys blocks too small to spill (RAY_SYS_SPILL_MIN) left out — + * and the number of mappings that went past RAM — a pool, direct or sys + * block mapped over a spill file (the watermark's call, or a refused + * anonymous mapping), or taken from RAM past the watermark because no spill + * file could be made. */ +static _Atomic(int64_t) g_anon_maps = 0; +static _Atomic(int64_t) g_anon_large = 0; +static _Atomic(int64_t) g_anon_spills = 0; +static _Atomic(int64_t) g_anon_stmt_peak = 0; /* high-water since the last boundary */ +static _Atomic(int64_t) g_spill_pools = 0; /* spill pools mapped, all heaps */ + +static void heap_anon_spilled(void) { + atomic_fetch_add_explicit(&g_anon_spills, 1, memory_order_relaxed); +} + /* Commit `bytes` of anonymous (RAM-resident) footprint and advance the peak - * high-water. Called only from the two anon-commit sites; file-backed spill - * mappings never call this (they must not count toward the RAM watermark). */ -static void heap_anon_commit(int64_t bytes) { + * high-water. Called from the anon-commit sites (pools, direct blocks, sys + * blocks); file-backed spill mappings never call this (they must not count + * toward the RAM watermark). `mapped`: a mapping ray_heap_relieve counts — + * a pool, a direct block, a sys block that could spill; `large`: one of the + * last two. */ +static void heap_anon_commit(int64_t bytes, bool mapped, bool large) { + if (mapped) atomic_fetch_add_explicit(&g_anon_maps, 1, memory_order_relaxed); + if (large) atomic_fetch_add_explicit(&g_anon_large, bytes, memory_order_relaxed); int64_t nv = atomic_fetch_add_explicit(&g_anon_committed, bytes, memory_order_relaxed) + bytes; int64_t pk = atomic_load_explicit(&g_anon_peak, memory_order_relaxed); @@ -356,15 +385,30 @@ static void heap_anon_commit(int64_t bytes) { memory_order_relaxed)) { /* pk reloaded with the current value on failure; retry. */ } + pk = atomic_load_explicit(&g_anon_stmt_peak, memory_order_relaxed); + while (nv > pk && + !atomic_compare_exchange_weak_explicit(&g_anon_stmt_peak, &pk, nv, + memory_order_relaxed, + memory_order_relaxed)) {} } /* Threshold above which anon allocations spill to disk. Default keeps our - * 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. */ + * anon footprint below the RAM the process may actually use — physical RAM, + * or the container's cgroup limit when that is smaller (#688) — by a quarter + * of it, at least 3 GiB and at most half. That room is for the page cache: + * the mapped inputs, the dirty pages of the files being written and those of + * the spill files themselves. Without it spilling would start only once + * nothing was left, and under a cgroup the page cache is charged to the same + * limit (#712). */ 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_ram_limit(); + if (wm > 0) return wm; + int64_t lim = ray_sys_ram_limit(); + if (lim <= 0) return lim; + int64_t room = lim / 4; + if (room < (INT64_C(3) << 30)) room = INT64_C(3) << 30; + if (room > lim / 2) room = lim / 2; + return lim - room; } /* True if committing `bytes` more anonymous RAM would cross the watermark. */ static bool heap_anon_would_exceed(size_t bytes) { @@ -374,6 +418,14 @@ static bool heap_anon_would_exceed(size_t bytes) { return cur + (int64_t)bytes > wm; } +/* A boundary far from the watermark visits the heaps for the spill pools + * alone (ray_heap_relieve) — to park the empty ones, discard their pages and + * age them — so at most this often: a stream of small statements (a + * server's) would otherwise walk every worker heap each time, 13-14 µs a + * statement at 16 workers. A new watermark visits at the next boundary. */ +#define RAY_FAR_VISIT_MS 100 +static _Atomic(int64_t) g_far_visit_ms = INT64_MIN / 2; + int64_t ray_heap_anon_committed(void) { return atomic_load_explicit(&g_anon_committed, memory_order_relaxed); } @@ -383,9 +435,15 @@ int64_t ray_heap_anon_peak(void) { int64_t ray_heap_anon_watermark(void) { return heap_anon_watermark(); } +int64_t ray_heap_mem_budget(void) { + int64_t wm = atomic_load_explicit(&g_anon_watermark, memory_order_relaxed); + return wm > 0 ? wm : ray_sys_ram_limit(); +} +/* A new budget: the next boundary visits the heaps. */ void ray_heap_set_anon_watermark(int64_t bytes) { atomic_store_explicit(&g_anon_watermark, bytes < 0 ? 0 : bytes, memory_order_relaxed); + atomic_store_explicit(&g_far_visit_ms, INT64_MIN / 2, memory_order_relaxed); } ray_heap_t* ray_heap_registry[RAY_HEAP_REGISTRY_SIZE]; @@ -472,6 +530,11 @@ uint8_t ray_order_for_size(size_t data_size) { * -------------------------------------------------------------------------- */ static bool heap_add_pool(ray_heap_t* h, uint8_t order); +static bool heap_unpark(ray_heap_t* h, bool spill); +static void heap_unpark_all(ray_heap_t* h); +static bool heap_make_room(size_t bytes); +static int64_t heap_decay_threshold_ms(void); +static void heap_abandon_spill(ray_heap_t* h); /* -------------------------------------------------------------------------- * Freelist operations (circular sentinel via fl_prev/fl_next) @@ -589,13 +652,16 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { * would push our RAM footprint past the watermark — a file-backed pool * can't be OOM-killed. Otherwise take the fast anon path (and still fall * back to a spill file below if the kernel refuses the mapping). */ - if (!heap_anon_would_exceed(pool_size)) + bool over = heap_anon_would_exceed(pool_size); + if (!over) mem = ray_vm_alloc_aligned(pool_size, pool_size); #if !RAY_HEAP_FILE_SPILL + /* No spill files here: past the watermark the pool comes from RAM. */ + if (!mem && over) mem = ray_vm_alloc_aligned(pool_size, pool_size); if (!mem) return false; #else - if (!mem) { + if (!mem) do { /* Anonymous mmap refused — usually means RAM+swap can't satisfy * pool_size right now. Fall back to file-backed mmap: create a * tempfile in h->swap_path, reserve `pool_size` bytes of disk @@ -608,15 +674,19 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { size_t plen = strlen(h->swap_path); size_t need = plen + 64; /* room for "rayheap___.dat" */ swap_path = (char*)ray_sys_alloc(need); - if (!swap_path) return false; + if (!swap_path) break; snprintf(swap_path, need, "%srayheap_%d_%u_%llu.dat", h->swap_path, (int)getpid(), (unsigned)h->id, (unsigned long long)cnt); - swap_fd = open(swap_path, O_RDWR | O_CREAT | O_EXCL, 0600); + /* Close-on-exec, as every spill file: a child of .sys.exec would + * otherwise hold the unlinked file — its pages, dirty ones written + * back — for as long as it runs, past the pool's unmapping. */ + swap_fd = open(swap_path, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0600); if (swap_fd < 0) { ray_sys_free(swap_path); - return false; + swap_path = NULL; + break; } /* Reserve EXACTLY pool_size bytes of disk blocks AND grow the @@ -630,7 +700,9 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { close(swap_fd); unlink(swap_path); ray_sys_free(swap_path); - return false; + swap_fd = -1; + swap_path = NULL; + break; } /* Reserve 2*pool_size of address space anonymously to guarantee @@ -646,7 +718,9 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { close(swap_fd); unlink(swap_path); ray_sys_free(swap_path); - return false; + swap_fd = -1; + swap_path = NULL; + break; } uintptr_t addr = (uintptr_t)anon; @@ -669,7 +743,9 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { close(swap_fd); unlink(swap_path); ray_sys_free(swap_path); - return false; + swap_fd = -1; + swap_path = NULL; + break; } /* Count the swap-backed pool as committed working set — it is a RAM @@ -688,7 +764,11 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { unlink(swap_path); ray_sys_free(swap_path); swap_path = NULL; - } + } while (0); + /* No spill file (no writable spill directory, disk full): RAM past the + * watermark rather than failing the allocation. */ + if (!mem && over) mem = ray_vm_alloc_aligned(pool_size, pool_size); + if (!mem) return false; #endif /* RAY_HEAP_FILE_SPILL */ /* Enable transparent huge pages on anon pools (Linux). Self-aligned @@ -725,16 +805,24 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { } /* --- Track pool --- */ - h->pools[h->pool_count].base = mem; - h->pools[h->pool_count].pool_order = pool_order; - h->pools[h->pool_count].backed = (swap_fd >= 0) ? 1 : 0; - h->pools[h->pool_count].hugepage = pool_hugepage; - h->pools[h->pool_count].swap_fd = swap_fd; - h->pools[h->pool_count].swap_path = swap_path; /* NULL when not backed */ + h->pools[h->pool_count] = (ray_pool_entry_t){ + .base = mem, + .pool_order = pool_order, + .backed = (swap_fd >= 0) ? 1 : 0, + .hugepage = pool_hugepage, + .swap_fd = swap_fd, + .swap_path = swap_path, /* NULL when not backed */ + }; h->pool_count++; if (swap_fd < 0) /* anonymous pool: counts toward the RAM watermark */ - heap_anon_commit((int64_t)pool_size); + heap_anon_commit((int64_t)pool_size, true, false); + else + atomic_fetch_add_explicit(&g_spill_pools, 1, memory_order_relaxed); + if (over || swap_fd >= 0) { + heap_anon_spilled(); + h->spilled = 1; + } return true; } @@ -847,6 +935,7 @@ static void ray_release_owned_refs(ray_t* v) { if (LAMBDA_NFO(v)) ray_release(LAMBDA_NFO(v)); if (LAMBDA_DBG(v)) ray_release(LAMBDA_DBG(v)); if (LAMBDA_CLOSURE(v)) ray_release(LAMBDA_CLOSURE(v)); + if (LAMBDA_CAPROWS(v)) ray_release(LAMBDA_CAPROWS(v)); return; } if (v->type == RAY_LAZY) { @@ -980,6 +1069,7 @@ bool ray_retain_owned_refs(ray_t* v) { if (LAMBDA_NFO(v)) ray_retain(LAMBDA_NFO(v)); if (LAMBDA_DBG(v)) ray_retain(LAMBDA_DBG(v)); if (LAMBDA_CLOSURE(v)) ray_retain(LAMBDA_CLOSURE(v)); + if (LAMBDA_CAPROWS(v)) ray_retain(LAMBDA_CAPROWS(v)); return true; } /* Lazy handles own their graph uniquely — no retain on copy */ @@ -1097,6 +1187,8 @@ static void ray_detach_owned_refs(ray_t* v) { LAMBDA_NFO(v) = NULL; LAMBDA_DBG(v) = NULL; LAMBDA_CLOSURE(v) = NULL; + LAMBDA_CAPROWS(v) = NULL; + LAMBDA_CAPQ(v) = 0; return; } if (v->type == RAY_LAZY) { @@ -1220,7 +1312,7 @@ static void* heap_direct_map_file(ray_heap_t* h, size_t map_size, snprintf(path, need, "%sraydirect_%d_%u_%llu.dat", h->swap_path, (int)getpid(), (unsigned)h->id, (unsigned long long)cnt); - int fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0600); + int fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0600); if (fd < 0) { ray_sys_free(path); return NULL; } /* Reserve real disk blocks up front so later stores can't SIGBUS on a @@ -1294,9 +1386,9 @@ static inline void direct_cache_unlock(void) { } static size_t direct_cache_budget(void) { - int64_t wm = heap_anon_watermark(); + int64_t wm = ray_heap_mem_budget(); size_t b = (wm > 0) ? (size_t)wm / 16 : 0; - /* 1/16 of the watermark is the sole bound (1GB on a 16GB box, ~8GB + /* 1/16 of the memory budget is the sole bound (1GB on a 16GB box, ~8GB * on 128GB). Earlier absolute caps (512MB, then 4GB) each turned * out to exclude exactly the blocks whose kernel re-zeroing cost the * most at the next data scale: a 100M-row group query cycles several @@ -1390,6 +1482,14 @@ void ray_heap_direct_cache_drain(void) { direct_cache_drain(); } +/* Bytes a drain would hand back now. */ +static int64_t direct_cache_bytes(void) { + direct_cache_lock(); + size_t b = g_direct_cache_bytes; + direct_cache_unlock(); + return (int64_t)b; +} + /* Direct large allocation: mmap the exact page-rounded size instead of a * power-of-2 oversized buddy pool. Returns a marked ray_t or NULL on failure. */ static ray_t* heap_alloc_direct(ray_heap_t* h, size_t data_size) { @@ -1415,21 +1515,22 @@ static ray_t* heap_alloc_direct(ray_heap_t* h, size_t data_size) { * SUCCEEDS, then kills us at fault time — so a fallback-on-failure alone * would not catch it.) Otherwise use anonymous RAM, and fall back to a * spill file only if the kernel refuses the mapping. - * Under pressure, drain the reuse cache before deciding — its resident - * pages are the first thing to give back. */ - bool force_file = heap_anon_would_exceed(map_size); - if (force_file) { - direct_cache_drain(); - force_file = heap_anon_would_exceed(map_size); - } + * Under pressure, give back what is free before deciding + * (heap_make_room). */ + bool force_file = heap_anon_would_exceed(map_size) && heap_make_room(map_size); if (!force_file) base = ray_vm_alloc(map_size); /* anon RW, page-aligned, counted */ if (!base) { base = heap_direct_map_file(h, map_size, &swap_fd, &swap_path); + /* No spill file (no writable spill directory, disk full): RAM + * past the watermark rather than failing the allocation. */ + if (!base && force_file) base = ray_vm_alloc(map_size); if (!base) return NULL; } if (swap_fd < 0) /* anonymous: counts toward the RAM watermark */ - heap_anon_commit((int64_t)map_size); + heap_anon_commit((int64_t)map_size, true, true); + if (force_file || swap_fd >= 0) + heap_anon_spilled(); } ray_direct_hdr_t* hdr = (ray_direct_hdr_t*)base; @@ -1523,6 +1624,11 @@ ray_t* ray_alloc(size_t data_size) { * the invariant — no pool is ever added without a drain first. */ heap_drain_foreign(h); candidates = h->avail & (UINT64_MAX << order); + /* Then a pool the heap parked (heap_park_empty_pools), an + * anonymous one first. */ + if (candidates == 0 && h->parked + && (heap_unpark(h, false) || heap_unpark(h, true))) + candidates = h->avail & (UINT64_MAX << order); if (candidates == 0) { if (!heap_add_pool(h, order)) return NULL; candidates = h->avail & (UINT64_MAX << order); @@ -1892,6 +1998,34 @@ void ray_free_raw(void* p) { ray_free((ray_t*)((char*)p - 32)); /* 32 = ray_t header before the data */ } +bool ray_raw_discard(void* p, size_t from, size_t upto) { +#if RAY_HEAP_FILE_SPILL && defined(MADV_REMOVE) + if (!p || upto <= from) return false; + ray_t* v = (ray_t*)((char*)p - 32); + /* An anonymous block is below the watermark, and the direct-block + * cache keeps it resident for its next use: left alone. */ + if (!ray_is_direct(v) || !ray_direct_file_backed(v)) return false; + size_t room = ray_block_data_bytes(v); + if (upto > room) upto = room; + long ps = sysconf(_SC_PAGESIZE); + uintptr_t pg = ps > 0 ? (uintptr_t)ps : 4096; + /* whole pages only, and never the first: it holds the headers */ + uintptr_t first = ((uintptr_t)p + pg - 1) & ~(pg - 1); + uintptr_t lo = ((uintptr_t)p + from) & ~(pg - 1); + uintptr_t hi = ((uintptr_t)p + upto) & ~(pg - 1); + if (lo < first) lo = first; + if (hi <= lo) return false; + /* punched out of the spill file: a dirty page is dropped, not written */ + return madvise((void*)lo, hi - lo, MADV_REMOVE) == 0; +#else + /* No way to punch a mapped range here (macOS has no MADV_REMOVE, and + * F_PUNCHHOLE does not say what it does to pages mapped shared): the + * pages stay until the block is freed, as before. */ + (void)p; (void)from; (void)upto; + return false; +#endif +} + void* ray_realloc_raw(void* p, size_t n) { if (!p) return ray_alloc_raw(n); ray_t* v = (ray_t*)((char*)p - 32); @@ -2071,6 +2205,99 @@ void ray_mem_stats(ray_mem_stats_t* out) { * popped once per thread lifetime, never on an allocation path. */ static ray_heap_t* g_heap_idle = NULL; +/* The spill directory, as ray_heap_init resolves it (see there). */ +static void heap_swap_dir(char* out, size_t cap) { + const char* env = getenv("RAY_HEAP_SWAP"); + if (!(env && *env)) env = getenv("TMPDIR"); + const char* sp = (env && *env && strlen(env) < cap - 16) ? env : "/tmp"; + size_t sp_len = strlen(sp); + memcpy(out, sp, sp_len); + out[sp_len] = '\0'; + if (sp_len > 0 && out[sp_len - 1] != '/' && sp_len < cap - 1) { + out[sp_len] = '/'; + out[sp_len + 1] = '\0'; + } +} + +/* -------------------------------------------------------------------------- + * Off-heap system blocks + * + * ray_sys_alloc serves storage that lives outside the per-thread heaps: the + * string arenas of the symbol table and the column domains, their hash + * tables, index-build scratch. It counts toward the anonymous watermark like + * pools and direct blocks, so -m (or the default) bounds it too, and a block + * of RAY_SYS_SPILL_MIN bytes or more that would cross the watermark is mapped + * over a spill file instead (#712), or taken from RAM when no spill file can be + * made. The file is unlinked and its descriptor closed at once — the mapping + * keeps it — so spilled blocks hold no fds. Either way the block reads zero + * (fresh anonymous memory, or a new file created O_EXCL and preallocated), + * which ray_sys_alloc promises its callers (mem/sys.h): it never comes from + * the direct-block cache. + * -------------------------------------------------------------------------- */ +#define RAY_SYS_SPILL_MIN ((size_t)1 << 20) + +#if RAY_HEAP_FILE_SPILL +static void* heap_sys_map_file(size_t size) { + static _Atomic uint64_t sys_swap_counter = 0; + char path[320]; + heap_swap_dir(path, 256); + size_t plen = strlen(path); + snprintf(path + plen, sizeof(path) - plen, "raysys_%d_%llu.dat", (int)getpid(), + (unsigned long long)atomic_fetch_add_explicit(&sys_swap_counter, 1, + memory_order_relaxed)); + int fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0600); + if (fd < 0) return NULL; + void* p = NULL; + if (heap_preallocate(fd, 0, (off_t)size) == 0) { + p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) p = NULL; + } + unlink(path); + close(fd); + if (p) ray_sys_track_add((int64_t)size); /* committed working set, as a spilled pool */ + return p; +} +#endif + +void* ray_heap_sys_map(size_t size, bool* spilled) { + *spilled = false; + void* p = NULL; + bool big = size >= RAY_SYS_SPILL_MIN; /* could spill, so ray_heap_relieve counts it */ +#if RAY_HEAP_FILE_SPILL + bool to_file = big && heap_anon_would_exceed(size) && heap_make_room(size); + if (!to_file) p = ray_vm_alloc(size); + if (!p && big) { + p = heap_sys_map_file(size); + if (p) { *spilled = true; heap_anon_spilled(); return p; } + } + /* No spill file (no writable spill directory, disk full): RAM rather + * than failing — callers of ray_sys_alloc grow core tables with it. */ + if (!p && to_file) { + p = ray_vm_alloc(size); + if (p) heap_anon_spilled(); + } +#else + p = ray_vm_alloc(size); +#endif + if (p) heap_anon_commit((int64_t)size, big, big); + return p; +} + +void ray_heap_sys_unmap(void* p, size_t size, bool spilled) { + if (!p) return; +#if RAY_HEAP_FILE_SPILL + if (spilled) { + munmap(p, size); + ray_sys_track_sub((int64_t)size); + return; + } +#else + (void)spilled; +#endif + atomic_fetch_sub_explicit(&g_anon_committed, (int64_t)size, memory_order_relaxed); + ray_vm_free(p, size); +} + void ray_heap_init(void) { if (ray_tl_heap) return; @@ -2150,16 +2377,7 @@ void ray_heap_init(void) { * always ensured so heap_add_pool can concatenate `` * unconditionally. An empty / over-long value is rejected in favour of * the next option. */ - const char* env = getenv("RAY_HEAP_SWAP"); - if (!(env && *env)) env = getenv("TMPDIR"); - const char* sp = (env && *env && strlen(env) < sizeof(h->swap_path) - 16) ? env : "/tmp"; - size_t sp_len = strlen(sp); - memcpy(h->swap_path, sp, sp_len); - h->swap_path[sp_len] = '\0'; - if (sp_len > 0 && h->swap_path[sp_len - 1] != '/' && sp_len < sizeof(h->swap_path) - 1) { - h->swap_path[sp_len] = '/'; - h->swap_path[sp_len + 1] = '\0'; - } + heap_swap_dir(h->swap_path, sizeof(h->swap_path)); ray_tl_heap = h; } @@ -2178,11 +2396,13 @@ void ray_heap_abandon(void) { * it, or the next ray_eval_str on the adopting thread would release a * trace this thread already handed on. */ ray_clear_error_trace(); + ray_parted_cache_clear(); /* Take back whatever was freed to us while we ran, so the heap is * handed on with its memory on its freelists rather than on a list the * adopter has to notice. */ heap_drain_foreign(h); + heap_abandon_spill(h); ray_registry_lock(); h->idle_next = g_heap_idle; @@ -2207,6 +2427,7 @@ void ray_heap_destroy(void) { * memory is still mapped; once the for-loop below munmap's the * pools, dereferencing g_error_trace becomes UB. */ ray_clear_error_trace(); + ray_parted_cache_clear(); /* FILE sym-domain string atoms used to live on the per-thread buddy * heap, requiring a drop here so the process-global cache never handed @@ -2244,6 +2465,7 @@ void ray_heap_destroy(void) { (uintptr_t)h->pools[i].base + BSIZEOF(h->pools[i].pool_order)); ray_vm_free(hdr->vm_base, BSIZEOF(h->pools[i].pool_order)); if (h->pools[i].backed) { + atomic_fetch_sub_explicit(&g_spill_pools, 1, memory_order_relaxed); if (h->pools[i].swap_fd >= 0) close(h->pools[i].swap_fd); if (h->pools[i].swap_path) { unlink(h->pools[i].swap_path); @@ -2307,7 +2529,264 @@ static void dfd_validate_freelists(void) { * starts here. */ #define RAY_RELEASE_MIN_ORDER 13 +/* Which pools a reclaim may unmap: oversized ones (gc pass 4), spill ones + * (the idle decay, an abandoned heap, a relief that acts — releasing a + * spill block's pages frees nothing, see heap_release_free_pages), or + * anonymous ones (heap_make_room, ray_heap_relieve). */ +#define RAY_RECLAIM_OVERSIZED 1u +#define RAY_RECLAIM_SPILL 2u +#define RAY_RECLAIM_ANON 4u + +static bool heap_reclaim_admits(const ray_pool_entry_t* pe, unsigned mode) { + return ((mode & RAY_RECLAIM_OVERSIZED) && pe->pool_order > RAY_HEAP_POOL_ORDER) + || ((mode & RAY_RECLAIM_SPILL) && pe->backed) + || ((mode & RAY_RECLAIM_ANON) && !pe->backed); +} + +/* The pools of h that `mode` admits and that may be entirely free, into + * out[]; returns how many. h's foreign list must have been drained and its + * slab cache flushed: every free block is then coalesced as far as it goes, + * so an empty pool holds exactly the cascade heap_add_pool cut it into — one + * free block of each order k from RAY_ORDER_MIN to pool_order-1, at offset + * 2^k. No free block at order RAY_HEAP_POOL_ORDER-1 or above therefore rules + * out every pool at once (a clear avail bit is exact; only a set one can be + * stale), and otherwise one header per cascade offset settles a pool — the + * offset is always the start of a block, never inside one, since only a + * block starting at the pool header could span it. A filter, not the test: + * a block another thread is freeing into h right now reads rc 0 too, before + * it is on any list of h's. heap_find_empty_pools confirms. A parked + * pool is not a candidate: it is empty by construction, and its blocks are + * on no list. */ +static uint32_t heap_empty_pool_candidates(ray_heap_t* h, unsigned mode, + uint32_t* out) { + if (h->pool_count <= 1) return 0; + if (!(h->avail & (UINT64_MAX << (RAY_HEAP_POOL_ORDER - 1)))) return 0; + uint32_t n = 0; + for (uint32_t p = 0; p < h->pool_count; p++) { + if (h->pools[p].parked || !heap_reclaim_admits(&h->pools[p], mode)) continue; + uintptr_t pb = (uintptr_t)h->pools[p].base; + int k = h->pools[p].pool_order - 1; + for (; k >= RAY_ORDER_MIN; k--) { + ray_t* b = (ray_t*)(pb + BSIZEOF(k)); + if (ray_atomic_load(&b->rc) != 0 || b->order != k) break; + } + if (k < RAY_ORDER_MIN) out[n++] = p; + } + return n; +} + +/* Set empty[p] for each unparked pool p of h that `mode` admits and whose + * bytes are all free; returns how many. empty[] has h->pool_count entries, + * zeroed by the caller. The caller vouches that h is quiescent — its own + * heap, or a parked worker's with ray_parallel_flag clear — and has drained + * h's foreign list and flushed its slab cache; a block in either is not on a + * freelist, so its pool is not empty as far as this goes. + * + * Emptiness is "every byte of the pool but its header is on h's freelists". + * A block of h's that is live, or queued anywhere, is by construction not + * there, so it shows up as a shortfall — no cross-heap scan is needed, since + * a free always routes a block to its owner. One walk of h's freelists + * sums the free bytes of every candidate at once: walking them once per + * pool made a boundary O(pools x free blocks), a quarter of a second on a + * fragmented heap of a few hundred MB. The walk only runs when the + * candidate filter above found something, and an empty pool's blocks are + * the cascade, so they come off the lists by offset rather than by a second + * walk (heap_pool_unlist). */ +static uint32_t heap_find_empty_pools(ray_heap_t* h, unsigned mode, uint8_t* empty) { + uint32_t cand[RAY_MAX_POOLS]; + uint32_t n = heap_empty_pool_candidates(h, mode, cand); + if (n == 0) return 0; + + /* Candidates by base, so a block finds its pool by binary search. */ + uint8_t top = 0; + for (uint32_t i = 0; i < n; i++) { + uint32_t c = cand[i]; + uint32_t j = i; + for (; j > 0 && (uintptr_t)h->pools[cand[j - 1]].base + > (uintptr_t)h->pools[c].base; j--) + cand[j] = cand[j - 1]; + cand[j] = c; + if (h->pools[c].pool_order > top) top = h->pools[c].pool_order; + } + size_t free_bytes[RAY_MAX_POOLS]; + memset(free_bytes, 0, n * sizeof(free_bytes[0])); + for (int ord = RAY_ORDER_MIN; ord < top; ord++) { + if (!(h->avail & (1ULL << ord))) continue; + ray_fl_head_t* fh = &h->freelist[ord]; + for (ray_t* blk = fh->fl_next; blk != (ray_t*)fh; blk = blk->fl_next) { + uintptr_t a = (uintptr_t)blk; + uint32_t lo = 0, hi = n; /* first candidate based above a */ + while (lo < hi) { + uint32_t mid = (lo + hi) / 2; + if ((uintptr_t)h->pools[cand[mid]].base <= a) lo = mid + 1; + else hi = mid; + } + if (lo == 0) continue; + const ray_pool_entry_t* pe = &h->pools[cand[lo - 1]]; + if (a < (uintptr_t)pe->base + BSIZEOF(pe->pool_order)) + free_bytes[lo - 1] += BSIZEOF(ord); + } + } + + uint32_t found = 0; + for (uint32_t i = 0; i < n; i++) { + uint8_t po = h->pools[cand[i]].pool_order; + if (free_bytes[i] == BSIZEOF(po) - BSIZEOF(RAY_ORDER_MIN)) { + empty[cand[i]] = 1; + found++; + } + } + return found; +} + +/* Take empty pool p's blocks — the cascade heap_add_pool cut it into — off + * h's freelists. */ +static void heap_pool_unlist(ray_heap_t* h, uint32_t p) { + uintptr_t pb = (uintptr_t)h->pools[p].base; + for (uint8_t k = RAY_ORDER_MIN; k < h->pools[p].pool_order; k++) { + fl_remove((ray_t*)(pb + BSIZEOF(k))); + if (fl_empty(&h->freelist[k])) + h->avail &= ~(1ULL << k); + } +} + +/* Unmap pool p of h, empty and off the freelists — unlisted, or parked — and + * drop its entry, the last one moving into p; returns the anonymous bytes + * unmapped. */ +static int64_t heap_pool_unmap(ray_heap_t* h, uint32_t p) { + ray_pool_entry_t* pe = &h->pools[p]; + uint8_t po = pe->pool_order; + uintptr_t pb = (uintptr_t)pe->base; + int64_t anon = 0; + if (pe->parked) h->parked--; + + dfd_purge_range(pb, pb + BSIZEOF(po)); + ray_vm_free(((ray_pool_hdr_t*)pb)->vm_base, BSIZEOF(po)); + /* File-backed pools also need their fd closed and tempfile + * unlinked, mirroring the heap_destroy path. Unmapping drops the + * unlinked file's pages without writing them back. */ + if (pe->backed) { + atomic_fetch_sub_explicit(&g_spill_pools, 1, memory_order_relaxed); + if (pe->swap_fd >= 0) close(pe->swap_fd); + if (pe->swap_path) { + unlink(pe->swap_path); + ray_sys_free(pe->swap_path); + } + } else { + atomic_fetch_sub_explicit(&g_anon_committed, + (int64_t)BSIZEOF(po), memory_order_relaxed); + anon = (int64_t)BSIZEOF(po); + } + h->pools[p] = h->pools[--h->pool_count]; + return anon; +} + +/* Unmap the pools of h that `mode` admits and whose bytes are all free, + * parked ones included, keeping h's last pool; returns the anonymous bytes + * unmapped. Same conditions as heap_find_empty_pools. */ +static int64_t heap_reclaim_empty_pools(ray_heap_t* h, unsigned mode) { + uint8_t empty[RAY_MAX_POOLS]; + memset(empty, 0, h->pool_count); + uint32_t n = heap_find_empty_pools(h, mode, empty); + for (uint32_t p = 0; h->parked && p < h->pool_count; p++) + if (h->pools[p].parked && heap_reclaim_admits(&h->pools[p], mode)) { + empty[p] = 1; + n++; + } + if (n == 0) return 0; + + /* Highest index first: unmapping pool p moves the last entry into p, and + * every entry above p has been dealt with by then. */ + int64_t anon = 0; + for (uint32_t p = h->pool_count; p-- > 0; ) { + if (!empty[p]) continue; + if (h->pool_count <= 1) break; /* a heap keeps its last pool */ + if (!h->pools[p].parked) heap_pool_unlist(h, p); + anon += heap_pool_unmap(h, p); + } + return anon; +} + +/* Parking. An empty pool kept for the next statement does not stay empty + * through it: every pool holds one free block of each small order (the + * cascade), so the first small allocations — the statement's own parsing + * and environment — take a block from each in turn, and by the time the + * statement wants a large block that the empty pools could make room for, + * none of them is empty. A parked pool keeps its mapping and its pages but + * its blocks are off the freelists: nothing is cut from it until the heap + * has no free block left of the order it needs (heap_unpark, on the + * allocation slow path before a new pool is mapped), and heap_make_room can + * still unmap it for a large block, an anonymous one. A spill one has its + * pages discarded at the boundary that parks it (heap_spill_pools_discard). + * The heap's last unparked pool stays on the lists. Parks the empty pools + * `mode` admits; the pool header keeps when (`now`, ms) the pool was parked + * (heap_spill_pools_age). */ +static void heap_park_empty_pools(ray_heap_t* h, unsigned mode, uint32_t now) { + uint8_t empty[RAY_MAX_POOLS]; + memset(empty, 0, h->pool_count); + if (heap_find_empty_pools(h, mode, empty) == 0) + return; + for (uint32_t p = h->pool_count; p-- > 0; ) { + if (!empty[p]) continue; + if (h->pool_count - h->parked <= 1) break; + heap_pool_unlist(h, p); + h->pools[p].parked = 1; + ((ray_pool_hdr_t*)h->pools[p].base)->parked_ms = now; + h->parked++; + } +} + +/* Put one parked pool's blocks back on the freelists — a spill one if + * `spill`, else an anonymous one; false if h has none. */ +static bool heap_unpark(ray_heap_t* h, bool spill) { + for (uint32_t p = h->pool_count; p-- > 0; ) { + ray_pool_entry_t* pe = &h->pools[p]; + if (!pe->parked || pe->backed != spill) continue; + uintptr_t pb = (uintptr_t)pe->base; + for (uint8_t o = pe->pool_order; o > RAY_ORDER_MIN; o--) + heap_insert_block(h, (ray_t*)(pb + BSIZEOF(o - 1)), (uint8_t)(o - 1)); + pe->parked = 0; + pe->discarded = 0; /* its pages are in use again */ + h->parked--; + return true; + } + return false; +} + +static void heap_unpark_all(ray_heap_t* h) { + while (h->parked && (heap_unpark(h, false) || heap_unpark(h, true))) {} +} + +/* An abandoned heap is visited by no boundary (heap_each_quiescent), so its + * empty spill pools would never age (heap_spill_pools_age): they go as its + * thread leaves it, which still owns it then. */ +static void heap_abandon_spill(ray_heap_t* h) { + for (uint32_t p = 0; p < h->pool_count; p++) + if (h->pools[p].backed) { + heap_flush_slabs(h); + (void)heap_reclaim_empty_pools(h, RAY_RECLAIM_SPILL); + return; + } +} + +/* The heaps a maintenance point may work on from this thread: its own, and + * the parked workers' of the live pool. Any other registered heap belongs + * to a thread that may be allocating right now — an embedding's own threads, + * a host-driven poll loop — or to none yet, and then may be adopted at any + * moment; only its owner may touch its freelists. Caller ensures + * ray_parallel_flag is clear. */ +static void heap_each_quiescent(void (*fn)(ray_heap_t* h, void* ctx), void* ctx) { + if (ray_tl_heap) fn(ray_tl_heap, ctx); + ray_pool_each_worker_heap(fn, ctx); +} + +static void heap_reclaim_oversized(ray_heap_t* h, void* ctx) { + (void)ctx; + (void)heap_reclaim_empty_pools(h, RAY_RECLAIM_OVERSIZED); +} + void ray_heap_gc(void) { + ray_parted_cache_prune(); ray_heap_t* h = ray_tl_heap; if (!h) return; #ifdef DEBUG @@ -2345,109 +2824,13 @@ void ray_heap_gc(void) { * Only oversized pools (pool_order > RAY_HEAP_POOL_ORDER) are * candidates — these are one-off large allocations. * - * Emptiness is computed by walking all heaps' freelists and slab - * caches to sum free capacity within the pool. This avoids atomic - * live_count operations on the alloc/free hot path. */ - /* Pass 4: Reclaim oversized empty pools. - * - * Emptiness is "every byte of the pool is on gh's own freelist or in - * its slab cache". That single sum is now the whole test: a block of - * gh's that is live, or queued on gh->foreign, or queued anywhere - * else, is by construction NOT on those two structures, so it shows - * up as a shortfall. The registry-wide foreign scan (and the - * destructive purge that had to follow it, because the scan raced) - * existed only because a free used to leave the block on whichever - * heap did the freeing. */ - for (int hid = 0; hid < RAY_HEAP_REGISTRY_SIZE; hid++) { - ray_heap_t* gh = ray_heap_registry[hid]; - if (!gh) continue; - - for (uint32_t p = 0; p < gh->pool_count; ) { - ray_pool_hdr_t* phdr = (ray_pool_hdr_t*)gh->pools[p].base; - - /* Skip standard pools and last-remaining pool */ - if (phdr->pool_order <= RAY_HEAP_POOL_ORDER - || gh->pool_count <= 1) { - p++; - continue; - } - - uint8_t po = phdr->pool_order; - uintptr_t pb = (uintptr_t)phdr; - uintptr_t pe = pb + BSIZEOF(po); - size_t pool_capacity = BSIZEOF(po) - BSIZEOF(RAY_ORDER_MIN); - - /* (a) Sum free bytes from owning heap's freelist + slabs */ - size_t free_bytes = 0; - for (int ord = RAY_ORDER_MIN; ord < RAY_HEAP_FL_SIZE; ord++) { - ray_fl_head_t* fh = &gh->freelist[ord]; - ray_t* blk = fh->fl_next; - while (blk != (ray_t*)fh) { - if ((uintptr_t)blk >= pb && (uintptr_t)blk < pe) - free_bytes += BSIZEOF(ord); - blk = blk->fl_next; - } - } - for (int si = 0; si < RAY_SLAB_ORDERS; si++) { - for (uint32_t j = 0; j < gh->slabs[si].count; j++) { - ray_t* sb = gh->slabs[si].stack[j]; - if ((uintptr_t)sb >= pb && (uintptr_t)sb < pe) - free_bytes += BSIZEOF(RAY_SLAB_MIN + si); - } - } - - if (free_bytes < pool_capacity) { - p++; - continue; /* pool still has live or queued blocks */ - } - - /* Pool is entirely free — safe to munmap. Remove its blocks - * from the owning heap's freelists and slab caches. */ - for (int ord = RAY_ORDER_MIN; ord < RAY_HEAP_FL_SIZE; ord++) { - ray_fl_head_t* fh = &gh->freelist[ord]; - ray_t* blk = fh->fl_next; - while (blk != (ray_t*)fh) { - ray_t* next = blk->fl_next; - if ((uintptr_t)blk >= pb && (uintptr_t)blk < pe) { - fl_remove(blk); - dfd_remove(blk); - if (fl_empty(fh)) - gh->avail &= ~(1ULL << ord); - } - blk = next; - } - } - for (int si = 0; si < RAY_SLAB_ORDERS; si++) { - uint32_t dst = 0; - for (uint32_t j = 0; j < gh->slabs[si].count; j++) { - ray_t* sb = gh->slabs[si].stack[j]; - if ((uintptr_t)sb >= pb && (uintptr_t)sb < pe) { - dfd_remove(sb); - continue; - } - gh->slabs[si].stack[dst++] = sb; - } - gh->slabs[si].count = dst; - } - - dfd_purge_range(pb, pe); - ray_vm_free(phdr->vm_base, BSIZEOF(po)); - /* File-backed pools also need their fd closed and tempfile - * unlinked, mirroring the heap_destroy path. */ - if (gh->pools[p].backed) { - if (gh->pools[p].swap_fd >= 0) close(gh->pools[p].swap_fd); - if (gh->pools[p].swap_path) { - unlink(gh->pools[p].swap_path); - ray_sys_free(gh->pools[p].swap_path); - } - } else { - atomic_fetch_sub_explicit(&g_anon_committed, - (int64_t)BSIZEOF(po), memory_order_relaxed); - } - gh->pools[p] = gh->pools[--gh->pool_count]; - /* Don't increment p — check swapped entry */ - } - } + * Emptiness is computed from the owning heap's freelists (see + * heap_reclaim_empty_pools). This avoids atomic live_count + * operations on the alloc/free hot path. Only our own heap and the + * parked workers' are visited (heap_each_quiescent); a worker's + * slab cache is not flushed here (pass 3), so a pool with a block + * still in it waits for a later pass. */ + heap_each_quiescent(heap_reclaim_oversized, NULL); /* Pass 5: Release physical pages from free blocks in every * idle heap. Pass 2 may have returned blocks to worker-owned @@ -2525,7 +2908,9 @@ void ray_heap_gc(void) { /* Hand back the pages of every free block of `h` at or above the release * floor that has not already been released, and report how many. The three * callers differ only in which heaps they visit and what they do first; - * the walk itself is this. */ + * the walk itself is this. A block of a spill pool is only marked: its + * pages are the spill file's page cache, which madvise unmaps from us + * without freeing — such memory goes back when its pool is unmapped. */ static int64_t heap_release_free_pages(ray_heap_t* h) { int64_t released = 0; for (int ord = RAY_RELEASE_MIN_ORDER; ord < RAY_HEAP_FL_SIZE; ord++) { @@ -2535,20 +2920,138 @@ static int64_t heap_release_free_pages(ray_heap_t* h) { blk = blk->fl_next) { if (blk->attrs > RAY_FREE_AGE_RELEASE) continue; /* released */ int pidx = heap_find_pool(h, blk); + blk->attrs = RAY_FREE_AGE_RELEASE + 1; + if (pidx >= 0 && h->pools[pidx].backed) continue; bool hp = (pidx >= 0) ? (h->pools[pidx].hugepage != 0) : false; ray_vm_release_block(blk, BSIZEOF(ord), hp); - blk->attrs = RAY_FREE_AGE_RELEASE + 1; released++; } } return released; } +/* Whether a parked spill pool's pages are discarded (heap_spill_discard) — + * or the pool unmapped, as where the platform cannot discard them. Policy: + * the setter (ray_heap_set_spill_discard) is for tests. */ +static _Atomic(bool) g_spill_discard = true; +static _Atomic(int64_t) g_spill_discard_calls = 0; /* ray_heap_spill_discard_count */ + +bool ray_heap_set_spill_discard(bool on) { + return atomic_exchange_explicit(&g_spill_discard, on, memory_order_relaxed); +} + +/* Discard the pages of parked spill pool pe — dead data — and keep its file + * and its mapping for the next statement that spills: from the pool's + * second page to the end of its last page in RAM (ray_vm_resident_end: as + * far as its use reached), the range is punched out of the file, each dirty + * page with it, unwritten, and its memory free; then reserved again + * (heap_preallocate), so a later store still finds its disk block. The + * first page — the pool header and the free headers of the cascade's + * smallest blocks — stays as it is; the other cascade blocks' headers are + * written anew when the pool is taken back (heap_unpark), and nothing reads + * a parked pool's blocks before that. Returns 1 if pages were punched, 0 + * if none past the first page were in RAM, and -1 where it cannot be done — + * no way to punch a mapped range on this platform (macOS: F_PUNCHHOLE does + * not say what it does to pages mapped shared), or the file system or the + * disk refused: the pool is to be unmapped then. With pe NULL, 0 where + * pages would be discarded, -1 where not (ray_heap_spill_discards). */ +static int heap_spill_discard(const ray_pool_entry_t* pe) { +#if RAY_HEAP_FILE_SPILL && defined(__linux__) && defined(FALLOC_FL_PUNCH_HOLE) + if (!atomic_load_explicit(&g_spill_discard, memory_order_relaxed)) return -1; + if (!pe) return 0; + long ps = sysconf(_SC_PAGESIZE); + size_t pg = ps > 0 ? (size_t)ps : 4096; + size_t end = ray_vm_resident_end(pe->base, BSIZEOF(pe->pool_order)); + if (end <= pg) return 0; + off_t off = (off_t)pg, len = (off_t)(end - pg); + if (fallocate(pe->swap_fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, off, len) != 0 + || heap_preallocate(pe->swap_fd, off, len) != 0) + return -1; + return 1; +#else + (void)pe; + return -1; +#endif +} + +int64_t ray_heap_spill_discard_count(void) { + return atomic_load_explicit(&g_spill_discard_calls, memory_order_relaxed); +} + +bool ray_heap_spill_discards(void) { + return heap_spill_discard(NULL) == 0; +} + +/* Discard the pages of h's parked spill pools not discarded since they were + * last in use — those parked at this boundary — or unmap a pool whose pages + * cannot be (the boundary that parked it left h another pool, unparked). + * Returns whether pages were dropped: the boundary then flushes the + * cgroup's statistics (ray_sys_mem_flush). */ +static bool heap_spill_pools_discard(ray_heap_t* h) { + bool dropped = false; + for (uint32_t p = h->pool_count; h->parked && p-- > 0; ) { + ray_pool_entry_t* pe = &h->pools[p]; + if (!pe->parked || !pe->backed || pe->discarded) continue; + atomic_fetch_add_explicit(&g_spill_discard_calls, 1, memory_order_relaxed); + int got = heap_spill_discard(pe); + if (got < 0) { + (void)heap_pool_unmap(h, p); + dropped = true; + continue; + } + pe->discarded = 1; + dropped |= got > 0; + } + return dropped; +} + +/* A parked spill pool that no statement has taken back for the idle decay's + * threshold is unmapped, its file closed — but not h's last pool: the decay + * pool by pool, for a process never idle that long — a server — which would + * otherwise keep the files, their disk blocks reserved, for good. A negative + * threshold — the decay disabled — is never reached, as unsigned. `now` as + * for heap_park_empty_pools. */ +static void heap_spill_pools_age(ray_heap_t* h, uint32_t now) { + int64_t thr = heap_decay_threshold_ms(); + for (uint32_t p = h->pool_count; h->parked && h->pool_count > 1 && p-- > 0; ) { + const ray_pool_entry_t* pe = &h->pools[p]; + if (pe->parked && pe->backed + && now - ((const ray_pool_hdr_t*)pe->base)->parked_ms >= (uint64_t)thr) + (void)heap_pool_unmap(h, p); + } +} + +/* A direct or sys block of `bytes` is about to cross the watermark. Before + * it goes to a spill file, give back what the calling thread holds free: the + * direct-block cache, then its own heap's empty anonymous pools — parked + * ones above all (heap_park_empty_pools) — which no block of that size is + * ever cut from. A statement that freed its pool temporaries and goes on to + * large blocks would otherwise spill those while the pools sit empty and + * counted, and no rule at the boundary can tell that the next statement + * wants large blocks rather than its pools back. Only the caller's heap: + * any other, a worker's included, may be allocating right now. Returns + * whether `bytes` still crosses the watermark. */ +static bool heap_make_room(size_t bytes) { + direct_cache_drain(); + if (!heap_anon_would_exceed(bytes)) return false; +#if RAY_HEAP_FILE_SPILL + ray_heap_t* h = ray_tl_heap; + if (!h) return true; + heap_drain_foreign(h); + heap_flush_slabs(h); + int64_t got = heap_reclaim_empty_pools(h, RAY_RECLAIM_ANON); + return got == 0 || heap_anon_would_exceed(bytes); +#else + return true; /* past the watermark the block comes from RAM all the same */ +#endif +} + void ray_heap_release_pages(void) { /* Explicit release: callers asking for pages back get them NOW — * no aging — but still skip blocks already released. */ ray_heap_t* h = ray_tl_heap; if (!h) return; + heap_unpark_all(h); (void)heap_release_free_pages(h); } @@ -2568,8 +3071,10 @@ void ray_heap_release_pages(void) { * that already exist at the end of a unit of work — the statement boundary * and the event loop between wakeups — compare that stamp against a * threshold. If the process has been quiet longer than the threshold, one - * un-aged sweep releases the pages of every free block in every heap; - * otherwise the check is a relaxed load and a subtraction. + * un-aged sweep releases the pages of every free block and unmaps every + * empty spill pool (madvise frees nothing of a file mapping; see + * heap_release_free_pages); otherwise the check is a relaxed load and a + * subtraction. * * The threshold is the whole point: it is what separates "the workload has * stopped" from "we are between two iterations of a hot loop". Releasing in @@ -2584,7 +3089,7 @@ void ray_heap_release_pages(void) { * sweep after every one of them, discarding the working set the next is * about to fault back in. * - * The sweep works on EVERY registered heap, not just the caller's, and it + * The sweep works on the pool workers' heaps as well as the caller's, and it * drains each one's foreign list and slab cache before walking its * freelists. That is not incidental: in a server the main thread frees the * results of a parallel query, so the blocks land on the owning WORKER's @@ -2592,7 +3097,9 @@ void ray_heap_release_pages(void) { * memory — which a warm heap never does. Freelist-only, the sweep sees a * small fraction of the free bytes; with the drain it sees nearly all of * them. Draining also coalesces, so the pages come back in large runs - * instead of scattered blocks below the order-13 floor. + * instead of scattered blocks below the order-13 floor. No other heap is + * visited: the registry also holds the heaps of other live threads, whose + * freelists only their owners may touch (heap_each_quiescent). * * That is sound only because the sweep runs when ray_parallel_flag is 0. * The dispatcher clears the flag only after every worker's `pending--` is @@ -2657,6 +3164,18 @@ int64_t ray_heap_decay_due_ms(void) { return due > 0 ? due : 0; } +static void heap_decay_sweep(ray_heap_t* h, void* ctx) { + /* Blocks freed to h by another thread, and h's own slab cache, are not + * on a freelist and would be invisible to the walk below — in a server + * that is where most of the free bytes are. Nor are the blocks of a + * parked pool. */ + heap_drain_foreign(h); + heap_flush_slabs(h); + heap_unpark_all(h); + (void)heap_reclaim_empty_pools(h, RAY_RECLAIM_SPILL); + *(int64_t*)ctx += heap_release_free_pages(h); +} + int64_t ray_heap_decay(void) { if (ray_heap_decay_due_ms() != 0) return -1; if (atomic_load_explicit(&ray_parallel_flag, memory_order_relaxed) != 0) @@ -2667,22 +3186,227 @@ int64_t ray_heap_decay(void) { atomic_store_explicit(&g_heap_decay_armed, false, memory_order_relaxed); int64_t released = 0; - for (int hid = 0; hid < RAY_HEAP_REGISTRY_SIZE; hid++) { - ray_heap_t* gh = ray_heap_registry[hid]; - if (!gh) continue; - /* Blocks freed to gh by another thread, and gh's own slab cache, - * are not on a freelist and would be invisible to the walk below — - * in a server that is where most of the free bytes are. */ - heap_drain_foreign(gh); - heap_flush_slabs(gh); - released += heap_release_free_pages(gh); - } + heap_each_quiescent(heap_decay_sweep, &released); return released; } +/* What a relief would hand back, as far as the candidate filter can tell: + * the anonymous bytes of the heaps that did not spill a pool (room; of other + * threads' heaps, room_other). */ +typedef struct { int64_t room, room_other; } relieve_measure_t; + +static void heap_relieve_measure(ray_heap_t* h, void* ctx) { + relieve_measure_t* m = ctx; + heap_drain_foreign(h); + heap_flush_slabs(h); + if (h->spilled) return; + uint32_t cand[RAY_MAX_POOLS]; + uint32_t n = heap_empty_pool_candidates(h, RAY_RECLAIM_ANON, cand); + uint8_t empty[RAY_MAX_POOLS]; + memset(empty, 0, h->pool_count); + for (uint32_t i = 0; i < n; i++) empty[cand[i]] = 1; + int64_t room = 0; + uint32_t gone = 0; /* pools the reclaim would take */ + for (uint32_t p = 0; p < h->pool_count; p++) { + const ray_pool_entry_t* pe = &h->pools[p]; + if ((empty[p] || pe->parked) && !pe->backed) { + room += (int64_t)BSIZEOF(pe->pool_order); + gone++; + } + } + /* With every pool empty, the reclaim keeps the first. */ + if (gone && gone == h->pool_count) + room -= (int64_t)BSIZEOF(h->pools[0].pool_order); + m->room += room; + if (h != ray_tl_heap) m->room_other += room; +} + +typedef struct { int64_t released; uint32_t now; bool near, act, dropped; } relieve_visit_t; + +/* If the relief acts (act), a heap gives back its empty spill pools, and a + * heap that did not spill a pool its empty anonymous ones too and the pages + * of its other free blocks — one that did keeps those: it ran out of its + * own. What stays empty is parked, a parked spill pool's pages are + * discarded, and a spill pool long unused is unmapped. The heap has been + * looked at: what it spilled is known now. Far from the watermark (!near) + * the visit is only for the spill pools: it parks the empty ones it finds on + * the freelists as they are, without a drain or a slab flush — a pool with + * a block still in either waits for a later visit, and the next statement + * keeps its slab cache. */ +static void heap_relieve_visit(ray_heap_t* h, void* ctx) { + relieve_visit_t* v = ctx; + if (v->near) { + heap_drain_foreign(h); + heap_flush_slabs(h); + } + int64_t spills = atomic_load_explicit(&g_spill_pools, memory_order_relaxed); + heap_spill_pools_age(h, v->now); + if (v->act) { + (void)heap_reclaim_empty_pools(h, h->spilled ? RAY_RECLAIM_SPILL + : RAY_RECLAIM_SPILL | RAY_RECLAIM_ANON); + if (!h->spilled) v->released += heap_release_free_pages(h); + } + heap_park_empty_pools(h, v->near ? RAY_RECLAIM_ANON | RAY_RECLAIM_SPILL + : RAY_RECLAIM_SPILL, v->now); + v->dropped |= heap_spill_pools_discard(h); + v->dropped |= atomic_load_explicit(&g_spill_pools, memory_order_relaxed) != spills; + h->spilled = 0; +} + +/* What the boundaries since the last relief have shown (ray_heap_relieve). */ +enum { + RELIEF_NONE, /* nothing against relieving */ + RELIEF_JUST, /* the last relief has not been put to the test yet */ + RELIEF_FUTILE, /* the statement after it spilled all the same */ +}; +static _Atomic(int) g_relieve_state = RELIEF_NONE; +static _Atomic(int64_t) g_relieve_wm = 0; /* the watermark of the last relief */ +static _Atomic(int64_t) g_relieve_maps = 0; /* g_anon_maps at the last boundary */ +static _Atomic(int64_t) g_relieve_large = 0; /* g_anon_large at the last boundary */ +static _Atomic(int64_t) g_relieve_spills = 0; /* g_anon_spills at the last boundary */ +static _Atomic(bool) g_relieve_other = false; /* the last relief took others' pools */ + +/* Statement boundary. A free block keeps its pages and a standard pool + * stays mapped, so the next query reuses them without faulting (see the idle + * decay above). Where memory is short that can turn against the next query: + * a kept pool still counts toward the watermark, so memory the next query + * wants in another form — a large block, or a pool of another heap — goes to + * spill files instead. A repeated heavy query then ran far slower than its + * first run. Handing back at every boundary near the watermark was no + * answer either: the next statement maps and faults it straight back + * (#750). So the boundary acts on evidence, not on the footprint alone. + * + * The evidence is a spill: a mapping of the statement that just ended went + * past RAM (g_anon_spills). Then a heap that spilled a pool ran out of its + * own, so its empty pools are its working set and stay, parked; the empty + * anonymous pools of the heaps that did not are memory the spilling one + * could not reach. Those are unmapped — the relief — when that hands back + * at least a pool and brings the next pool under the watermark; the + * direct-block cache goes with them, and the pages of those heaps' other + * free blocks. + * + * A relief can be futile: when the next statement that maps anything spills + * again although it took the room for pools only, the room went back to the + * same kind of memory it came from — more relief only refaults it. No relief + * then until a statement maps without spilling, or the watermark moves. A + * statement that maps nothing says nothing either way. The other way round, + * when the statement after a relief that took other threads' pools does not + * spill but puts large blocks in that room and runs up to the watermark, it + * needed the relief, and a repeat of it will again (a heavy query run again + * and again): its boundary relieves as a spill's would. + * + * Without the evidence, near the watermark (the next pool would not fit), + * the empty pools are parked (heap_park_empty_pools): the next statement + * takes them back without a fault, and its large blocks can still have them + * (heap_make_room). + * + * An empty spill pool is parked like the rest, its file and its mapping + * kept for the next statement that spills, but its pages — dead data — are + * discarded at the boundary that parks it (heap_spill_pools_discard): a + * dirty one is dropped unwritten, which the kernel would otherwise write + * back for nothing, and its memory is free; the next statement that spills + * takes the pool back, its pages zero-filled anew. Where pages cannot be + * discarded the pool is unmapped instead. + * When the relief acts, the empty spill pools go with the anonymous ones, + * from every heap the relief visits, the spilling one's too, and a parked + * spill pool unused for the idle decay's threshold goes too + * (heap_spill_pools_age), so a server that is never idle does not keep its + * file for good. After spill pages are dropped, the limiting cgroup's + * statistics are flushed (ray_sys_mem_flush): the kernel updates them + * lazily and holds writers to them, and the dirty pages just dropped would + * otherwise throttle the next writes as if they were still there (measured: + * a 64 MB spill right after dropping 137 MB of dirty pages, 1.2 s instead of + * 0.1 s, 900 MB cgroup). The boundary + * visits the heaps while any spill pool is mapped — far from the watermark + * at most every RAY_FAR_VISIT_MS, and only for the spill pools. + * + * Every check is a relaxed load or a counter comparison; the walks — a + * drain and a slab flush per heap, a few header reads per possibly-empty + * pool, one freelist walk where a pool may be empty — run only on a spill or + * near the watermark (far from it, while a spill pool is mapped: the header + * reads and the walk). A spill pool parked at this boundary costs a + * mincore, a hole punched and the range reserved again; one parked before, + * nothing. + * + * Only this thread's heap and the parked workers' are visited + * (heap_each_quiescent). Without file spill (Windows) the watermark does not + * decide where memory goes — past it a pool comes from RAM all the same — so + * there is nothing to win, and the memory is left to the idle decay. + * Returns the number of blocks whose pages were released. */ +int64_t ray_heap_relieve(void) { + if (!RAY_HEAP_FILE_SPILL) return 0; + if (atomic_load_explicit(&ray_parallel_flag, memory_order_relaxed) != 0) + return 0; + const int64_t pool = (int64_t)BSIZEOF(RAY_HEAP_POOL_ORDER); + int64_t wm = heap_anon_watermark(); + int64_t committed = atomic_load_explicit(&g_anon_committed, memory_order_relaxed); + + /* What the statement that just ended did, and what that says of the + * last relief. */ + int64_t maps = atomic_load_explicit(&g_anon_maps, memory_order_relaxed); + int64_t large = atomic_load_explicit(&g_anon_large, memory_order_relaxed); + int64_t spills = atomic_load_explicit(&g_anon_spills, memory_order_relaxed); + int64_t peak = atomic_exchange_explicit(&g_anon_stmt_peak, committed, + memory_order_relaxed); + bool spilled = atomic_exchange_explicit(&g_relieve_spills, spills, + memory_order_relaxed) != spills; + bool mapped = atomic_exchange_explicit(&g_relieve_maps, maps, + memory_order_relaxed) != maps || spilled; + large -= atomic_exchange_explicit(&g_relieve_large, large, memory_order_relaxed); + bool needed = false; + int state = atomic_load_explicit(&g_relieve_state, memory_order_relaxed); + if (wm != atomic_load_explicit(&g_relieve_wm, memory_order_relaxed)) + state = RELIEF_NONE; + else if (mapped && state == RELIEF_JUST) { + needed = large >= pool && peak + pool > wm + && atomic_load_explicit(&g_relieve_other, memory_order_relaxed); + state = (spilled && large < pool) ? RELIEF_FUTILE : RELIEF_NONE; + } else if (mapped && state == RELIEF_FUTILE && !spilled) + state = RELIEF_NONE; + atomic_store_explicit(&g_relieve_state, state, memory_order_relaxed); + if (wm <= 0) return 0; + + bool relieve = (spilled || needed) && state == RELIEF_NONE; + bool near = relieve || spilled || committed + pool > wm; + if (!near && atomic_load_explicit(&g_spill_pools, memory_order_relaxed) == 0) + return 0; + int64_t now = ray_time_now_ms(); + if (!near) { + if (now - atomic_load_explicit(&g_far_visit_ms, memory_order_relaxed) + < RAY_FAR_VISIT_MS) + return 0; + atomic_store_explicit(&g_far_visit_ms, now, memory_order_relaxed); + } + relieve_visit_t v = { 0, (uint32_t)now, near, false, false }; + if (relieve) { + relieve_measure_t m = { direct_cache_bytes(), 0 }; + heap_each_quiescent(heap_relieve_measure, &m); + v.act = m.room >= pool && committed - m.room + pool <= wm; + if (v.act) { + direct_cache_drain(); + atomic_store_explicit(&g_relieve_wm, wm, memory_order_relaxed); + atomic_store_explicit(&g_relieve_state, RELIEF_JUST, memory_order_relaxed); + atomic_store_explicit(&g_relieve_other, m.room_other >= pool, + memory_order_relaxed); + } + } + heap_each_quiescent(heap_relieve_visit, &v); + /* The next statement's peak starts from the footprint this boundary + * leaves, not the one it found: what the relief handed back is no part + * of it (its peak decides whether it needed a relief). */ + atomic_store_explicit(&g_anon_stmt_peak, + atomic_load_explicit(&g_anon_committed, memory_order_relaxed), + memory_order_relaxed); + if (v.dropped) ray_sys_mem_flush(); + return v.released; +} + void ray_heap_merge(ray_heap_t* src) { ray_heap_t* dst = ray_tl_heap; if (!dst || !src) return; + /* A parked pool's blocks are on no list; the freelist splice below + * carries only listed ones. */ + heap_unpark_all(src); /* Merge stats: dst inherits src's outstanding allocations so that * future local frees of those blocks correctly decrement dst. */ @@ -3075,6 +3799,7 @@ static size_t retained_walk(const ray_t* v, ptrset_t* seen) { n += retained_walk(LAMBDA_NFO(lam), seen); n += retained_walk(LAMBDA_DBG(lam), seen); n += retained_walk(LAMBDA_CLOSURE(lam), seen); + n += retained_walk(LAMBDA_CAPROWS(lam), seen); return n; } if (ray_atom_owns_obj(v)) n += retained_walk(v->obj, seen); diff --git a/src/mem/heap.h b/src/mem/heap.h index 7c42d8497..20fab3804 100644 --- a/src/mem/heap.h +++ b/src/mem/heap.h @@ -52,6 +52,7 @@ * * Bits 0x01-0x03 RAY_SYM vectors: sym index width (RAY_SYM_W8/W16/W32/W64) * Bits 0x01-0x10 function objects (RAY_UNARY/BINARY/VARY): RAY_FN_* flags + * Bit 0x01 -RAY_STR atoms: RAY_ATTR_STR_CELL (a string column's cell bound for a row) * Bit 0x02 -RAY_I64 atoms: RAY_ATTR_GRAPH (ray_rel_t* CSR handle in .i64) * Bit 0x04 -RAY_I64 atoms: RAY_ATTR_HNSW (HNSW handle in .i64) * Bit 0x08 vectors: RAY_ATTR_HAS_INDEX (index ray_t* in aux[0..7]) @@ -86,6 +87,11 @@ * (.graph.free h) explicitly; the heap finalizer also frees the underlying * ray_rel_t when the atom's rc drops to zero so rebindings/scope-exit * never leak the graph. */ +/* RAY_ATTR_STR_CELL (-RAY_STR atoms): the atom is one cell of a string + * column, bound by a query that evaluates an expression row by row. `in` + * answers it as one value, as it answers a string element of a collection, + * not character by character as it answers a lone string literal. */ +#define RAY_ATTR_STR_CELL 0x01 #define RAY_ATTR_GRAPH 0x02 /* I64 atom carries an owning ray_hnsw_t* in its .i64 slot. @@ -213,6 +219,7 @@ typedef struct ray_dispatch ray_dispatch_t; void ray_heap_init(void); void ray_heap_destroy(void); + /* Detach the calling thread from its heap WITHOUT tearing the heap down: * the heap stays registered with its pools intact and is handed to the next * thread that calls ray_heap_init(). @@ -259,8 +266,10 @@ void ray_heap_release_pages(void); * none is pending (nothing to release, or decay disabled). An event loop * uses it to bound a wait it would otherwise make indefinite. * ray_heap_decay — sweep if due and if the worker pool is - * quiescent; returns the number of blocks released, or -1 if it did - * nothing. Safe to call from any maintenance point. + * quiescent: release the pages of free blocks and unmap empty spill pools + * of the caller's heap and the workers'; returns the number of blocks + * released, or -1 if it did nothing. Safe to call from any maintenance + * point. * * The threshold is fixed policy, reachable only through * ray_heap_set_decay_ms: negative disables the decay, 0 releases at the @@ -268,12 +277,36 @@ void ray_heap_release_pages(void); void ray_heap_note_activity(void); int64_t ray_heap_decay_due_ms(void); int64_t ray_heap_decay(void); +/* At a statement boundary: after a statement that spilled (or one that, + * right after such a relief, needed its room for large blocks), unmap the + * empty pools of the heaps that did not spill a pool when that makes room + * for the next pool under the anon watermark, drain the direct-block cache + * and release the pages of free blocks — unless the last relief was + * followed by a spill all the same. Otherwise, near the watermark, park + * empty pools. Empty spill pools are parked too, their files and mappings + * kept for the next spill but their pages discarded, a dirty one unwritten + * (where the platform cannot discard them, unmapped instead), and unmapped + * when the relief acts, from every heap but for a heap's last pool, or at + * the decay threshold. + * No-op inside parallel work and without file spill (Windows). */ +int64_t ray_heap_relieve(void); /* Set the threshold directly; negative disables. The environment is read * once on first use, so this exists to let a test drive the policy without * re-exec — not as a runtime knob. */ void ray_heap_set_decay_ms(int64_t ms); +/* Whether an empty parked spill pool's pages are discarded at the boundary + * (true) or the pool is unmapped, as where the platform cannot discard + * them (false). Policy; it exists for tests, as ray_heap_set_decay_ms. */ +bool ray_heap_set_spill_discard(bool on); /* returns the setting it replaced */ +/* Whether a parked spill pool's pages are discarded here and now: the + * platform can punch a mapped range, and the setting allows it. */ +bool ray_heap_spill_discards(void); +/* How many parked spill pools a boundary has set out to discard so far — + * each once per use (ray_heap_relieve). For tests. */ +int64_t ray_heap_spill_discard_count(void); + /* -------------------------------------------------------------------------- * Constants * -------------------------------------------------------------------------- */ @@ -329,21 +362,37 @@ static inline bool ray_direct_file_backed(const ray_t* v) { return ((const ray_direct_hdr_t*)((const char*)v - RAY_DIRECT_HDR))->swap_fd >= 0; } -/* Anonymous (RAM-resident, OOM-killable) pool + direct bytes currently - * committed by the heap. Allocations that would push this past the anon - * 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 +/* Bytes [0, upto) of ray_alloc_raw block `p` are not read again, and [0, + * from) of them were reported before. When `p` is spilled (a direct block + * over a spill file), the whole pages among them are punched out of the + * file now: a dirty one is never written back, and the page cache it held + * is free for what comes next. They read zero after. A no-op for every + * other block, and where the platform cannot punch a mapped range. True + * when pages were punched out. */ +bool ray_raw_discard(void* p, size_t from, size_t upto); + +/* Anonymous (RAM-resident, OOM-killable) pool, direct and sys bytes currently + * committed. Allocations that would push this past the anon watermark + * (default: ray_sys_ram_limit — physical RAM, or the container's cgroup + * memory limit when that is smaller — less a quarter of it, at least 3 GiB + * and at most half, left to the page cache) 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. */ int64_t ray_heap_anon_committed(void); /* High-water mark of the anon-committed footprint since process start — the - * peak RAM an operator actually demanded (pools + direct; excludes spill). */ + * peak RAM an operator actually demanded (pools, direct and sys blocks; + * excludes spill). */ int64_t ray_heap_anon_peak(void); /* Current anon watermark in bytes (the effective spill threshold; resolves 0 - * to ray_sys_ram_limit()). */ + * to the default, ray_sys_ram_limit() less the page-cache room). */ int64_t ray_heap_anon_watermark(void); void ray_heap_set_anon_watermark(int64_t bytes); +/* The RAM a query may plan for (sizing gates, cache budgets): the watermark + * when one was set (-m), else ray_sys_ram_limit(). Unlike the default + * watermark it does not leave the page-cache room, which decides where new + * memory goes, not how much a query may hold. */ +int64_t ray_heap_mem_budget(void); /* Release every block held by the direct-allocation reuse cache back to * the kernel (their committed-RAM accounting drops with them). The cache * self-drains under watermark pressure; this is for tests and explicit @@ -360,7 +409,8 @@ void ray_heap_direct_cache_drain(void); typedef struct { uint16_t heap_id; /* owning heap ID (for cross-thread free) */ uint8_t pool_order; /* pool's top order */ - uint8_t _pad[5]; + uint8_t _pad; + uint32_t parked_ms; /* when it was last parked, ms, wrapping (heap_park_empty_pools) */ void* vm_base; /* original mmap base (for ray_vm_free on Windows) */ } ray_pool_hdr_t; @@ -420,7 +470,11 @@ typedef struct { uint8_t pool_order; /* pool order for munmap sizing */ uint8_t backed; /* 0 = anon mmap, 1 = file-backed swap */ uint8_t hugepage; /* 1 = THP hint issued (Linux); 0 otherwise */ - uint8_t _pad[1]; + uint8_t parked : 1; /* empty, its blocks off the freelists + * (heap_park_empty_pools) */ + uint8_t discarded : 1; /* parked spill pool whose pages were discarded + * since it was last in use + * (heap_spill_pools_discard) */ } ray_pool_entry_t; /* -------------------------------------------------------------------------- @@ -537,6 +591,8 @@ typedef struct ray_heap { ray_mem_stats_t stats; uint32_t pool_count; /* number of tracked pools */ uint32_t last_pool_idx; /* MRU pool index for warm-first ray_free */ + uint32_t parked; /* pools parked among them */ + uint32_t spilled; /* a pool spilled since a boundary looked */ ray_pool_entry_t pools[RAY_MAX_POOLS]; /* pool tracking for destroy/merge */ struct ray_heap* pending_next; /* link for pending-merge LIFO queue */ struct ray_heap* idle_next; /* link for the abandoned-heap LIFO */ diff --git a/src/mem/sys.c b/src/mem/sys.c index 1147d1598..c1788b192 100644 --- a/src/mem/sys.c +++ b/src/mem/sys.c @@ -35,9 +35,10 @@ typedef struct { size_t map_size; /* total mmap'd bytes (header + user, page-rounded) */ size_t usr_size; /* user-requested bytes (for realloc memcpy) */ + bool spilled; /* mapped over a spill file (ray_heap_sys_map) */ /* Padding sized so the struct totals SYS_HDR_SIZE on both 32-bit - * (WASM, size_t=4 → pad=24) and 64-bit (Linux/macOS, size_t=8 → pad=16). */ - char _pad[SYS_HDR_SIZE - 2 * sizeof(size_t)]; + * (WASM, size_t=4) and 64-bit (Linux/macOS, size_t=8). */ + char _pad[SYS_HDR_SIZE - 2 * sizeof(size_t) - sizeof(bool)]; } sys_hdr_t; _Static_assert(sizeof(sys_hdr_t) == SYS_HDR_SIZE, "sys_hdr_t must be 32 bytes"); @@ -63,8 +64,16 @@ static inline void track_bump(_Atomic(int64_t)* cur_c, _Atomic(int64_t)* peak_c, void ray_sys_track_add(int64_t bytes) { track_bump(&g_sys_current, &g_sys_peak, bytes); } void ray_sys_track_sub(int64_t bytes) { track_bump(&g_sys_current, &g_sys_peak, -bytes); } -void ray_sys_track_file_add(int64_t bytes) { track_bump(&g_sys_mapped, &g_sys_mapped_peak, bytes); } -void ray_sys_track_file_sub(int64_t bytes) { track_bump(&g_sys_mapped, &g_sys_mapped_peak, -bytes); } +/* A file mapping is counted in whole pages on both sides. Mapping knows + * the file's exact length, but a free often re-derives it from the header + * and rounds to a page (heap.c, mmod 1), so counting raw bytes on the way + * in let every column read leave its page tail behind as a negative drift + * (#786). */ +static inline int64_t file_pages(int64_t bytes) { + return (bytes + 4095) & ~(int64_t)4095; +} +void ray_sys_track_file_add(int64_t bytes) { track_bump(&g_sys_mapped, &g_sys_mapped_peak, file_pages(bytes)); } +void ray_sys_track_file_sub(int64_t bytes) { track_bump(&g_sys_mapped, &g_sys_mapped_peak, -file_pages(bytes)); } static inline size_t page_round(size_t n) { return (n + 4095) & ~(size_t)4095; @@ -77,19 +86,21 @@ void* ray_sys_alloc(size_t size) { if (size == 0) size = 1; if (size > SIZE_MAX - SYS_HDR_SIZE) return NULL; size_t total = page_round(SYS_HDR_SIZE + size); - void* p = ray_vm_alloc(total); + bool spilled = false; + void* p = ray_heap_sys_map(total, &spilled); if (!p) return NULL; sys_hdr_t* hdr = (sys_hdr_t*)p; hdr->map_size = total; hdr->usr_size = size; + hdr->spilled = spilled; return (char*)p + SYS_HDR_SIZE; } void ray_sys_free(void* ptr) { if (!ptr) return; sys_hdr_t* hdr = (sys_hdr_t*)((char*)ptr - SYS_HDR_SIZE); - ray_vm_free(hdr, hdr->map_size); + ray_heap_sys_unmap(hdr, hdr->map_size, hdr->spilled); } /* L5: ray_sys_realloc(ptr, 0) frees ptr and returns NULL, matching the diff --git a/src/mem/sys.h b/src/mem/sys.h index 5be39a6dc..6436c40ec 100644 --- a/src/mem/sys.h +++ b/src/mem/sys.h @@ -26,6 +26,7 @@ #include #include +#include /* -------------------------------------------------------------------------- * System-level mmap allocator for infrastructure that can't use the buddy @@ -38,10 +39,21 @@ * so ray_sys_free() needs no size argument. * -------------------------------------------------------------------------- */ +/* Page-granular allocations off the per-thread heaps. They count toward + * the heap's anonymous watermark, and large ones spill to a file past it + * (ray_heap_sys_map / ray_heap_sys_unmap, defined in mem/heap.c). + * + * ray_sys_alloc returns zero-filled memory, and callers rely on it (the + * import dictionary's shard tables are not cleared): every block is a fresh + * mapping, anonymous or over a new preallocated spill file, never one taken + * from a cache of freed blocks. A cache added here must zero what it hands + * out. ray_sys_realloc keeps no such promise for the bytes it adds. */ void* ray_sys_alloc(size_t size); void* ray_sys_realloc(void* ptr, size_t new_size); void ray_sys_free(void* ptr); char* ray_sys_strdup(const char* s); +void* ray_heap_sys_map(size_t size, bool* spilled); +void ray_heap_sys_unmap(void* p, size_t size, bool spilled); /* -------------------------------------------------------------------------- * Global memory accounting. Two counters give the true runtime picture: @@ -55,8 +67,9 @@ char* ray_sys_strdup(const char* s); * * The low-level VM wrappers (ray_vm_alloc / _aligned / _free / _map_file / * _unmap_file) and the one raw-mmap site (heap swap fallback) call these so - * every mapping is counted exactly once. Bytes are the mapped length; add and - * sub must balance (same length in as out). + * every mapping is counted exactly once. Bytes are the mapped length (file + * mappings in whole 4 KiB pages); add and sub must balance (same length in as + * out, or the same once rounded to a page). * -------------------------------------------------------------------------- */ void ray_sys_track_add(int64_t bytes); /* committed RAM + */ void ray_sys_track_sub(int64_t bytes); /* committed RAM - */ diff --git a/src/ops/agg_engine.c b/src/ops/agg_engine.c index 836ba4edc..6a66a1de9 100644 --- a/src/ops/agg_engine.c +++ b/src/ops/agg_engine.c @@ -8,6 +8,8 @@ #include "lang/internal.h" /* sym_domain_rep */ #include "table/domain.h" #include "table/sym.h" /* ray_read_sym */ +#include "store/col.h" /* ray_col_cold — sampled-row read-ahead */ +#include "core/pool.h" /* ray_pool_want — a column asked for whole */ #include "core/platform.h" /* ray_cache_llc_bytes — replicated slab bound */ #include #include @@ -316,8 +318,19 @@ static void agg_key_bounds_fn(void* raw, uint32_t wid, int64_t start, int64_t en for (int64_t task = start; task < end; task++) { int64_t begin = c->rows / c->tasks * task; int64_t limit = task + 1 == c->tasks ? c->rows : c->rows / c->tasks * (task + 1); - agg_key_bounds(c->key, begin, limit, c->nullable, c->null, - &c->bounds[task * 2], &c->bounds[task * 2 + 1]); + /* Often the first read of the key: read ahead block by block. The + * key is the one column read, so it is requested from the first + * block on. */ + int64_t lo = INT64_MAX, hi = INT64_MIN; + for (int64_t b = begin; b < limit; b += 65536) { + int64_t e = limit - b > 65536 ? b + 65536 : limit, l, h; + ray_pool_scan_col_at(ray_data(c->key), c->rows, b, limit); + agg_key_bounds(c->key, b, e, c->nullable, c->null, &l, &h); + if (l < lo) lo = l; + if (h > hi) hi = h; + } + c->bounds[task * 2] = lo; + c->bounds[task * 2 + 1] = hi; } } static void agg_key_bounds_parallel(ray_t* key, int64_t rows, bool nullable, @@ -486,6 +499,321 @@ static bool agg_dense_plan_compact(ray_t** key_cols, uint32_t n_keys, int64_t nr return true; } +/* An estimate of the groups a key tuple forms — see agg_engine.h. + * + * The columns are sampled together at a fixed stride, AGG_EST_SAMPLE rows + * over the input — the rows of `rows` when given, a selection's survivors, + * since a filter that drops a dominant key value (the empty model of a + * device column, on nine rows in ten) hides the groups and the shares of + * what remains — (every row below that; the strided reads miss the cache, + * and 32,768 of them over three columns cost half a millisecond at 10 M + * rows with the prefetch below; the pages of a mapped column are asked + * for ahead of them, ray_col_want_rows), one row from each window of `stride` rows + * at an offset hashed from the window's index (agg_est_row), and each + * column's values go through a small open-addressing set that counts how + * often each was seen. + * Blocks of adjacent rows would be cheaper to read but blind to clustered + * keys: a run of four rows per value shows a block one value per four rows, + * while a stride past the run length shows every sample distinct. The + * distinct count of the sample is then raised by the Chao1 species + * estimator, d + f1 (f1 - 1) / 2 (f2 + 1) — f1 and f2 the values seen once + * and twice — which answers for the values the sample missed: a key of 45 + * values has no singletons and stays 45; a skewed key, one value on nine + * rows in ten and a million on the rest, shows thousands of singletons and + * few pairs and lands near the million. Each key's estimate is capped at + * what it could hold, the span of its sampled values — its codes for a SYM + * key, which are fixed once interned (the process-wide domain's count + * bounds them too, but grows with every symbol interned afterwards, and + * the estimate with it). + * + * The same pass hashes the tuple of the first n_prefix columns and the + * tuple of all of them into two more sets, for the groups a composite key + * forms (its columns' product overstates a city beside its country by the + * number of countries) and for the tuples a (key, value) grouping would + * keep. A tuple holds at most the product of its columns' caps, and at + * most one value per row. A sorted prefix defeats the stride: every + * sample is a different tuple once the run length is below the stride, and + * the Chao1 saturates at the cap. The sample notices — its prefix tuples + * never decrease — and reads AGG_EST_BLOCKS blocks of AGG_EST_BLOCK adjacent + * rows as well, which see the runs: the groups are the rows over the mean + * run length, the tuples the distinct ones per block; the lower of the two + * readings stands. (A run longer than a block reads as a block, so blocks + * alone would overstate a key of few groups; the stride is exact there.) */ +enum { AGG_EST_SAMPLE = AGG_EST_SAMPLE_ROWS, AGG_EST_PREFETCH = 16, + AGG_EST_BLOCK = 256, AGG_EST_BLOCKS = AGG_EST_SAMPLE / AGG_EST_BLOCK }; + +/* A sampled key value as int64: the integer itself (a null is its sentinel, + * one more value), a SYM's code. */ +static inline int64_t agg_est_read(const void* d, int8_t t, uint8_t attrs, int64_t r) { + switch (t) { + case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)d)[r]; + case RAY_I32: case RAY_DATE: case RAY_TIME: return ((const int32_t*)d)[r]; + case RAY_I16: return ((const int16_t*)d)[r]; + case RAY_U8: case RAY_BOOL: return ((const uint8_t*)d)[r]; + default: return ray_read_sym(d, r, t, attrs); + } +} + +/* Fold one column's value into a tuple hash (order-sensitive). */ +static inline uint64_t agg_est_mix(uint64_t h, int64_t v) { + h ^= (uint64_t)v * 0x9E3779B97F4A7C15ULL; + h *= 0xBF58476D1CE4E5B9ULL; + return h ^ (h >> 31); +} + +/* An open-addressing set of sampled values with how often each was seen, + * kept as the Chao1 inputs d, f1, f2 and the count of the most frequent + * (the share of the largest group). A count is at most the sample. */ +typedef struct { + int64_t* vals; + uint16_t* cnt; + int64_t d, f1, f2, max; +} agg_est_set_t; + +static inline void agg_est_set_add(agg_est_set_t* s, uint64_t mask, int64_t v) { + uint64_t h = ((uint64_t)v * 0x9E3779B97F4A7C15ULL) >> 20 & mask; + for (;; h = (h + 1) & mask) { + if (s->cnt[h] == 0) { + s->vals[h] = v; s->cnt[h] = 1; s->d++; s->f1++; + if (s->max < 1) s->max = 1; + return; + } + if (s->vals[h] == v) { + uint16_t c = ++s->cnt[h]; + if (c == 2) { s->f1--; s->f2++; } + else if (c == 3) s->f2--; + if (c > s->max) s->max = c; + return; + } + } +} + +/* The Chao1 estimate from a set's counts (the distinct count itself when + * the sample is the whole input), capped at `cap` when that is positive; + * never below 1. */ +static int64_t agg_est_chao1(const agg_est_set_t* s, bool sampled, int64_t cap) { + int64_t est = s->d; + if (sampled && s->f1 > 1) { + /* f1 <= AGG_EST_SAMPLE: the product is far from overflowing */ + int64_t add = s->f1 * (s->f1 - 1) / (2 * (s->f2 + 1)); + est = add > INT64_MAX - est ? INT64_MAX : est + add; + } + if (cap > 0 && cap < est) est = cap; + return est < 1 ? 1 : est; +} + +/* What a tuple of columns 0..n can hold: the product of their caps (a + * column without one, or a product past nrows, is nrows) and nrows. */ +static int64_t agg_est_tuple_cap(const int64_t* cap, uint32_t n, int64_t nrows) { + int64_t prod = 1; + for (uint32_t k = 0; k < n; k++) { + if (cap[k] <= 0 || prod > nrows / cap[k]) return nrows; + prod *= cap[k]; + } + return prod < nrows ? prod : nrows; +} + +/* Blocks of adjacent rows over a sorted prefix: the groups as rows over the + * mean run length of the prefix tuple, the (prefix, rest) tuples as the + * distinct ones per block scaled to the input. false when the input is too + * short for the blocks (the stride is then exact anyway). */ +static bool agg_est_blocks(ray_t** cols, uint32_t n, uint32_t n_prefix, + const int64_t* rows, int64_t nrows, int64_t* pos, + int64_t* prefix_est, int64_t* all_est) { + enum { SLOTS = AGG_EST_BLOCK * 4 }; + if (nrows < (int64_t)AGG_EST_BLOCK * 4) return false; + int64_t nblk = AGG_EST_BLOCKS; + if (nblk * AGG_EST_BLOCK > nrows) nblk = nrows / AGG_EST_BLOCK; + const int64_t gap = nrows / nblk; + /* the blocks' rows listed first (`pos` holds AGG_EST_SAMPLE), so the + * pages of a mapped column are asked for ahead of the reads, as the + * strided sample's are */ + int64_t np = 0; + for (int64_t b = 0; b < nblk; b++) + for (int64_t i = b * gap; i < b * gap + AGG_EST_BLOCK; i++) pos[np++] = rows ? rows[i] : i; + for (uint32_t k = 0; k < n; k++) ray_col_want_rows(cols[k], pos, np); + int64_t vals[SLOTS]; + uint16_t cnt[SLOTS]; + agg_est_set_t set = { vals, cnt, 0, 0, 0, 0 }; + int64_t runs = 0, read = 0, distinct = 0; + np = 0; + for (int64_t b = 0; b < nblk; b++) { + memset(cnt, 0, sizeof cnt); + set.d = set.f1 = set.f2 = set.max = 0; + uint64_t hp_prev = 0; + for (int64_t i = 0; i < AGG_EST_BLOCK; i++) { + const int64_t r = pos[np++]; + uint64_t hp = 0, ha = 0; + for (uint32_t k = 0; k < n; k++) { + ha = agg_est_mix(ha, agg_est_read(ray_data(cols[k]), cols[k]->type, + cols[k]->attrs, r)); + if (k + 1 == n_prefix) hp = ha; + } + if (i == 0 || hp != hp_prev) runs++; + hp_prev = hp; + agg_est_set_add(&set, SLOTS - 1, (int64_t)ha); + } + distinct += set.d; + read += AGG_EST_BLOCK; + } + *prefix_est = (int64_t)((double)nrows * (double)runs / (double)read); + *all_est = (int64_t)((double)nrows * (double)distinct / (double)read); + if (*prefix_est < 1) *prefix_est = 1; + if (*all_est < 1) *all_est = 1; + return true; +} + +bool agg_group_card_sample(ray_t** cols, uint32_t n, uint32_t n_prefix, + const int64_t* rows, int64_t nrows, int64_t population, + int64_t* col_est, int64_t* prefix_est, int64_t* prefix_max, + int64_t* all_est) { + if (n < 1 || n > 16 || n_prefix < 1 || n_prefix > n || nrows <= 0) return false; + /* the rows the estimates describe: the list itself, or the population + * it was sampled from */ + const int64_t pop = population > nrows ? population : nrows; + int64_t cap[16]; + const void* data[16]; + size_t esz[16]; + for (uint32_t k = 0; k < n; k++) { + ray_t* c = cols[k]; + switch (c->type) { + case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: + case RAY_BOOL: case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + case RAY_SYM: + break; + default: + return false; + } + data[k] = ray_data(c); + esz[k] = col_esz(c); + } + const bool tuples = prefix_est || prefix_max || all_est; + const int64_t sample = nrows < AGG_EST_SAMPLE ? nrows : AGG_EST_SAMPLE; + uint64_t slots = 64; + while (slots < (uint64_t)sample * 2) slots <<= 1; + const uint32_t nsets = n + (tuples ? 2 : 0); + const size_t set_bytes = (size_t)slots * (sizeof(int64_t) + sizeof(uint16_t)); + uint8_t* mem = ray_alloc_raw(set_bytes * nsets + (size_t)AGG_EST_SAMPLE * sizeof(int64_t)); + if (!mem) return false; + /* The rows the pass reads, listed first: the pages of a mapped column + * are asked for ahead of the reads, through the pool, as the select's + * own scan asks for its. Read as they were met, each strided row of a + * column not in memory waited on its own page fault, on this thread — + * a quarter second and more per column at 100 M rows, where the pass + * costs a millisecond in memory. The pages asked for are those the + * sampled rows fall on (ray_col_want_rows), or the rows between the + * first and last sampled as one range when the rows the estimate + * describes fall on every page of that span — a row per page or more: + * the select reads the span whole then, and its stream runs while this + * pass waits on the first of them; a sample's pages alone, 30,000 + * reads of one page each, took twice as long as the stream. The span, + * not the column: a selection over a slice of a time-ordered table + * asks for its slice (a 1% window asked for the columns whole before, + * 90 MB read for 2 needed at 4 M rows). */ + int64_t* pos = (int64_t*)(mem + set_bytes * nsets); + for (int64_t i = 0; i < sample; i++) { + const int64_t ri = agg_est_sample_row(i, sample, nrows); + pos[i] = rows ? rows[ri] : ri; + } + int64_t lo_r = pos[0], hi_r = pos[0]; + for (int64_t i = 1; i < sample; i++) { + if (pos[i] < lo_r) lo_r = pos[i]; + if (pos[i] > hi_r) hi_r = pos[i]; + } + for (uint32_t k = 0; k < n; k++) { + const size_t span = (size_t)(hi_r - lo_r + 1) * esz[k]; + if (pop >= (int64_t)(span >> 12)) { + if (cols[k]->mmod == 1 && ray_pool_scan_on()) { + const uint8_t* p = (const uint8_t*)data[k] + (size_t)lo_r * esz[k]; + if (!ray_vm_resident(p, span)) ray_pool_want(p, span); + } + } else { + ray_col_want_rows(cols[k], pos, sample); + } + } + agg_est_set_t sets[18]; + for (uint32_t i = 0; i < nsets; i++) { + sets[i].vals = (int64_t*)(mem + (size_t)i * set_bytes); + sets[i].cnt = (uint16_t*)(mem + (size_t)i * set_bytes + (size_t)slots * sizeof(int64_t)); + memset(sets[i].cnt, 0, (size_t)slots * sizeof(uint16_t)); + sets[i].d = sets[i].f1 = sets[i].f2 = sets[i].max = 0; + } + const uint64_t mask = slots - 1; + int64_t lo[16], hi[16], prev[16]; + for (uint32_t k = 0; k < n; k++) { lo[k] = INT64_MAX; hi[k] = INT64_MIN; prev[k] = INT64_MIN; } + bool sorted = true; /* the sampled prefix tuples never decrease */ + for (int64_t i = 0; i < sample; i++) { + const int64_t r = pos[i]; + if (i + AGG_EST_PREFETCH < sample) { + /* the strided reads miss the cache; keep several in flight */ + const size_t rp = (size_t)pos[i + AGG_EST_PREFETCH]; + for (uint32_t k = 0; k < n; k++) + __builtin_prefetch((const char*)data[k] + rp * esz[k]); + } + uint64_t hp = 0, ha = 0; + int cmp = 0; /* the prefix tuple against the previous sample's */ + for (uint32_t k = 0; k < n; k++) { + const int64_t v = agg_est_read(data[k], cols[k]->type, cols[k]->attrs, r); + if (v < lo[k]) lo[k] = v; + if (v > hi[k]) hi[k] = v; + agg_est_set_add(&sets[k], mask, v); + if (tuples) { + ha = agg_est_mix(ha, v); + if (k < n_prefix) { + hp = ha; + if (cmp == 0 && v != prev[k]) cmp = v < prev[k] ? -1 : 1; + prev[k] = v; + } + } + } + if (tuples) { + if (cmp < 0) sorted = false; + agg_est_set_add(&sets[n], mask, (int64_t)hp); + agg_est_set_add(&sets[n + 1], mask, (int64_t)ha); + } + } + const bool sampled = sample < pop; + for (uint32_t k = 0; k < n; k++) { + /* the span of the sampled values (codes) bounds what the key can hold */ + uint64_t span = (uint64_t)hi[k] - (uint64_t)lo[k]; + cap[k] = span < (uint64_t)INT64_MAX - 1 ? (int64_t)span + 1 : 0; + int64_t est = agg_est_chao1(&sets[k], sampled, cap[k]); + if (col_est) col_est[k] = est; + } + if (tuples) { + int64_t kp = agg_est_chao1(&sets[n], sampled, agg_est_tuple_cap(cap, n_prefix, pop)); + int64_t ka = agg_est_chao1(&sets[n + 1], sampled, agg_est_tuple_cap(cap, n, pop)); + int64_t bp, ba; + /* adjacent entries of a sampled list are not adjacent rows */ + if (sorted && sampled && pop == nrows && + agg_est_blocks(cols, n, n_prefix, rows, nrows, pos, &bp, &ba)) { + if (bp < kp) kp = bp; + if (ba < ka) ka = ba; + } + if (prefix_est) *prefix_est = kp; + if (all_est) *all_est = ka; + /* the largest group's rows: its share of the sample over the population */ + if (prefix_max) *prefix_max = sets[n].max * (pop / sample) + + sets[n].max * (pop % sample) / sample; + } + ray_free_raw(mem); + return true; +} + +int64_t agg_group_card_estimate(ray_t** key_cols, uint32_t n_keys, int64_t nrows) { + int64_t est[16]; + if (n_keys < 1 || n_keys > 16 || + !agg_group_card_sample(key_cols, n_keys, n_keys, NULL, nrows, 0, est, NULL, NULL, NULL)) + return -1; + int64_t total = 1; + for (uint32_t k = 0; k < n_keys; k++) { + if (est[k] < 1) return -1; /* never below 1 (static analysis) */ + if (total > INT64_MAX / est[k]) return -1; + total *= est[k]; + } + return total; +} + bool agg_dense_plan(ray_t** key_cols, uint32_t n_keys, const agg_vtable_t** vts, uint32_t n_aggs, int64_t nrows, dense_plan_t* out) { @@ -675,6 +1003,60 @@ static void agg_gather_native_run(void* raw, uint32_t wid, int64_t start, int64_ if (any_null) atomic_store_explicit(&c->any_null, true, memory_order_relaxed); } +typedef struct { const ray_t* v; _Atomic(int) found; } key_null_scan_t; + +/* Any null sentinel in [start, end)? Written as a block-wise OR-reduction + * so the compiler vectorises the compare; the block boundary is where the + * early exit happens. */ +static bool key_null_in_range(const ray_t* v, int64_t start, int64_t end) { + const void* p = ray_data((ray_t*)v); + enum { BLOCK = 4096 }; + for (int64_t s = start; s < end; s += BLOCK) { + int64_t e = s + BLOCK < end ? s + BLOCK : end; + int any = 0; + switch (v->type) { + case RAY_F64: { const double* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] != d[i]); break; } + case RAY_F32: { const float* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] != d[i]); break; } + case RAY_I64: case RAY_TIMESTAMP: { const int64_t* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] == NULL_I64); break; } + case RAY_I32: case RAY_DATE: case RAY_TIME: { const int32_t* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] == NULL_I32); break; } + case RAY_I16: { const int16_t* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] == NULL_I16); break; } + case RAY_GUID: { const uint64_t* d = p; for (int64_t i = s; i < e; i++) any |= (d[2 * i] == 0 && d[2 * i + 1] == 0); break; } + default: return false; + } + if (any) return true; + } + return false; +} + +static void key_null_scan_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + key_null_scan_t* c = raw; + if (atomic_load_explicit(&c->found, memory_order_relaxed)) return; + if (key_null_in_range(c->v, start, end)) atomic_store_explicit(&c->found, 1, memory_order_relaxed); +} + +/* A result key column inherits its source column's "may have nulls" flag, + * but a fused `where:` can remove every null row, and the same query over + * the filtered table materialized first carries no flag: one result, two + * spellings on the wire. For a typed key keep the flag only when a key + * value is null: a vectorised sentinel scan, split across the pool for a + * large column. Text keys keep theirs: for them the flag is always "may". */ +void ray_group_key_settle_nulls(ray_t* kc) { + if (!kc || RAY_IS_ERR(kc) || !(kc->attrs & RAY_ATTR_HAS_NULLS)) return; + switch (kc->type) { + case RAY_F64: case RAY_F32: case RAY_I64: case RAY_TIMESTAMP: + case RAY_I32: case RAY_DATE: case RAY_TIME: case RAY_I16: case RAY_GUID: break; + default: return; + } + key_null_scan_t c = { kc, 0 }; + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, kc->len, RAY_PARALLEL_THRESHOLD)) + ray_pool_dispatch(pool, key_null_scan_fn, &c, kc->len); + else key_null_scan_fn(&c, 0, 0, kc->len); + if (!atomic_load_explicit(&c.found, memory_order_relaxed)) + kc->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; +} + /* Build a result key column of src_col's type by gathering the first-row cell * of each group at native (type-exact) byte width. For SYM, adopts the source * domain so the intern ids resolve correctly. Caller owns the returned column. */ @@ -684,7 +1066,14 @@ ray_t* ray_group_gather(ray_t* src_col, const int64_t* first_row, int64_t n) { if (!out || RAY_IS_ERR(out)) return out; for (int64_t i = 0; i < n; i++) { ray_t* value = first_row[i] < 0 ? NULL : ray_list_get(src_col, first_row[i]); - out = ray_list_append(out, value); + /* A failed append returns an error and leaves `out`, with the + * items it already retained, to the caller. */ + ray_t* next = ray_list_append(out, value); + if (!next || RAY_IS_ERR(next)) { + ray_release(out); + return next ? next : ray_error("oom", NULL); + } + out = next; } return out; } @@ -723,10 +1112,10 @@ ray_t* ray_group_gather(ray_t* src_col, const int64_t* first_row, int64_t n) { ray_pool_dispatch(pool, agg_gather_native_run, &c, n); else agg_gather_native_run(&c, 0, 0, n); if (agg_cancelled()) { ray_release(out); return ray_error("cancel", NULL); } - if (ray_vec_may_have_nulls(src_col) || - (atomic_load_explicit(&c.any_null, memory_order_relaxed) && - src_col->type != RAY_BOOL && src_col->type != RAY_U8)) - out->attrs |= RAY_ATTR_HAS_NULLS; + bool gathered_null = atomic_load_explicit(&c.any_null, memory_order_relaxed) && + src_col->type != RAY_BOOL && src_col->type != RAY_U8; + if (gathered_null || ray_vec_may_have_nulls(src_col)) out->attrs |= RAY_ATTR_HAS_NULLS; + if (!gathered_null) ray_group_key_settle_nulls(out); return out; } @@ -807,6 +1196,7 @@ typedef struct { const int64_t* prefix; /* per-segment selected-count prefix */ int64_t nrows; uint32_t n_segs; + int64_t row_end; /* past the segment of the range's last selected row */ /* iteration state */ int64_t remaining; /* selected rows left in this worker's range */ uint32_t seg; /* current segment */ @@ -826,6 +1216,7 @@ static void agg_sel_cursor_init(agg_sel_cursor_t* c, ray_t* sel, c->nrows = m->nrows; c->n_segs = m->n_segs; c->remaining = sel_end - sel_start; + c->row_end = c->nrows; if (c->remaining <= 0) { c->seg = c->n_segs; c->seg_pos = 0; return; } /* Find the segment containing the sel_start'th selected row: largest s with * prefix[s] <= sel_start. Linear-then-skip is fine (n_segs small), but the @@ -838,6 +1229,13 @@ static void agg_sel_cursor_init(agg_sel_cursor_t* c, ray_t* sel, } c->seg = lo; c->seg_pos = sel_start - prefix[lo]; /* intra-segment selected offset */ + /* And the one holding the last: the rows read ahead end there. */ + for (hi = c->n_segs; lo < hi; ) { + uint32_t mid = lo + (hi - lo) / 2; + if (prefix[mid + 1] <= sel_end - 1) lo = mid + 1; + else hi = mid; + } + if ((int64_t)(lo + 1) * RAY_MORSEL_ELEMS < c->nrows) c->row_end = (int64_t)(lo + 1) * RAY_MORSEL_ELEMS; } /* Decode the next chunk of original row indices into rows[] (cap AGG_SEL_CHUNK); @@ -868,6 +1266,10 @@ static int64_t agg_sel_cursor_next(agg_sel_cursor_t* c, int64_t* rows) { if (c->seg_pos >= seg_sel) { c->seg++; c->seg_pos = 0; } } } + /* A pass over the selection reads these rows next, in order: often the + * first read of its aggregate inputs (scan read-ahead; the filter's + * zones keep the chunks it rules out from being requested). */ + if (n) ray_pool_scan_at(c->nrows, rows[0], c->row_end); return n; } @@ -1711,8 +2113,10 @@ static void agg_dense_task_fn(void* raw, uint32_t wid, int64_t start, int64_t en int64_t begin = chunk * task; int64_t limit = task + 1 == c->n_tasks ? c->task_rows : chunk * (task + 1); if (c->sel) agg_dense_phaseA_fn(c, (uint32_t)task, begin, limit); - else for (int64_t row = begin; row < limit && !agg_cancelled(); row += 8192) + else for (int64_t row = begin; row < limit && !agg_cancelled(); row += 8192) { + ray_pool_scan_at(c->task_rows, row, limit); agg_dense_phaseA_fn(c, (uint32_t)task, row, limit - row < 8192 ? limit : row + 8192); + } if (loc->eager) for (int64_t s = 0; s < loc->slots; s++) if (loc->first_row[s] != INT64_MAX) loc->occupied[s / 64] |= UINT64_C(1) << (s % 64); @@ -1979,6 +2383,7 @@ static ray_t* agg_dense_finish(ray_t** key_cols, int64_t* key_syms, ray_op_ext_t if (kc->type == RAY_SYM) ray_sym_vec_adopt_domain(kc, sym_domain_rep(key_cols[k])); agg_dense_key_emit_t emit = {key_plan, occupied_slot, key_part_slots, key_bits, kc, k}; ray_pool_dispatch(pool, agg_dense_key_emit, &emit, ng); + ray_group_key_settle_nulls(kc); } result = ray_table_add_col(result, key_syms[k], kc); ray_release(kc); @@ -2040,6 +2445,7 @@ typedef struct { const dense_plan_t* plan; agg_valdesc_t values; int64_t rows, part_slots; + int64_t in_rows; /* rows of the input selected_rows index */ uint32_t sources, parts, bits, n_tasks; agg_dense_partition_task_t* tasks; uint64_t* counts; @@ -2054,52 +2460,67 @@ typedef struct { _Atomic(bool) failed; } agg_dense_partition_ctx_t; +/* Slots and partition counts of input positions [begin, limit). */ +static void agg_dense_partition_count_rows(agg_dense_partition_ctx_t* c, uint64_t* count, + int64_t begin, int64_t limit) { + const void* data = ray_data(c->key); + if (c->plan->n_keys > 1) { + #define PART_SLOT_MULTI(COMPONENT) \ + for (int64_t r = begin; r < limit; r++) { \ + int64_t source = c->selected_rows ? c->selected_rows[r] : r; \ + int64_t slot = 0; \ + for (uint32_t k = 0; k < c->plan->n_keys; k++) \ + slot += COMPONENT(c->plan, k, agg_read_key_i64(c->keys[k], c->key_data[k], source)) * c->plan->strides[k]; \ + c->gids[r] = (uint32_t)slot; \ + count[slot & (c->parts - 1)]++; \ + } + if (c->plan->compacted) { PART_SLOT_MULTI(agg_dense_component); } + else { PART_SLOT_MULTI(agg_dense_component_raw); } + #undef PART_SLOT_MULTI + return; + } + #define PART_COUNT(T) do { \ + const T* p = data; \ + for (int64_t r = begin; r < limit; r++) { \ + uint32_t slot = (uint32_t)agg_dense_component_raw(c->plan, 0, (int64_t)p[c->selected_rows ? c->selected_rows[r] : r]); \ + c->gids[r] = slot; \ + count[slot & (c->parts - 1)]++; \ + } \ + } while (0) + switch (c->key->type) { + case RAY_I64: case RAY_TIMESTAMP: PART_COUNT(int64_t); break; + case RAY_I32: case RAY_DATE: case RAY_TIME: PART_COUNT(int32_t); break; + case RAY_I16: PART_COUNT(int16_t); break; + case RAY_U8: case RAY_BOOL: PART_COUNT(uint8_t); break; + case RAY_SYM: + switch (c->key->attrs & RAY_SYM_W_MASK) { + case RAY_SYM_W8: PART_COUNT(uint8_t); break; + case RAY_SYM_W16: PART_COUNT(uint16_t); break; + case RAY_SYM_W32: PART_COUNT(uint32_t); break; + default: PART_COUNT(int64_t); break; + } + break; + } + #undef PART_COUNT +} + static void agg_dense_partition_count(void* raw, uint32_t wid, int64_t start, int64_t end) { (void)wid; agg_dense_partition_ctx_t* c = raw; - const void* data = ray_data(c->key); for (int64_t task = start; task < end; task++) { int64_t begin = c->rows / c->sources * task; int64_t limit = task + 1 == c->sources ? c->rows : c->rows / c->sources * (task + 1); uint64_t* count = c->counts + task * c->parts; - if (c->plan->n_keys > 1) { - #define PART_SLOT_MULTI(COMPONENT) \ - for (int64_t r = begin; r < limit; r++) { \ - int64_t source = c->selected_rows ? c->selected_rows[r] : r; \ - int64_t slot = 0; \ - for (uint32_t k = 0; k < c->plan->n_keys; k++) \ - slot += COMPONENT(c->plan, k, agg_read_key_i64(c->keys[k], c->key_data[k], source)) * c->plan->strides[k]; \ - c->gids[r] = (uint32_t)slot; \ - count[slot & (c->parts - 1)]++; \ - } - if (c->plan->compacted) { PART_SLOT_MULTI(agg_dense_component); } - else { PART_SLOT_MULTI(agg_dense_component_raw); } - #undef PART_SLOT_MULTI - continue; - } - #define PART_COUNT(T) do { \ - const T* p = data; \ - for (int64_t r = begin; r < limit; r++) { \ - uint32_t slot = (uint32_t)agg_dense_component_raw(c->plan, 0, (int64_t)p[c->selected_rows ? c->selected_rows[r] : r]); \ - c->gids[r] = slot; \ - count[slot & (c->parts - 1)]++; \ - } \ - } while (0) - switch (c->key->type) { - case RAY_I64: case RAY_TIMESTAMP: PART_COUNT(int64_t); break; - case RAY_I32: case RAY_DATE: case RAY_TIME: PART_COUNT(int32_t); break; - case RAY_I16: PART_COUNT(int16_t); break; - case RAY_U8: case RAY_BOOL: PART_COUNT(uint8_t); break; - case RAY_SYM: - switch (c->key->attrs & RAY_SYM_W_MASK) { - case RAY_SYM_W8: PART_COUNT(uint8_t); break; - case RAY_SYM_W16: PART_COUNT(uint16_t); break; - case RAY_SYM_W32: PART_COUNT(uint32_t); break; - default: PART_COUNT(int64_t); break; - } - break; + if (begin >= limit) continue; + /* This pass is the first read of the keys: keep the rows past each + * block requested from storage (scan read-ahead), from the input + * row the block starts at — selected rows come in order. */ + const int64_t* sel = c->selected_rows; + int64_t stop = sel ? sel[limit - 1] + 1 : limit; + for (int64_t b = begin; b < limit; b += 8192) { + ray_pool_scan_at(c->in_rows, sel ? sel[b] : b, stop); + agg_dense_partition_count_rows(c, count, b, limit - b > 8192 ? b + 8192 : limit); } - #undef PART_COUNT } } @@ -2126,6 +2547,58 @@ static void agg_dense_partition_field(agg_dense_partition_ctx_t* c, const void* #undef SCATTER_FIELD } +/* Records of input positions [begin, limit), written at `cursor`. */ +static void agg_dense_partition_scatter_rows(agg_dense_partition_ctx_t* c, uint64_t* cursor, + int64_t begin, int64_t limit) { + const agg_valdesc_t* vd = &c->values; + if (vd->n_aggs == 1 && vd->val_data[0] && !vd->val2_data[0]) { + #define SCATTER_UNARY(W) do { \ + for (int64_t r = begin; r < limit; r++) { \ + uint32_t slot = c->gids[r]; \ + uint32_t gid = slot >> c->bits, part = slot & (c->parts - 1); \ + char* dst = c->payload + cursor[part]++ * (4 + (W)); \ + memcpy(dst, &gid, 4); \ + memcpy(dst + 4, (const char*)vd->val_data[0] + (size_t)(c->selected_rows ? c->selected_rows[r] : r) * (W), (W)); \ + } \ + } while (0) + switch (vd->val_esz[0]) { + case 1: SCATTER_UNARY(1); break; + case 2: SCATTER_UNARY(2); break; + case 4: SCATTER_UNARY(4); break; + case 8: SCATTER_UNARY(8); break; + } + #undef SCATTER_UNARY + return; + } + /* Complete nearby records before advancing through a source + * range. Whole-column passes repeatedly read/write the same large + * output buffer when several input fields share each record. */ + int64_t chunk_rows = (64 * 1024) / c->record_size; + if (chunk_rows > AGG_SEL_CHUNK) chunk_rows = AGG_SEL_CHUNK; + if (chunk_rows < 1) chunk_rows = 1; + uint64_t chunk_starts[RAY_POOL_INIT_TASKS / 2]; + for (int64_t chunk = begin; chunk < limit; chunk += chunk_rows) { + int64_t chunk_end = limit - chunk < chunk_rows ? limit : chunk + chunk_rows; + memcpy(chunk_starts, cursor, c->parts * sizeof(*cursor)); + for (int64_t r = chunk; r < chunk_end; r++) { + uint32_t slot = c->gids[r], part = slot & (c->parts - 1), gid = slot >> c->bits; + char* dst = c->payload + cursor[part]++ * c->record_size; + memcpy(dst, &gid, 4); + } + size_t emitted = sizeof(uint32_t); + for (uint32_t a = 0; a < vd->n_aggs; a++) { + if (vd->val_data[a] && c->value_offsets[a] >= emitted) { + agg_dense_partition_field(c, vd->val_data[a], vd->val_esz[a], c->value_offsets[a], chunk_starts, chunk, chunk_end); + emitted = c->value_offsets[a] + vd->val_esz[a]; + } + if (vd->val2_data[a] && c->value2_offsets[a] >= emitted) { + agg_dense_partition_field(c, vd->val2_data[a], vd->val2_esz[a], c->value2_offsets[a], chunk_starts, chunk, chunk_end); + emitted = c->value2_offsets[a] + vd->val2_esz[a]; + } + } + } +} + static void agg_dense_partition_scatter(void* raw, uint32_t wid, int64_t start, int64_t end) { (void)wid; agg_dense_partition_ctx_t* c = raw; @@ -2136,52 +2609,14 @@ static void agg_dense_partition_scatter(void* raw, uint32_t wid, int64_t start, uint64_t cursor[RAY_POOL_INIT_TASKS / 2]; assert(c->parts <= RAY_POOL_INIT_TASKS / 2); memcpy(cursor, starts, c->parts * sizeof(*cursor)); - const agg_valdesc_t* vd = &c->values; - if (vd->n_aggs == 1 && vd->val_data[0] && !vd->val2_data[0]) { - #define SCATTER_UNARY(W) do { \ - for (int64_t r = begin; r < limit; r++) { \ - uint32_t slot = c->gids[r]; \ - uint32_t gid = slot >> c->bits, part = slot & (c->parts - 1); \ - char* dst = c->payload + cursor[part]++ * (4 + (W)); \ - memcpy(dst, &gid, 4); \ - memcpy(dst + 4, (const char*)vd->val_data[0] + (size_t)(c->selected_rows ? c->selected_rows[r] : r) * (W), (W)); \ - } \ - } while (0) - switch (vd->val_esz[0]) { - case 1: SCATTER_UNARY(1); break; - case 2: SCATTER_UNARY(2); break; - case 4: SCATTER_UNARY(4); break; - case 8: SCATTER_UNARY(8); break; - } - #undef SCATTER_UNARY - } else { - /* Complete nearby records before advancing through a source - * range. Whole-column passes repeatedly read/write the same large - * output buffer when several input fields share each record. */ - int64_t chunk_rows = (64 * 1024) / c->record_size; - if (chunk_rows > AGG_SEL_CHUNK) chunk_rows = AGG_SEL_CHUNK; - if (chunk_rows < 1) chunk_rows = 1; - uint64_t chunk_starts[RAY_POOL_INIT_TASKS / 2]; - for (int64_t chunk = begin; chunk < limit; chunk += chunk_rows) { - int64_t chunk_end = limit - chunk < chunk_rows ? limit : chunk + chunk_rows; - memcpy(chunk_starts, cursor, c->parts * sizeof(*cursor)); - for (int64_t r = chunk; r < chunk_end; r++) { - uint32_t slot = c->gids[r], part = slot & (c->parts - 1), gid = slot >> c->bits; - char* dst = c->payload + cursor[part]++ * c->record_size; - memcpy(dst, &gid, 4); - } - size_t emitted = sizeof(uint32_t); - for (uint32_t a = 0; a < vd->n_aggs; a++) { - if (vd->val_data[a] && c->value_offsets[a] >= emitted) { - agg_dense_partition_field(c, vd->val_data[a], vd->val_esz[a], c->value_offsets[a], chunk_starts, chunk, chunk_end); - emitted = c->value_offsets[a] + vd->val_esz[a]; - } - if (vd->val2_data[a] && c->value2_offsets[a] >= emitted) { - agg_dense_partition_field(c, vd->val2_data[a], vd->val2_esz[a], c->value2_offsets[a], chunk_starts, chunk, chunk_end); - emitted = c->value2_offsets[a] + vd->val2_esz[a]; - } - } - } + if (begin >= limit) continue; + /* The first read of the aggregate inputs: keep the rows past each + * block requested, as in the count pass. */ + const int64_t* sel = c->selected_rows; + int64_t stop = sel ? sel[limit - 1] + 1 : limit; + for (int64_t b = begin; b < limit; b += 8192) { + ray_pool_scan_at(c->in_rows, sel ? sel[b] : b, stop); + agg_dense_partition_scatter_rows(c, cursor, b, limit - b > 8192 ? b + 8192 : limit); } } } @@ -2332,6 +2767,7 @@ static ray_t* agg_dense_partitioned(ray_t** key_cols, int64_t* key_syms, ray_op_ agg_dense_partition_ctx_t c = { .key = key_cols[0], .keys = key_cols, .key_data = d->key_data, .plan = plan, .rows = rows, .part_slots = part_slots, + .in_rows = selection ? ray_rowsel_meta(selection)->nrows : rows, .sources = sources, .parts = parts, .bits = bits, .failed = false, .values = { .n_aggs = ext->n_aggs, .vts = vo->vts, .off = vo->off, .block = vo->block, .val_data = d->val_data, .val_types = d->val_types, .val_hasnull = d->val_hasnull, .val_esz = d->val_esz, @@ -3285,8 +3721,15 @@ RAY_INLINE void agg_radix_chunk_pass(agg_radix_ctx_t* c, int64_t ch, bool scatte agg_radix_visit(c, cur, rows[i], pos++, scatter); return; } - for (int64_t r = start; r < end; r++) - agg_radix_visit(c, cur, r, r, scatter); + /* Keep the next rows requested from storage, block by block (scan + * read-ahead): the count pass is the first read of the key columns, the + * scatter pass the first of the aggregate columns. */ + for (int64_t b = start; b < end; b += 8192) { + int64_t e = end - b > 8192 ? b + 8192 : end; + ray_pool_scan_at(c->n_in, b, end); + for (int64_t r = b; r < e; r++) + agg_radix_visit(c, cur, r, r, scatter); + } } /* Phase 1, pass 1: count each chunk's rows per partition. */ @@ -4202,6 +4645,7 @@ static ray_t* agg_parts_emit(ray_op_ext_t* ext, agg_desc_t* d, ray_release(result); return kerr; } for (uint32_t k = 0; k < n_keys; k++) { + ray_group_key_settle_nulls(kouts[k]); result = ray_table_add_col(result, key_syms[k], kouts[k]); ray_release(kouts[k]); } @@ -5232,6 +5676,13 @@ static bool agg_ts_precheck_declines(ray_t** key_cols, uint32_t n_keys, int64_t const int64_t ratio = AGG_TS_PRE_SAMPLE2 / AGG_TS_PRE_SAMPLE; int64_t pstep = nrows / AGG_TS_PRE_SAMPLE2; if (pstep < 1) pstep = 1; + if (!sel) + for (uint32_t k = 0; k < n_keys; k++) + if (ray_col_cold(key_cols[k])) + for (int64_t i = 0; i < AGG_TS_PRE_SAMPLE2; i++) { + int64_t pos = i * pstep + (int64_t)(ray_hash_i64(i + 7919) % (uint64_t)pstep); + if (pos < nrows) ray_col_want_row(key_cols[k], pos); + } int64_t d = 0, n = 0; bool declined = false; for (int64_t phase = 0; phase < ratio && !declined; phase++) { @@ -5311,6 +5762,12 @@ static double agg_ts_estimate(ray_pool_t* pool, ray_t** key_cols, const void** k .sel = sel, .sel_prefix = sel_prefix, .hs = hs, .cnt = cnt, .keys = keys, .n = ns, }; + if (!sel) + for (uint32_t k = 0; k < n_keys; k++) + if (ray_col_cold(key_cols[k])) + for (int64_t i = 0; i < AGG_TS_SAMPLE; i++) + ray_col_want_row(key_cols[k], + i * ctx.step + (int64_t)(ray_hash_i64(i) % (uint64_t)ctx.step)); if (ray_pool_par_dispatch_ok(pool, AGG_TS_SAMPLE, 1)) ray_pool_dispatch_n(pool, agg_ts_sample_fn, &ctx, AGG_TS_SAMPLE_TASKS); else @@ -5978,6 +6435,10 @@ static ray_t* agg_indexed_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ray_t* src = ie ? ray_table_get_col(tbl, ie->sym) : NULL; int64_t param = ext->agg_k ? ext->agg_k[a] : 0; ray_t* col = NULL; + /* The kernels below read src at every row, group by group, so at + * scattered rows: a cold mapped column is requested first, whole + * (scan read-ahead). */ + if (src && ray_pool_scan_on()) ray_col_want_rows(src, rows, nrows); if (kind == OP_MEDIAN) col = ray_median_per_group_buf(src, rows, offsets, counts, ng); else if (kind == OP_QUANTILE) { double q = 0.5; if (ext->agg_k) memcpy(&q, ¶m, sizeof(q)); @@ -6051,6 +6512,9 @@ static bool agg_shared_sample(ray_graph_t* g, ray_op_ext_t* ext, ray_t* tbl, uint32_t gid = 0; int groups = 0, unchanged = 0; int64_t step = rows / SAMPLES; + if (ray_col_cold(keys[0])) + for (int i = 0; i < SAMPLES; i++) + ray_col_want_row(keys[0], i * step + (int64_t)(ray_hash_i64(i) % (uint64_t)step)); for (int i = 0; i < SAMPLES; i++) { uint64_t jitter = ray_hash_i64(i); int64_t row = i * step + jitter % step; @@ -6343,6 +6807,7 @@ static void agg_firstn_task(agg_firstn_ctx_t* c, uint32_t t) { 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; + if (!(seg & 7)) ray_pool_scan_at(c->nrows, b, s1 * 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); @@ -6474,6 +6939,9 @@ static ray_t* agg_first_n_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t { int64_t samples = nrows < AGG_FIRSTN_SAMPLES ? nrows : AGG_FIRSTN_SAMPLES; int64_t step = nrows / samples, hits = 0; + for (uint32_t k = 0; k < n_keys; k++) + if (ray_col_cold(key_cols[k])) + for (int64_t i = 0; i < samples; i++) ray_col_want_row(key_cols[k], i * step); 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); @@ -6701,7 +7169,7 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * this is data-derived and independent of cache or RAM size. */ uint32_t dense_workers = ray_pool_total_workers(pool); double scatter_budget = (double)eff_n * 2 * (8.0 * (ext->n_keys + ext->n_aggs + 1)); - int64_t watermark = ray_heap_anon_watermark(); + int64_t watermark = ray_heap_mem_budget(); double dense_budget = scatter_budget; if (dense_budget > (double)SIZE_MAX) dense_budget = (double)SIZE_MAX; if (watermark > 0 && dense_budget > (double)watermark / 4) dense_budget = (double)watermark / 4; @@ -6805,6 +7273,15 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (dense_par_ok && !sel && ext->n_keys == 1) { const void* data = ray_data(key_cols[0]); double touched_slots = 0; + if (ray_col_cold(key_cols[0])) + for (uint32_t w = 0; w < dense_workers; w++) { + int64_t start = nrows / dense_workers * w; + int64_t end = w + 1 == dense_workers ? nrows : nrows / dense_workers * (w + 1); + int64_t samples = end - start < 1024 ? end - start : 1024; + for (int64_t i = 0; i < samples; i++) + ray_col_want_row(key_cols[0], + start + i * ((end - start - 1) / (samples > 1 ? samples - 1 : 1))); + } for (uint32_t w = 0; w < dense_workers; w++) { int64_t start = nrows / dense_workers * w; int64_t end = w + 1 == dense_workers ? nrows : nrows / dense_workers * (w + 1); @@ -6969,7 +7446,7 @@ static ray_t* agg_build_compact(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (!seen) want[n_want++] = s; } for (uint32_t a = 0; a < ext->n_aggs; a++) { - if (ext->agg_ops[a] == OP_COUNT && !(ext->agg_ins && ext->agg_ins[a] != RAY_OP_NONE)) + if (ext->agg_ops[a] == OP_COUNT) continue; /* COUNT needs no typed input */ ray_op_t* ins[2] = { ext->agg_ins ? op_node(g, ext->agg_ins[a]) : NULL, ext->agg_ins2 ? op_node(g, ext->agg_ins2[a]) : NULL }; diff --git a/src/ops/agg_engine.h b/src/ops/agg_engine.h index 6029e234f..4814e15c4 100644 --- a/src/ops/agg_engine.h +++ b/src/ops/agg_engine.h @@ -219,6 +219,75 @@ bool agg_dense_plan(ray_t** key_cols, uint32_t n_keys, const agg_vtable_t** vts, uint32_t n_aggs, int64_t nrows, dense_plan_t* out); +/* Cardinality estimates for a planner choosing between strategies before + * any grouping runs (try_count_distinct_v2_rewrite), from one strided + * sample of 32,768 rows over `cols` (every row below that) — over the + * `nrows` row indices of `rows` when that is given (a selection's + * survivors), else over rows 0..nrows. When `rows` is itself a sample of + * a larger population (the survivors of a predicate run over sampled rows), + * `population` is that population's size — the estimates and the caps + * scale to it — else 0. A column's + * distinct values in the sample are raised by the Chao1 estimator from the + * values seen once and twice, so a key the sample cannot exhaust — a + * million values, or one value on most rows and a million on the rest — is + * estimated near its size, while a key of 45 values stays 45. The + * estimate is capped at the span of the sampled values — the codes of a + * SYM key, fixed once interned, where the process-wide domain's count + * would move the estimate with every symbol interned afterwards. + * col_est[k] (when given) receives column k's estimate; + * prefix_est the estimate for the tuple of the first n_prefix columns (the + * groups a composite key forms, which the product of its columns' estimates + * overstates when one column follows from another); prefix_max the rows of + * the largest such group (its share of the sample over the input: a + * per-group pass is serial over it); all_est the estimate + * for the tuple of all n columns (the tuples a (key, value) grouping would + * keep). A tuple is capped at the product of its columns' caps and at + * nrows; a sorted prefix, which a stride reads as all distinct, is read + * through blocks of adjacent rows as well. Estimates, never bounds: a + * planner weighs them against thresholds with slack. false — with the + * outputs unset — when a column is not a dense key type (integer, temporal, + * SYM), n is 0 or above 16, the input is empty, or memory runs out. */ +bool agg_group_card_sample(ray_t** cols, uint32_t n, uint32_t n_prefix, + const int64_t* rows, int64_t nrows, int64_t population, + int64_t* col_est, int64_t* prefix_est, int64_t* prefix_max, + int64_t* all_est); + +/* The rows the estimator samples (every row below that). */ +#define AGG_EST_SAMPLE_ROWS (1 << 15) + +/* The row the estimator samples from window i of the `sample` equal ones + * the rows are cut into (nrows / sample rows each, fractional): an offset + * into the window hashed from i by the splitmix64 finaliser. A fixed + * offset reads a key whose period divides the stride — five values + * cycling under a stride of 305 — as one value. An offset nearly linear + * in i, the high bits of i times the golden ratio, keeps the sampled rows + * an arithmetic progression and a key with a period near the stride at a + * nearly fixed phase: a composite of (% i 1000) and (% i 1009) at 10 M + * rows read as ten million tuples under it, one of 1000 and 1013 as a + * tenth of its groups. The finaliser's offsets make the collisions those + * of a random sample. Shared with a planner sampling rows for a predicate + * (query.c). */ +static inline int64_t agg_est_sample_row(int64_t i, int64_t sample, int64_t nrows) { + /* window i of `sample` equal ones over the rows, [lo, hi): a whole + * stride would leave the rows past sample * (nrows / sample) unread, + * the last fifth of 41,943 rows under a sample of 32,768 */ + const int64_t lo = (int64_t)((double)i * (double)nrows / (double)sample); + int64_t hi = (int64_t)((double)(i + 1) * (double)nrows / (double)sample); + if (hi > nrows) hi = nrows; + const int64_t w = hi - lo; + if (w <= 1) return lo; + uint64_t h = (uint64_t)i * 0x9E3779B97F4A7C15ULL; + h = (h ^ (h >> 30)) * 0xBF58476D1CE4E5B9ULL; + h = (h ^ (h >> 27)) * 0x94D049BB133111EBULL; + h ^= h >> 31; + return lo + (int64_t)(h % (uint64_t)w); +} + +/* The product of the per-key estimates above for key_cols: the packed key + * space a direct-index grouping would hold. -1 when a key is not a dense + * key type, the input is empty, or the product overflows. */ +int64_t agg_group_card_estimate(ray_t** key_cols, uint32_t n_keys, int64_t nrows); + /* Result column name for a plain-column-input aggregate: input column name * (ray_sym_str of in_sym) + per-op suffix (_sum/_count/_mean/_min/_max/...), * interned. Falls back to in_sym on buffer overflow. Behavior-identical to diff --git a/src/ops/cdfuse.c b/src/ops/cdfuse.c index db90762e0..c341e8ffd 100644 --- a/src/ops/cdfuse.c +++ b/src/ops/cdfuse.c @@ -54,7 +54,10 @@ #include "ops/internal.h" /* scratch_*, read_col_i64 */ #include "ops/hash.h" /* ray_hash_i64 */ #include "ops/cdfuse.h" +#include "ops/agg_engine.h" /* agg_group_card_sample — the route gate */ +#include "ops/hll.h" /* ray_count_distinct_approx — the gate's group count check */ #include "table/sym.h" /* RAY_IS_SYM */ +#include "store/col.h" /* ray_col_cold — sampled-row read-ahead */ /* Peak-footprint estimate used by the admission gate below: 32B/row for * phase 1's records plus up to 24B per (partition, key) pair in phase 2, @@ -146,13 +149,16 @@ static bool cdf_repeat(cdf_recent_t* recent, uint64_t hash, int64_t key, int64_t entry->key = key; entry->value = value; entry->used = true; return false; } +static inline int64_t cdf_sample_row(int64_t nrows, int i) { + int64_t step = nrows / 1024; + return i * step + ray_hash_i64(i) % step; +} static bool cdf_sample_repetition(const cdf_p1_ctx_t* c) { if (c->nrows < 1024) return false; cdf_recent_t recent[64] = {{0}}; int repeats = 0; - int64_t step = c->nrows / 1024; for (int i = 0; i < 1024; i++) { - int64_t row = i * step + ray_hash_i64(i) % step; + int64_t row = cdf_sample_row(c->nrows, i); int64_t key = cdf_read(c->kdata, row, c->ktype, c->kattrs); int64_t value = cdf_read(c->vdata, row, c->vtype, c->vattrs); repeats += cdf_repeat(recent, cdf_pair_hash(key, value), key, value); @@ -167,14 +173,20 @@ static void cdf_p1_hist(void* raw, uint32_t wid, int64_t start, int64_t end) { if (c->dedup) memset(recent, 0, sizeof(recent)); int64_t begin = c->nrows / c->nw * task; int64_t limit = task + 1 == c->nw ? c->nrows : c->nrows / c->nw * (task + 1); - for (int64_t r = begin; r < limit; r++) { - int64_t k = cdf_read(c->kdata, r, c->ktype, c->kattrs); - int64_t v = cdf_read(c->vdata, r, c->vtype, c->vattrs); - uint64_t hash = cdf_pair_hash(k, v); - if (c->dedup && cdf_repeat(recent, hash, k, v)) continue; - uint32_t part = hash & (c->n_parts - 1); - if (my[part].cap == UINT32_MAX) { atomic_store(&c->oom, 1); return; } - my[part].cap++; + /* The first read of these rows: keep the next ones requested from + * storage, block by block (scan read-ahead). */ + for (int64_t b = begin; b < limit; b += 8192) { + int64_t e = limit - b > 8192 ? b + 8192 : limit; + ray_pool_scan_at(c->nrows, b, limit); + for (int64_t r = b; r < e; r++) { + int64_t k = cdf_read(c->kdata, r, c->ktype, c->kattrs); + int64_t v = cdf_read(c->vdata, r, c->vtype, c->vattrs); + uint64_t hash = cdf_pair_hash(k, v); + if (c->dedup && cdf_repeat(recent, hash, k, v)) continue; + uint32_t part = hash & (c->n_parts - 1); + if (my[part].cap == UINT32_MAX) { atomic_store(&c->oom, 1); return; } + my[part].cap++; + } } atomic_fetch_add_explicit(&c->rows_done, limit - begin, memory_order_relaxed); } @@ -586,8 +598,8 @@ ray_t* ray_cd_fused(ray_t* key_col, ray_t* val_col, int64_t nrows) { /* Memory admission gate: peak footprint is ~CDF_BYTES_PER_ROW bytes/row * (see the constant's derivation above and the phase-3 KNOWN MEMORY * BOUND comment). Decline rather than risk the OOM killer when that - * estimate would exceed a quarter of the heap's anon watermark (default: - * total physical RAM) — leaving headroom for the rest of the query + * estimate would exceed a quarter of the heap's memory budget (default: + * physical RAM or the cgroup limit) — leaving headroom for the rest of the query * (source columns, other operators, concurrent work) sharing the same * budget. No new env knob: this rides the existing watermark, which * ray_heap_set_anon_watermark already lets tests/embedders override. @@ -596,7 +608,7 @@ ray_t* ray_cd_fused(ray_t* key_col, ray_t* val_col, int64_t nrows) { * tests calling ray_cd_fused directly, without the app's runtime/RAM * probe) sees ray_sys_total_ram() == 0, which must not read as a * zero-byte budget. */ - int64_t wm = ray_heap_anon_watermark(); + int64_t wm = ray_heap_mem_budget(); if (wm > 0 && (double)nrows * CDF_BYTES_PER_ROW > (double)wm / 4.0) return NULL; @@ -621,6 +633,13 @@ ray_t* ray_cd_fused(ray_t* key_col, ray_t* val_col, int64_t nrows) { .nrows = nrows, .oom = 0, .rows_done = 0, }; + if (nrows >= 1024) { + bool kc = ray_col_cold(key_col), vc = ray_col_cold(val_col); + for (int i = 0; (kc || vc) && i < 1024; i++) { + if (kc) ray_col_want_row(key_col, cdf_sample_row(nrows, i)); + if (vc) ray_col_want_row(val_col, cdf_sample_row(nrows, i)); + } + } p1.dedup = cdf_sample_repetition(&p1); if (p1.dedup) ray_profile_tick("count-distinct: source preaggregation"); ray_profile_tick("count-distinct: prepared"); @@ -756,3 +775,116 @@ ray_t* ray_cd_fused(ray_t* key_col, ray_t* val_col, int64_t nrows) { } return tbl; } + +/* The scatter path serves a distinct count beside the group by K: the + * post-group row→group map and a per-group dedup over the slices (the + * global-hash kernel past 50 K groups). Up to CD_SCATTER_MAX_GROUPS groups + * it is the route whenever the rewrite's (K, X) grouping would not be + * dense; past CD_SCATTER_MANY_GROUPS its map and kernel fall behind the + * rewrite's radix grouping whatever that grouping dedups; between the two + * the tuple count decides. */ +#define CD_SCATTER_MAX_GROUPS (256 * 1024) +#define CD_SCATTER_MANY_GROUPS (1024 * 1024) + +/* The scatter's per-group dedup is serial over a group: its critical path + * is the largest group's rows, where the rewrite's (K, X) pass spreads + * every row over the workers. The rewrite is the route once the largest + * group holds more than this many workers' shares of the rows: at 28 + * workers a key whose largest value held half the rows took 180 ms on the + * scatter against 136 on the rewrite, one holding 8% of them 107 against + * 138, uniform groups 89 against 140 (12 M rows surviving a filter over + * 100 M; the issue's 45 groups hold 2% each). */ +#define CD_SCATTER_SKEW 8 + +/* Whether the two-pass rewrite (group by (K, X), then count per K; query.c) + * beats grouping by K and counting distinct X over each group's slice — the + * path a `(count (distinct X))` takes beside other aggregates, and the one + * the planner falls back to when this returns false (#756). + * + * The rewrite wins when its (K, X) grouping is dense: the packed key space + * — the product of the keys' spans and X's — fits the row count, so the + * dedup is a direct-index pass. Past that it is a radix grouping that + * materializes and orders every (K, X) tuple — 1.8 GB and 3x the time of + * the slice dedup at 10 M rows with 45 groups of 3 M distinct values — + * unless the groups are so many that the scatter's own machinery is the + * slower one: at 2 M and 5 M groups the rewrite took 1.3x to 2x less time, + * at 750 K groups whose (K, X) tuples were as many as the rows the scatter + * took 1.3x less time and 1.9x less memory, and at 750 K groups whose + * tuples were a sixth of the rows the rewrite took 1.3x less time; below + * 256 K groups the scatter is the route (#756). Few groups do not favour + * the rewrite: at 2 to 9 groups of 3 M to 6 M values on 28 workers the + * slice dedup took the same time or less and 40% of the memory, and the + * issue's 45 groups on 46 workers would otherwise have taken the rewrite at + * 3x the time. A group holding many workers' shares of the rows takes + * the rewrite (CD_SCATTER_SKEW). The group, value and tuple counts and + * the largest group's rows are sampled estimates (agg_group_card_sample) + * over the `nrows` rows of `rows` when a `where:` selected them — a filter + * that drops a dominant value hides the groups and the shares of what + * remains — else over the table; half a millisecond at 10 M rows. A + * skewed or clustered key the sample cannot exhaust estimates high, + * towards the rewrite. */ +/* The sampled count of the groups is a lower bound for a key the sample + * reads mostly as singletons — six million search phrases over thirteen + * million rows, most on one row and a few on thousands, read as a few + * hundred thousand (the Chao1 takes the phrases seen twice for the whole + * tail's repeats). Before the slices are chosen on such a count, the key + * columns are counted approximately in full (ray_count_distinct_approx, + * parallel, a few milliseconds at 100 M rows): a column past the many-groups + * mark makes the tuple past it. Over the whole table, not the selection — + * an upper bound that errs towards the rewrite. */ +static bool cd_many_groups_in_full(ray_t** K_cols, int n_K) { + for (int j = 0; j < n_K; j++) { + ray_t* k = K_cols[j]; + /* the count reads the column whole, a chunk per thread: a mapped + * column not in memory is asked for ahead as one range, else each + * thread waits on its chunk's pages in turn */ + if (ray_pool_scan_on() && ray_col_cold(k)) + ray_pool_want(ray_data(k), (size_t)k->len * col_esz(k)); + ray_t* c = ray_count_distinct_approx(k); + if (!c) return false; + bool many = !RAY_IS_ERR(c) && c->type == -RAY_I64 && c->i64 > CD_SCATTER_MANY_GROUPS; + if (RAY_IS_ERR(c)) ray_error_free(c); else ray_release(c); + if (many) return true; + } + return false; +} + +bool ray_cd_two_pass_preferred(ray_t** K_cols, int n_K, ray_t* X_col, + const int64_t* rows, int64_t nrows, int64_t population, + int64_t workers) { + if (n_K < 1 || n_K > 15) return true; + const int64_t pop = population > nrows ? population : nrows; + int64_t k_est[15], k_card = 0, k_max = 0, x_est = 0, t_est = 0; + if (!agg_group_card_sample(K_cols, (uint32_t)n_K, (uint32_t)n_K, rows, nrows, population, + k_est, &k_card, &k_max, NULL)) + return true; /* K unbounded (a key the estimate does not cover) */ + if (!agg_group_card_sample(&X_col, 1, 1, rows, nrows, population, &x_est, NULL, NULL, NULL)) + return false; /* X unbounded: (K, X) is radix; the slices dedup */ + const int64_t nrows_list = nrows; + nrows = pop; /* the rows the estimates describe */ + /* the packed (K, X) key space: the keys' spans times X's */ + int64_t k_span = 1; + for (int j = 0; j < n_K; j++) { + if (k_span > nrows / k_est[j]) { k_span = nrows + 1; break; } + k_span *= k_est[j]; + } + if (k_span <= nrows / x_est) return true; /* dense: a direct-index dedup */ + /* a dominant group: the scatter would dedup it on one worker */ + if (workers > 1 && k_max > nrows / workers * CD_SCATTER_SKEW) return true; + if (k_card > CD_SCATTER_MANY_GROUPS) return true; + /* the slices on a count the sample cannot vouch for (more sampled + * singletons than the Chao1's repeats explain: any count past the + * sample's size): a full approximate count may say many groups */ + if (k_card > AGG_EST_SAMPLE_ROWS && cd_many_groups_in_full(K_cols, n_K)) return true; + if (k_card <= CD_SCATTER_MAX_GROUPS) return false; + /* a radix (K, X) pass over 256 K to 1 M groups: the rewrite wins when + * that pass dedups, the scatter when the tuples are nearly the rows */ + ray_t* cols[16]; + for (int j = 0; j < n_K; j++) cols[j] = K_cols[j]; + cols[n_K] = X_col; + if (!agg_group_card_sample(cols, (uint32_t)n_K + 1, (uint32_t)n_K, rows, + population > 0 ? nrows_list : nrows, population, + NULL, NULL, NULL, &t_est)) + return true; + return t_est < nrows - nrows / 4; +} diff --git a/src/ops/cdfuse.h b/src/ops/cdfuse.h index 5cc5f6782..b6bf83440 100644 --- a/src/ops/cdfuse.h +++ b/src/ops/cdfuse.h @@ -44,4 +44,23 @@ * canonical bit encodings; callers restore the source logical type. */ ray_t* ray_cd_fused(ray_t* key_col, ray_t* val_col, int64_t nrows); +/* The route for a `(count (distinct X))` grouped by K_cols[0..n_K) over + * the nrows rows of `rows` (a selection's survivors, sampled from + * `population` rows when that is above nrows; NULL for all rows 0..nrows) + * on `workers` workers (#756): true for the two-pass rewrite — + * group by (K, X), then count per K — false for grouping by K and counting + * distinct X over each group's slice. Decided from sampled cardinality + * estimates (agg_group_card_sample): the rewrite where its (K, X) grouping + * is dense, where the largest group holds more than CD_SCATTER_SKEW + * workers' shares of the rows (the slice dedup is serial over a group), + * past a million groups, and between 256 K and a million groups when the + * (K, X) tuples dedup below three quarters of the rows; the slices + * otherwise. A sampled group count the slices would rely on is confirmed + * by an approximate distinct count over the whole key column (a key the + * sample reads as singletons may hold far more values than the Chao1 + * says): past a million there, the rewrite. */ +bool ray_cd_two_pass_preferred(ray_t** K_cols, int n_K, ray_t* X_col, + const int64_t* rows, int64_t nrows, int64_t population, + int64_t workers); + #endif /* RAY_OPS_CDFUSE_H */ diff --git a/src/ops/collection.c b/src/ops/collection.c index d06186240..c6fa46eff 100644 --- a/src/ops/collection.c +++ b/src/ops/collection.c @@ -24,6 +24,7 @@ /* Collection / higher-order builtins — extracted from eval.c */ #include "lang/internal.h" +#include "lang/env.h" #include "core/types.h" #include "core/pool.h" #include "ops/hash.h" @@ -51,6 +52,7 @@ * ══════════════════════════════════════════ */ #define HS_EMPTY ((int64_t)-1) +#define HS_NULL_CLASSES 32 typedef struct hashset_t { int64_t* slots; /* cap entries; -1 = empty, else row index */ @@ -58,8 +60,11 @@ typedef struct hashset_t { int64_t cap; /* power of 2 */ int64_t mask; /* cap - 1 */ int64_t count; /* live entries (excl. null bucket) */ - int null_seen; /* 1 if any null has been recorded */ - int64_t null_idx; /* row index of first null encountered */ + /* First null row of each null class (hs_null_class): nulls equal one + * another only within a class, as atom_eq has it. */ + int n_null; + int8_t null_cls[HS_NULL_CLASSES]; + int64_t null_at[HS_NULL_CLASSES]; /* Cached typed-vec data pointers to avoid re-derefs in hot loops. */ ray_t* src; /* source vec or list */ int8_t src_type; /* ray_t.type */ @@ -242,6 +247,15 @@ static inline int hs_row_is_null(ray_t* src, int64_t i, void* data) { return ray_vec_may_have_nulls(src) && ray_vec_is_null(src, i); } +/* The class of a null row: two nulls are equal when two values of their + * types can be — the same type, or both numeric (atom_eq). A LIST cell + * carries its own type; a missing cell is the untyped null. */ +static int8_t hs_null_class(ray_t* src, int64_t i, void* data) { + if (src->type != RAY_LIST) return ray_null_class(src->type); + ray_t* e = ((ray_t**)data)[i]; + return e ? ray_null_class(e->type) : RAY_NULL; +} + static bool hashset_init(hashset_t* hs, ray_t* src, int64_t hint) { int64_t cap = 16; /* Cap target: 2× hint to keep load factor under 0.5. */ @@ -253,8 +267,7 @@ static bool hashset_init(hashset_t* hs, ray_t* src, int64_t hint) { hs->cap = cap; hs->mask = cap - 1; hs->count = 0; - hs->null_seen = 0; - hs->null_idx = HS_EMPTY; + hs->n_null = 0; hs->src = src; hs->src_type = src ? src->type : 0; hs->src_has_nulls = src ? ray_vec_may_have_nulls(src) : false; @@ -342,8 +355,12 @@ hashset_scan(hashset_t* hs, ray_t* probe_src, int64_t probe_i, static int64_t hashset_find_xrow(hashset_t* hs, ray_t* probe_src, int64_t probe_i, int8_t probe_type, void* probe_data) { - if (hs_row_is_null(probe_src, probe_i, probe_data)) - return hs->null_seen ? hs->null_idx : HS_EMPTY; + if (hs_row_is_null(probe_src, probe_i, probe_data)) { + int8_t c = hs_null_class(probe_src, probe_i, probe_data); + for (int k = 0; k < hs->n_null; k++) + if (hs->null_cls[k] == c) return hs->null_at[k]; + return HS_EMPTY; + } /* sym-domain Phase 2: SYM-vec vs SYM-vec probes across DIFFERENT * domains cannot compare (or hash) raw ids. Re-express the probe * cell in the build side's domain once, then run the standard raw @@ -458,9 +475,12 @@ static void distinct_sort_indices(ray_t* src, int64_t* idx, int64_t count) { * the set silently keeps the previous capacity (caller proceeds). */ static bool hashset_insert(hashset_t* hs, int64_t i) { if (hs_row_is_null(hs->src, i, hs->src_data)) { - if (hs->null_seen) return false; - hs->null_seen = 1; - hs->null_idx = i; + int8_t c = hs_null_class(hs->src, i, hs->src_data); + for (int k = 0; k < hs->n_null; k++) + if (hs->null_cls[k] == c) return false; + if (hs->n_null == HS_NULL_CLASSES) return false; /* cannot happen */ + hs->null_cls[hs->n_null] = c; + hs->null_at[hs->n_null++] = i; return true; } if (hs->count * 2 >= hs->cap) { @@ -1056,7 +1076,12 @@ ray_t* ray_apply_fn(ray_t** args, int64_t n) { int atom_eq(ray_t* a, ray_t* b) { int a_null = RAY_ATOM_IS_NULL(a); int b_null = RAY_ATOM_IS_NULL(b); - if (a_null && b_null) return 1; + /* Two nulls are equal where two values of their types can be: the same + * type, or both numeric. A symbol null, the empty string and an integer + * null are different values, as 'a, "a" and 1 are — treating every null + * as one collapsed (distinct (list ' "" 0Nl)) to a single cell. */ + if (a_null && b_null) + return ray_null_class(a->type) == ray_null_class(b->type); if (a_null || b_null) return 0; if (a->type != b->type) { if (is_numeric(a) && is_numeric(b)) @@ -1368,6 +1393,23 @@ ray_t* ray_distinct_fn(ray_t* x) { } /* (in val vec) — check membership */ +/* One element of a collection left operand. A string element is one whole + * value: the lone-string arms of ray_in_fn answer per character, which is + * right for a string atom on its own but not for a row of a collection — + * (in ["p" "qq"] (list "qq" "zz")) answered [[false] [false false]]. A + * string set (vector) already compares whole strings in ray_in_fn. */ +static ray_t* in_row(ray_t* elem, ray_t* vec) { + if (elem->type == -RAY_STR && ray_is_atom(vec)) + return make_bool(atom_eq(elem, vec) ? 1 : 0); + if (elem->type == -RAY_STR && vec->type == RAY_LIST) { + ray_t** set = (ray_t**)ray_data(vec); + for (int64_t j = 0; j < ray_len(vec); j++) + if (atom_eq(elem, set[j])) return make_bool(1); + return make_bool(0); + } + return ray_in_fn(elem, vec); +} + ray_t* ray_in_fn(ray_t* val, ray_t* vec) { if (ray_is_lazy(val)) val = ray_lazy_materialize(val); if (ray_is_lazy(vec)) vec = ray_lazy_materialize(vec); @@ -1395,6 +1437,11 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { if (flat_vec) ray_release(flat_vec); return r; } + /* A string column's cell, bound for one row of a query, is one value: + * the per-character arms below are for a lone string literal. */ + if (val->type == -RAY_STR && (val->attrs & RAY_ATTR_STR_CELL) && + (ray_is_atom(vec) || vec->type == RAY_LIST)) + return in_row(val, vec); /* STR in STR: for each char of val, check membership in vec string */ if (ray_is_atom(val) && (-val->type) == RAY_STR && ray_is_atom(vec) && (-vec->type) == RAY_STR) { const char* vp = ray_str_ptr(val); @@ -1440,8 +1487,31 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { if (is_collection(val) && !ray_is_atom(val)) { int64_t vlen = ray_len(val); if (vlen == 0) { - /* Empty collection → return empty list */ - return ray_list_new(0); + /* No needles: an empty B8, the shape every other left operand + * answers — `where` over it must not raise (#785). */ + return ray_vec_new(RAY_BOOL, 0); + } + /* A string vector against a string atom or a list: its rows can only + * equal the set's string elements, so the set is the string vector + * of those and the hash-set path below answers — one probe per row + * instead of a boxed cell and a scan of the set per row. */ + if (val->type == RAY_STR && (vec->type == -RAY_STR || vec->type == RAY_LIST)) { + ray_t* sv; + if (vec->type == -RAY_STR) { + sv = ray_vec_new(RAY_STR, 1); + if (sv && !RAY_IS_ERR(sv)) + sv = ray_str_vec_append(sv, ray_str_ptr(vec), ray_str_len(vec)); + } else { + ray_t** el = (ray_t**)ray_data(vec); + sv = ray_vec_new(RAY_STR, ray_len(vec)); + for (int64_t j = 0; j < ray_len(vec) && sv && !RAY_IS_ERR(sv); j++) + if (el[j] && el[j]->type == -RAY_STR) + sv = ray_str_vec_append(sv, ray_str_ptr(el[j]), ray_str_len(el[j])); + } + if (!sv || RAY_IS_ERR(sv)) return sv ? sv : ray_error("oom", NULL); + ray_t* r = ray_in_fn(val, sv); + ray_release(sv); + return r; } /* Hash-based fast path: both sides are typed vecs of compatible * shape and the result is a row-aligned bool vec. Build a @@ -1531,52 +1601,53 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { hashset_destroy(&hs); return result; } - /* Probe first element to check if result is scalar or vector */ - int alloc0 = 0; - ray_t* e0 = collection_elem(val, 0, &alloc0); - if (RAY_IS_ERR(e0)) return e0; - ray_t* r0 = ray_in_fn(e0, vec); - if (alloc0) ray_release(e0); - if (RAY_IS_ERR(r0)) return r0; - if (ray_is_atom(r0) && r0->type == -RAY_BOOL) { - /* All results are scalar bools — use typed bool vector */ - ray_t* result = ray_vec_new(RAY_BOOL, vlen); - if (RAY_IS_ERR(result)) { ray_release(r0); return result; } - result->len = vlen; - bool* out = (bool*)ray_data(result); - out[0] = r0->b8; - ray_release(r0); - for (int64_t i = 1; i < vlen; i++) { - int alloc = 0; - ray_t* elem = collection_elem(val, i, &alloc); - if (RAY_IS_ERR(elem)) { ray_release(result); return elem; } - ray_t* r = ray_in_fn(elem, vec); - if (alloc) ray_release(elem); - if (RAY_IS_ERR(r)) { ray_release(result); return r; } - out[i] = r->b8; + /* One verdict per element: a bool vector while every answer is a + * bool, a list from the first answer that is not (a nested element + * answers a vector). The verdicts so far are boxed into the list + * and collection carries on there. */ + ray_t* result = ray_vec_new(RAY_BOOL, vlen); + if (!result || RAY_IS_ERR(result)) return result ? result : ray_error("oom", NULL); + result->len = vlen; + int64_t i = 0; + for (; i < vlen; i++) { + int alloc = 0; + ray_t* elem = collection_elem(val, i, &alloc); + if (RAY_IS_ERR(elem)) { ray_release(result); return elem; } + ray_t* r = in_row(elem, vec); + if (alloc) ray_release(elem); + if (RAY_IS_ERR(r)) { ray_release(result); return r; } + if (!(ray_is_atom(r) && r->type == -RAY_BOOL)) { + bool* out = (bool*)ray_data(result); + ray_t* lst = ray_list_new(vlen); + for (int64_t k = 0; k < i && lst && !RAY_IS_ERR(lst); k++) { + ray_t* b = make_bool(out[k]); + lst = ray_list_append(lst, b); + ray_release(b); + } + ray_release(result); + if (lst && !RAY_IS_ERR(lst)) lst = ray_list_append(lst, r); ray_release(r); + if (!lst || RAY_IS_ERR(lst)) return lst ? lst : ray_error("oom", NULL); + result = lst; + i++; + break; } - return result; - } else { - /* Results are non-scalar — collect as list */ - ray_t* result = ray_list_new(vlen); - if (RAY_IS_ERR(result)) { ray_release(r0); return result; } - result = ray_list_append(result, r0); - ray_release(r0); + ((bool*)ray_data(result))[i] = r->b8; + ray_release(r); + } + if (result->type == RAY_BOOL) return result; + for (; i < vlen; i++) { + int alloc = 0; + ray_t* elem = collection_elem(val, i, &alloc); + if (RAY_IS_ERR(elem)) { ray_release(result); return elem; } + ray_t* r = in_row(elem, vec); + if (alloc) ray_release(elem); + if (RAY_IS_ERR(r)) { ray_release(result); return r; } + result = ray_list_append(result, r); + ray_release(r); if (RAY_IS_ERR(result)) return result; - for (int64_t i = 1; i < vlen; i++) { - int alloc = 0; - ray_t* elem = collection_elem(val, i, &alloc); - if (RAY_IS_ERR(elem)) { ray_release(result); return elem; } - ray_t* r = ray_in_fn(elem, vec); - if (alloc) ray_release(elem); - if (RAY_IS_ERR(r)) { ray_release(result); return r; } - result = ray_list_append(result, r); - ray_release(r); - if (RAY_IS_ERR(result)) return result; - } - return result; } + return result; } /* Typed vector: search without boxing */ if (ray_is_vec(vec) && ray_is_atom(val)) { @@ -1585,10 +1656,10 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { bool val_null = RAY_ATOM_IS_NULL(val); if (has_nulls) { for (int64_t i = 0; i < len; i++) { - if (ray_vec_is_null(vec, i)) { - if (val_null) return make_bool(1); - continue; - } + /* Only a null row can match a null needle, and only a null + * of its class (atom_eq): the untyped null or a symbol null + * is not 0Nl. A non-null needle skips the null rows. */ + if (ray_vec_is_null(vec, i) != val_null) continue; int alloc = 0; ray_t* elem = collection_elem(vec, i, &alloc); int eq = atom_eq(val, elem); @@ -1620,6 +1691,88 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { return make_bool(0); } +/* Interpreter membership inside queries follows the plan's null-row rule. + * Keep ray_in_fn itself context-free: collection operations and the GUID + * plan fallback call it directly and apply their own semantics. */ +static ray_t* membership_not(ray_t* r) { + if (r->type != RAY_LIST) return ray_not_fn(r); + ray_t* out = ray_list_new(r->len); + if (!out || RAY_IS_ERR(out)) return out; + for (int64_t i = 0; i < r->len; i++) { + ray_t* item = membership_not(((ray_t**)ray_data(r))[i]); + if (!item || RAY_IS_ERR(item)) { ray_release(out); return item; } + out = ray_list_append(out, item); + ray_release(item); + if (!out || RAY_IS_ERR(out)) return out; + } + return out; +} + +static ray_t* eval_membership(ray_t* val, ray_t* vec, bool negate) { + bool query = ray_env_query_scope_above(0); + if (query && (RAY_IS_PARTED(val->type) || val->type == RAY_MAPCOMMON)) { + ray_t* flat = val->type == RAY_MAPCOMMON ? materialize_mapcommon(val) + : parted_to_flat_vec(val); + if (!flat || RAY_IS_ERR(flat)) return flat ? flat : ray_error("oom", NULL); + ray_t* r = eval_membership(flat, vec, negate); + ray_release(flat); + return r; + } + if (query && (RAY_IS_PARTED(vec->type) || vec->type == RAY_MAPCOMMON)) { + ray_t* flat = vec->type == RAY_MAPCOMMON ? materialize_mapcommon(vec) + : parted_to_flat_vec(vec); + if (!flat || RAY_IS_ERR(flat)) return flat ? flat : ray_error("oom", NULL); + ray_t* r = eval_membership(val, flat, negate); + ray_release(flat); + return r; + } + /* The typed kernel already excludes null rows and parallelizes both + * membership and negation. LIST probes need the general comparator. */ + if (query && ray_is_vec(val) && (ray_is_vec(vec) || ray_is_atom(vec))) { + ray_t* fast = ray_in_vec_exec(val, vec, negate); + if (fast) return fast; + } + if (query && !ray_is_atom(val) && ray_len(val) == 0) + return ray_vec_new(RAY_BOOL, 0); + ray_t* r = ray_in_fn(val, vec); + if (!r || RAY_IS_ERR(r)) return r; + if (query && ray_is_atom(val) && RAY_ATOM_IS_NULL(val)) { + ray_release(r); + return make_bool(0); + } + if (r->type == RAY_BOOL) { + uint8_t* out = (uint8_t*)ray_data(r); + for (int64_t i = 0; i < r->len; i++) { + if (negate) out[i] = (uint8_t)!out[i]; + if (query && !ray_is_atom(val)) { + static const uint8_t zero_guid[16] = {0}; + bool is_null = val->type == RAY_GUID + ? memcmp((const uint8_t*)ray_data(val) + i * 16, zero_guid, 16) == 0 + : val->type == RAY_LIST + ? RAY_ATOM_IS_NULL(((ray_t**)ray_data(val))[i]) + : ray_vec_is_null(val, i); + if (is_null) out[i] = 0; + } + } + return r; + } + if (negate) { + ray_t* out = membership_not(r); + ray_release(r); + return out; + } + return r; +} + +ray_t* ray_in_eval_fn(ray_t* val, ray_t* vec) { + if (!ray_env_query_scope_above(0)) return ray_in_fn(val, vec); + return eval_membership(val, vec, false); +} + +ray_t* ray_not_in_fn(ray_t* val, ray_t* vec) { + return eval_membership(val, vec, true); +} + /* Helper: convert a boxed list result back to a typed vector if the original was typed */ ray_t* list_to_typed_vec(ray_t* list, int8_t orig_vec_type) { if (!list || RAY_IS_ERR(list) || list->type != RAY_LIST) return list; @@ -2761,11 +2914,9 @@ ray_t* ray_find_fn(ray_t* vec, ray_t* val) { if (has_nulls) { for (int64_t i = 0; i < len; i++) { - if (ray_vec_is_null(vec, i)) { - if (val_null) return make_i64(i); - continue; - } - if (val_null) continue; + /* A null row matches only a null of its class (atom_eq), + * as in `in`: 0Nl is not found among dates. */ + if (ray_vec_is_null(vec, i) != val_null) continue; int alloc = 0; ray_t* elem = collection_elem(vec, i, &alloc); int eq = atom_eq(elem, val); diff --git a/src/ops/exec.c b/src/ops/exec.c index bb3c5fefe..d4f354709 100644 --- a/src/ops/exec.c +++ b/src/ops/exec.c @@ -637,7 +637,8 @@ typedef struct { uint8_t* ob; /* output base; element i writes ob[i - ob_base] */ int64_t ob_base; /* 0 for full-vec output; morsel start for fused-sel */ int8_t ct; - /* SYM columns: per-domain-position membership verdict (1 = in set), + /* SYM columns: per-domain-position membership verdict (1 = in set; + * null slot preadjusted so XOR with negate always yields 0), * built once over the VOCABULARY in in_build_worker_ctx. Turns the * per-row linear set scan into one byte load — any set size, width- * specialized, vectorizable. NULL when not applicable. */ @@ -1120,6 +1121,9 @@ static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, memset(lut, 0, (size_t)d); for (int64_t j = 0; j < sv_len; j++) if (svi[j] >= 0 && svi[j] < d) lut[svi[j]] = 1; + /* Null rows fail both in and not-in. The worker XORs every + * entry with negate, so preadjust ID 0 to keep it false. */ + lut[0] = (uint8_t)negate; *lut_hdr_out = lh; symlut = lut; } @@ -1227,12 +1231,13 @@ ray_t* ray_in_vec_exec(ray_t* col, ray_t* set, bool negate) { static ray_t* flatten_parted_col(ray_t* col); -/* GUID membership fallback: the typed `in` kernel bails on guid operands - * (16-byte cells it can't compare), so route them through the general - * ray_in_fn path, which builds a guid-aware hashset. `col` is a materialized - * column vector, so ray_in_fn returns a fresh RAY_BOOL vector we own and may - * invert in place for not-in. */ -static ray_t* exec_in_guid_fallback(ray_t* col, ray_t* set, bool negate) { +/* General membership fallback: the typed `in` kernel bails on guid operands + * (16-byte cells it can't compare) and on string columns (variable-length + * cells), so route them through the general ray_in_fn path, which builds a + * guid- and string-aware hashset. `col` is a materialized column vector, so + * ray_in_fn returns a fresh RAY_BOOL vector we own and may invert in place + * for not-in. */ +static ray_t* exec_in_general_fallback(ray_t* col, ray_t* set, bool negate) { ray_t* input = col; bool owns_input = false; if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) { @@ -1261,7 +1266,17 @@ static ray_t* exec_in_guid_fallback(ray_t* col, ray_t* set, bool negate) { r = out; } - if (r->type == RAY_BOOL) { + /* The caller indexes the answer as one bool per row; anything else is + * not a membership verdict for this column. */ + if (r->type != RAY_BOOL || r->len != (ray_is_atom(col) ? 1 : ray_len(input))) { + int8_t rt = r->type; + ray_release(r); + if (owns_input) ray_release(input); + return ray_error("type", "in: membership of a %s column answered %s, not a bool per row", + ray_type_name(ray_is_atom(col) ? (int8_t)-col->type : input->type), + ray_type_name(rt)); + } + { uint8_t* b = (uint8_t*)ray_data(r); if (negate) for (int64_t i = 0; i < r->len; i++) b[i] = (uint8_t)!b[i]; @@ -1277,7 +1292,7 @@ static ray_t* exec_in_guid_fallback(ray_t* col, ray_t* set, bool negate) { const uint8_t* data = (const uint8_t*)ray_data(input); for (int64_t i = 0; i < r->len; i++) if (memcmp(data + i * 16, null_guid, 16) == 0) b[i] = 0; - } else if (ray_vec_may_have_nulls(col)) { + } else if (ray_vec_may_have_nulls(input)) { for (int64_t i = 0; i < r->len; i++) if (ray_vec_is_null(input, i)) b[i] = 0; } @@ -1286,13 +1301,26 @@ static ray_t* exec_in_guid_fallback(ray_t* col, ray_t* set, bool negate) { return r; } -/* True when either operand is a guid column/atom (parted base included). */ -static bool in_is_guid(ray_t* col, ray_t* set) { +/* True when the typed kernel's refusal is a shape the general path answers: + * a guid on either side, or a string on either side (parted base included) + * — a string column, or any column against a string set, which matches no + * row of another type exactly as the bare `in` does. A string ATOM subject + * has one verdict only against a column of cells; against a lone string or + * a list, ray_in_fn answers it per character, which is not a row verdict, + * so those shapes stay out. */ +static bool in_has_general_fallback(ray_t* col, ray_t* set) { int8_t ct = ray_is_atom(col) ? (int8_t)(-col->type) : col->type; int8_t st = ray_is_atom(set) ? (int8_t)(-set->type) : set->type; if (RAY_IS_PARTED(ct)) ct = (int8_t)RAY_PARTED_BASETYPE(ct); if (RAY_IS_PARTED(st)) st = (int8_t)RAY_PARTED_BASETYPE(st); - return ct == RAY_GUID || st == RAY_GUID; + if (ct == RAY_GUID || st == RAY_GUID) return true; + if (ct != RAY_STR && st != RAY_STR) return false; + /* Only a column of cells answers one verdict per row: a LIST column's + * cell may be a vector, and its answer a list no mask can use. */ + if (!ray_is_atom(col) && !(ct >= RAY_BOOL && ct <= RAY_STR)) return false; + if (ct == RAY_STR && ray_is_atom(col)) + return !ray_is_atom(set) && st != RAY_LIST; + return true; } static ray_t* exec_in(ray_graph_t* g, ray_op_t* op, ray_t* col, ray_t* set) { @@ -1324,8 +1352,8 @@ static ray_t* exec_in(ray_graph_t* g, ray_op_t* op, ray_t* col, ray_t* set) { svf_stack, svi_stack, &in_ctx, &sv_hdr, &lut_hdr); if (st == IN_CTX_UNSUPPORTED) { - if (in_is_guid(col, set)) - return exec_in_guid_fallback(col, set, negate); + if (in_has_general_fallback(col, set)) + return exec_in_general_fallback(col, set, negate); return ray_error("nyi", "OP_IN on RAY_STR not yet implemented"); } if (st == IN_CTX_OOM) @@ -1633,11 +1661,14 @@ static inline bool group_has_keys(ray_graph_t* g, ray_op_t* group_op) { /* 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) { +static bool op_tree_leaves(ray_graph_t* g, uint32_t id, bool reduced, bool atoms_only, 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_CONST: { + ray_op_ext_t* x = find_ext(g, id); + return !atoms_only || (x && x->literal && ray_is_atom(x->literal)); + } case OP_SCAN: return false; case OP_SUM: case OP_PROD: case OP_ALL: case OP_ANY: case OP_MIN: case OP_MAX: @@ -1649,10 +1680,17 @@ static bool op_tree_leaves(ray_graph_t* g, uint32_t id, bool reduced, int depth) } 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 (!op_tree_leaves(g, n->in_id[i], reduced, atoms_only, 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; + if (!x || !op_tree_leaves(g, x->third_in, reduced, atoms_only, depth + 1)) return false; + } + if (n->opcode == OP_CONCAT) { + ray_op_ext_t* x = find_ext(g, id); + if (!x) return false; + uint32_t* extra = (uint32_t*)(x + 1); + for (int64_t i = 2; i < x->sym; i++) + if (!op_tree_leaves(g, extra[i - 2], reduced, atoms_only, depth + 1)) return false; } return true; } @@ -1661,14 +1699,19 @@ static bool op_tree_leaves(ray_graph_t* g, uint32_t id, bool reduced, int depth) * 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); +bool op_tree_is_scalar(ray_graph_t* g, uint32_t id) { + return op_tree_leaves(g, id, true, false, 0); +} + +/* As above, but vector constants do not count as scalar atoms. */ +bool op_tree_is_atom(ray_graph_t* g, uint32_t id) { + return op_tree_leaves(g, id, true, 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); + return op_tree_leaves(g, id, false, false, 0); } /* Execute a pushed-down filter interposed as a GROUP's inputs[0] @@ -2104,6 +2147,9 @@ void ray_exec_memo_pop(ray_graph_t* g, const ray_exec_memo_save_t* save) { g->memo_hdr = save->hdr; g->memo_table = save->table; } +/* Row filters being executed on this thread, the outermost first. */ +static RAY_TLS int tl_filter_depth; + ray_t* exec_node(ray_graph_t* g, ray_op_t* op) { if (!op) return ray_error("nyi", NULL); @@ -2155,8 +2201,21 @@ ray_t* exec_node(ray_graph_t* g, ray_op_t* op) { } } + /* A row filter (not a HAVING over a group); an `and` runs as a chain of + * them, each executing the next one in as its input. */ + bool row_filter = false; + if (op->opcode == OP_FILTER) { + ray_op_t* fc = op_child(g, op, 0); + row_filter = !fc || fc->opcode != OP_GROUP; + } + if (row_filter) tl_filter_depth++; ray_t* _prof_result = exec_node_inner(g, op); tl_exec_depth--; + /* The outermost filter of a chain has the final selection: the + * select's columns held back for it can be requested now. */ + if (row_filter && --tl_filter_depth == 0 && _prof_result && !RAY_IS_ERR(_prof_result)) + ray_select_scan_filtered(g->selection, + _prof_result->type == RAY_TABLE ? ray_table_nrows(_prof_result) : 0); /* First consumer of a shared node: keep a ref for the others (a lazy * value is not kept — materialising it is the consumer's business). */ @@ -2689,7 +2748,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { if (dom_id < 0) absent = true; else probe = dom_id; } - const int64_t* grows = NULL; + ray_idx_rows_t grows = { NULL, false }; int64_t gn = 0; int hit = absent ? 0 : ray_index_hash_group(eq_col, probe, &grows, &gn); @@ -2709,7 +2768,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { bool mono = true; int64_t prevv = INT64_MIN; for (int64_t pp = 0; pp < gn; pp++) { - int64_t v = read_col_i64(rgd, grows[pp], rt, ra); + int64_t v = read_col_i64(rgd, ray_idx_rows_at(grows, pp), rt, ra); if (v < prevv) { mono = false; break; } prevv = v; } @@ -2717,19 +2776,19 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int64_t a = 0, b = gn; /* first pos >= lo */ while (a < b) { int64_t m = a + (b - a) / 2; - if (read_col_i64(rgd, grows[m], rt, ra) < lo) a = m + 1; + if (read_col_i64(rgd, ray_idx_rows_at(grows, m), rt, ra) < lo) a = m + 1; else b = m; } int64_t startp = a; b = gn; /* first pos > hi */ while (a < b) { int64_t m = a + (b - a) / 2; - if (read_col_i64(rgd, grows[m], rt, ra) <= hi) a = m + 1; + if (read_col_i64(rgd, ray_idx_rows_at(grows, m), rt, ra) <= hi) a = m + 1; else b = m; } int64_t nrows = ray_table_nrows(input); - ray_t* sel = ray_index_rowsel_from_ids( - nrows, grows + startp, a - startp); + ray_t* sel = ray_index_rowsel_from_rows( + nrows, ray_idx_rows_from(grows, startp), a - startp); if (sel) { ray_idx_hits[IDX_SITE_FILTER_EQRANGE]++; g->selection = sel; @@ -3185,9 +3244,11 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_op_ext_t* ext = find_ext(g, op->id); int64_t n = ext ? ext->sym : 10; - /* Fused sort+limit: detect SORT child → only gather N rows */ + /* Fused sort+limit: detect SORT child → only gather N rows. Not + * for N = 0: exec_sort reads a 0 limit as none (every row); the + * plain HEAD below trims the sort to no rows. */ ray_op_t* child_op = op_child(g, op, 0); - if (child_op && child_op->opcode == OP_SORT) { + if (child_op && child_op->opcode == OP_SORT && n > 0) { ray_t* sort_input = exec_node(g, op_child(g, child_op, 0)); if (!sort_input || RAY_IS_ERR(sort_input)) return sort_input; ray_t* tbl = (sort_input->type == RAY_TABLE) ? sort_input : g->table; @@ -3725,6 +3786,19 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int64_t nr_in = ray_table_nrows(input); if (result && !RAY_IS_ERR(result)) { int64_t rc = ray_table_ncols(result); + /* A collection projection may change the row count. Use + * its length for scalar broadcasting; unequal non-scalar + * lengths are rejected below, independently of column order. */ + int64_t broadcast_len = nr_in; + bool has_collection = false; + for (int64_t c = 0; c < rc; c++) { + ray_t* cv = ray_table_get_col_idx(result, c); + if (!cv || cv->type < 0) continue; + int64_t len = ray_parted_nrows(cv); + if (len == 1) continue; + if (!has_collection) broadcast_len = len; + has_collection = true; + } bool has_full = false; if (nr_in != 1) { for (int64_t c = 0; c < rc; c++) { @@ -3748,6 +3822,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { if (!op_tree_is_const(g, columns[c])) all_const = false; has_full = all_const; } + if (has_collection) has_full = true; /* 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 @@ -3758,11 +3833,14 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { 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++) { + for (int64_t c = 0; broadcast_len != 1 && has_full && c < rc; c++) { ray_t* cv = ray_table_get_col_idx(result, c); if (!cv || cv->type < 0 || RAY_IS_PARTED(cv->type) || cv->type == RAY_MAPCOMMON || cv->len != 1) continue; - ray_t* n_obj = make_i64(nr_in); + /* One input row does not turn a row-aligned expression + * into a scalar. Only constants/reductions may expand. */ + if (nr_in == 1 && !op_tree_is_scalar(g, columns[c])) continue; + ray_t* n_obj = make_i64(broadcast_len); ray_t* wide = n_obj ? ray_take_fn(cv, n_obj) : ray_error("oom", NULL); if (n_obj) ray_release(n_obj); if (!wide || RAY_IS_ERR(wide)) { @@ -3774,6 +3852,24 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_table_set_col_idx(result, c, wide); ray_release(wide); } + /* Length-changing constant projections must not silently + * truncate or pad the other columns during materialization. */ + ray_t* shape_err = ray_table_validate_rectangular(result, "select"); + if (shape_err) { + ray_release(result); + g->table = saved_table; + ray_release(input); + return shape_err; + } + if (g->selection && ray_table_nrows(result) != nr_in) { + ray_t* err = ray_error("length", + "select: collection projection has %lld rows; where requires %lld input-aligned rows", + (long long)ray_table_nrows(result), (long long)nr_in); + ray_release(result); + g->table = saved_table; + ray_release(input); + return err; + } } g->table = saved_table; @@ -4196,7 +4292,8 @@ static bool dag_can_stream(ray_graph_t* g, ray_op_t* root) { return ok && has_default_scan; } -static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root); +static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root, bool reset_cancel); +static _Thread_local int exec_depth; /* nesting of ray_execute on this thread */ /* Validate compiler-marked missing scans before execution. Optimizer rewrites * may replace a root or eliminate such a scan from the live DAG (for example @@ -4222,6 +4319,57 @@ static ray_t* validate_scan_columns(ray_graph_t* g) { return NULL; } +void exec_scan_init(ray_pool_scan_t* s) { + s->n = 0; + s->rows = -1; + s->gate = NULL; + s->gate_log2 = 0; +} + +void exec_scan_add_col(ray_pool_scan_t* s, ray_t* col) { + if (!col || col->mmod != 1 || col->type <= 0 || RAY_IS_PARTED(col->type) || + col->type == RAY_MAPCOMMON || col->type == RAY_LIST || col->type == RAY_STR) return; + if (col->len <= 0 || (s->rows >= 0 && col->len != s->rows)) return; + size_t esz = ray_sym_elem_size(col->type, col->attrs); + if (esz == 0) return; + s->rows = col->len; + const uint8_t* base = (const uint8_t*)ray_data(col); + for (uint32_t k = 0; k < s->n; k++) if (s->base[k] == base) return; + size_t bytes = (size_t)col->len * esz; + if (s->n >= RAY_POOL_SCAN_MAX || ray_vm_resident(base, bytes)) return; + /* The pages at its start that are resident already, up to 4 MiB: read + * ahead with the header when the column was opened (see warm). They + * run on from the first, so halving finds where they end. */ + size_t lo = 0, hi = (bytes < ((size_t)4 << 20) ? bytes : ((size_t)4 << 20)) / 4096; + while (lo < hi) { + size_t mid = lo + (hi - lo) / 2; + if (ray_vm_resident(base + mid * 4096, 1)) lo = mid + 1; else hi = mid; + } + s->base[s->n] = base; + s->esz[s->n] = (uint32_t)esz; + s->warm[s->n] = (int64_t)(lo * 4096 / esz); + s->n++; +} + +/* The graph's scanned columns, when they are mapped (see exec_scan_add_col); + * NULL when no scan reads a mapped column. */ +static const ray_pool_scan_t* exec_scan_columns(ray_graph_t* g, ray_pool_scan_t* s) { + exec_scan_init(s); + for (uint32_t i = 0; i < g->node_count; i++) { + ray_op_t* op = &g->nodes[i]; + if (op->opcode != OP_SCAN) continue; + ray_op_ext_t* ext = find_ext(g, op->id); + if (!ext) continue; + uint16_t tid = 0; + memcpy(&tid, ext->base.pad, sizeof(tid)); + ray_t* tbl = (tid > 0 && g->tables && (uint32_t)(tid - 1) < g->n_tables) + ? g->tables[tid - 1] : g->table; + if (!tbl || tbl->type != RAY_TABLE) continue; + exec_scan_add_col(s, ray_table_get_col(tbl, ext->sym)); + } + return s->rows >= 0 ? s : NULL; +} + ray_t* ray_execute(ray_graph_t* g, ray_op_t* root) { /* The qstats capture mode is armed once per query at the eval boundary * (ray_eval, eval_depth==0) — covering PROF (profiler/query-log) AND the @@ -4236,12 +4384,27 @@ 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; + /* Scan read-ahead: a registration over mapped columns made by the + * caller (a select, which also knows its filter) stands; otherwise the + * graph's own mapped scans are registered for its dispatches. */ + ray_pool_scan_t scan; + const ray_pool_scan_t* prev_scan = ray_pool_scan_get(); + bool own_scan = !prev_scan || prev_scan->rows < 0; + if (own_scan) ray_pool_scan_set(exec_scan_columns(g, &scan)); /* 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); + /* The cancel flag is reset at the outermost call only. A node's own + * path may execute a sub-graph (the grouped expression bridge + * materializing an input the element-wise compiler declines, #756); + * were that call to reset the flag, a cancel that arrived before it + * would be dropped and the workers would run the remaining tickets. */ + bool outermost = exec_depth++ == 0; + ray_t* result = ray_execute_inner(g, root, outermost); + exec_depth--; + if (own_scan) ray_pool_scan_set(prev_scan); return result ? result : ray_error("oom", NULL); } @@ -4282,14 +4445,15 @@ static ray_t* flatten_parted_col(ray_t* col) { return flat; } -static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root) { +static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root, bool reset_cancel) { if (!g || !root) return ray_error("nyi", NULL); /* Lazy-init the global thread pool on first call */ ray_pool_t* pool = ray_pool_get(); - /* Reset cancellation flag at the start of each query */ - if (pool) + /* Reset cancellation flag at the start of each query (not of a nested + * execution — see ray_execute) */ + if (pool && reset_cancel) atomic_store_explicit(&pool->cancelled, 0, memory_order_relaxed); /* Detect streaming mode: check if g->table has parted columns. diff --git a/src/ops/expr.c b/src/ops/expr.c index dbb7ce744..8940e9c93 100644 --- a/src/ops/expr.c +++ b/src/ops/expr.c @@ -697,9 +697,9 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { /* Issue #533: which nodes may skip the SYM null proof. A null SYM is * id 0, below every real intern id, and the fallback ranks a null SYM * below everything in all six comparisons (null == null, null != x, - * null < x hold; null == x, x < null do not). Raw id compares in the - * fused lane produce the same table, so a SYM column whose every - * consumer in this subtree is EQ..GE against a non-null constant (a + * null < x hold; null == x, x < null do not). Raw id equality compares + * preserve this; ordered compares bail below to lexical LUTs. A SYM + * column whose every consumer is EQ..GE against a non-null constant (a * null literal bails at OP_CONST) or another SYM scan needs no O(n) * ray_vec_has_nulls walk. Any other consumer — ISNULL, CAST, * arithmetic — reads the lane as a value and keeps the proof. */ @@ -905,6 +905,14 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { uint16_t op = node->opcode; int8_t ot; + /* SYM lanes contain intern ids, not lexical ranks. Route + * ordering through the used-id lookup/rank executor; + * equality can keep using the fused integer kernels. */ + if ((op == OP_LT || op == OP_LE || op == OP_GT || op == OP_GE) && + (op_child(g, node, 0)->out_type == RAY_SYM || + (s2 != 0xFF && op_child(g, node, 1)->out_type == RAY_SYM))) + EXPR_BAIL(EXPR_BAIL_OTHER); + /* Determine output type */ if (op == OP_CAST) ot = node->out_type; @@ -3239,9 +3247,9 @@ static void binary_range(ray_op_t* op, int8_t out_type, } else if (l_esz == 4) { /* SYM W32 stores unsigned IDs; for EQ/NE the unsigned compare * gives the same result as the signed compare against r_i64 - * (truncated to 32-bit). For ordering ops we keep the signed - * compare (matches the previous generic-path semantics for - * I32/DATE/TIME). */ + * (truncated to 32-bit). Ordered SYM/SYM and SYM/STR + * comparisons go to exec_sym_order; the raw ordered arm is + * retained for mixed SYM/numeric DAG operands. */ if (RAY_IS_SYM(lhs->type)) { if (opc == OP_EQ || opc == OP_NE) { const uint32_t* d = (const uint32_t*)lbase; @@ -3739,6 +3747,14 @@ ray_t* exec_elementwise_binary(ray_graph_t* g, ray_op_t* op, ray_t* lhs, ray_t* len = lhs->len; } + int8_t lt = lhs->type < 0 ? (int8_t)-lhs->type : lhs->type; + int8_t rt = rhs->type < 0 ? (int8_t)-rhs->type : rhs->type; + if ((op->opcode == OP_LT || op->opcode == OP_LE || + op->opcode == OP_GT || op->opcode == OP_GE) && + ((lt == RAY_SYM && (rt == RAY_SYM || rt == RAY_STR)) || + (rt == RAY_SYM && lt == RAY_STR))) + return exec_sym_order(op->opcode, lhs, rhs, l_scalar, r_scalar); + if (op->opcode == OP_POW) { int8_t lt = ew_value_base_type(lhs); int8_t rt = ew_value_base_type(rhs); diff --git a/src/ops/graph.c b/src/ops/graph.c index f78059738..d39eda74c 100644 --- a/src/ops/graph.c +++ b/src/ops/graph.c @@ -140,7 +140,7 @@ ray_graph_t* ray_graph_new(ray_t* tbl) { void ray_graph_free(ray_graph_t* g) { if (!g) return; - if (g->compile_err) { ray_release(g->compile_err); g->compile_err = NULL; } + if (g->compile_err) { ray_error_free(g->compile_err); g->compile_err = NULL; } /* errors are not refcounted */ /* Unconsumed slice-group hint (error paths / shapes that never * reached exec_group). */ diff --git a/src/ops/group.c b/src/ops/group.c index 9a74defb9..e2c5d5e4c 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -623,19 +623,58 @@ static void reduce_range(ray_t* input, int64_t start, int64_t end, } } -/* Context for parallel reduction */ +/* Keyless reductions over a pooled input run in chunks whose shape depends + * only on the row count: one partial per chunk, folded in chunk order. The + * association order of a float sum, the zero a min/max keeps among equal + * ±0, and the first/last winner are then the same whatever the worker count + * and whichever worker claimed which rows. (Per-worker partials depended on + * the dynamic claim order and changed run to run.) Below + * RAY_PARALLEL_THRESHOLD the input is one chunk scanned in one pass. Above + * it, chunks are whole multiples of RED_BLOCK rows, at most RED_MAX_CHUNKS + * of them — one ray_pool_dispatch_n window, no task-ring growth — and each + * chunk is walked RED_BLOCK rows at a time (scan read-ahead per block). */ +#define RED_BLOCK ((int64_t)8 * RAY_MORSEL_ELEMS) +#define RED_MAX_CHUNKS ((int64_t)RAY_POOL_INIT_TASKS) + +static inline int64_t red_chunk_rows(int64_t n) { + if (n < RAY_PARALLEL_THRESHOLD) return n > 0 ? n : 1; + int64_t per = (n + RED_MAX_CHUNKS - 1) / RED_MAX_CHUNKS; + return (per + RED_BLOCK - 1) / RED_BLOCK * RED_BLOCK; +} + +static inline int64_t red_n_chunks(int64_t n) { + int64_t rows = red_chunk_rows(n); + return n > 0 ? (n + rows - 1) / rows : 0; +} + +/* Chunked keyless reduction: one partial per chunk */ typedef struct { ray_t* input; - reduce_acc_t* accs; /* one per worker */ + reduce_acc_t* parts; /* [red_n_chunks(n)] */ bool has_nulls; - const int64_t* idx; /* NULL = no selection; else int64[total_pass] */ + const int64_t* idx; /* NULL = no selection; else int64[n] */ + int64_t n; /* rows (selected positions) to reduce */ + int64_t rows; /* red_chunk_rows(n) */ uint16_t opcode; -} par_reduce_ctx_t; +} red_chunk_ctx_t; -static void par_reduce_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { - par_reduce_ctx_t* c = (par_reduce_ctx_t*)ctx; - reduce_range(c->input, start, end, &c->accs[worker_id], - c->has_nulls, c->idx, c->opcode); +static void red_chunk_run(const red_chunk_ctx_t* c, int64_t k, reduce_acc_t* out) { + reduce_acc_t acc; + reduce_acc_init(&acc); + int64_t lo = k * c->rows; + int64_t hi = c->n - lo > c->rows ? lo + c->rows : c->n; + for (int64_t b = lo; b < hi; b += RED_BLOCK) { + int64_t e = hi - b > RED_BLOCK ? b + RED_BLOCK : hi; + if (!c->idx) ray_pool_scan_at(c->n, b, hi); + reduce_range(c->input, b, e, &acc, c->has_nulls, c->idx, c->opcode); + } + *out = acc; +} + +static void red_chunk_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + (void)worker_id; + red_chunk_ctx_t* c = (red_chunk_ctx_t*)ctx; + for (int64_t k = start; k < end; k++) red_chunk_run(c, k, &c->parts[k]); } static void reduce_merge(reduce_acc_t* dst, const reduce_acc_t* src, int8_t in_type, @@ -708,14 +747,22 @@ static void reduce_merge(reduce_acc_t* dst, const reduce_acc_t* src, int8_t in_t dst->cnt += src->cnt; break; case OP_FIRST: case OP_LAST: + /* src holds the rows after dst's: dst keeps its first, src's last + * wins. */ + if (src->has_first) { + if (!dst->has_first) { + dst->first_f = src->first_f; + dst->first_i = src->first_i; + dst->has_first = true; + } + dst->last_f = src->last_f; + dst->last_i = src->last_i; + } dst->cnt += src->cnt; break; default: break; } - /* reduce_merge does not merge first/last; caller handles these separately. - * Since workers process sequential ranges, worker 0's first is the global first, - * and the last worker's last is the global last. */ } /* Hash mixing constants used by the count-distinct kernel and helpers. */ @@ -3025,7 +3072,7 @@ static int64_t mode_large_group(ray_t* src, const int64_t* rows, int64_t count) while (c.partitions < c.tasks) c.partitions *= 2; /* Includes the scattered records and the worst hash-table capacity. */ if ((uint64_t)count > SIZE_MAX / 160 || - (uint64_t)count * 160 > (uint64_t)ray_heap_anon_watermark() / 4) return -4; + (uint64_t)count * 160 > (uint64_t)ray_heap_mem_budget() / 4) return -4; ray_t *records_hdr = NULL, *scatter_hdr = NULL, *hist_hdr = NULL; c.records = scratch_alloc(&records_hdr, (size_t)count * sizeof(mode_record_t)); c.histogram = scratch_calloc(&hist_hdr, @@ -4251,83 +4298,47 @@ ray_t* exec_reduction(ray_graph_t* g, ray_op_t* op, ray_t* input) { in_type == RAY_SYM ? input : NULL); } - ray_pool_t* pool = ray_pool_get(); - if (pool && scan_n >= RAY_PARALLEL_THRESHOLD) { - uint32_t nw = ray_pool_total_workers(pool); - ray_t* accs_hdr; - reduce_acc_t* accs = (reduce_acc_t*)scratch_calloc(&accs_hdr, nw * sizeof(reduce_acc_t)); - if (!accs) { if (sel_idx_block) ray_release(sel_idx_block); return ray_error("oom", NULL); } - for (uint32_t i = 0; i < nw; i++) reduce_acc_init(&accs[i]); - - par_reduce_ctx_t ctx = { .input = input, .accs = accs, - .has_nulls = has_nulls, .idx = sel_idx, - .opcode = op->opcode }; - ray_pool_dispatch(pool, par_reduce_fn, &ctx, scan_n); - - /* Merge: worker 0 is the base, merge the rest in order */ - reduce_acc_t merged; - reduce_acc_init(&merged); - merged = accs[0]; - for (uint32_t i = 1; i < nw; i++) { - reduce_merge(&merged, &accs[i], in_type, ray_sym_vec_domain(input), - op->opcode); - } - /* first = accs[first worker with data], last = accs[last worker with data] */ - for (uint32_t i = 0; i < nw; i++) { - if (accs[i].has_first) { - if (in_type == RAY_F64 || in_type == RAY_F32) merged.first_f = accs[i].first_f; - else merged.first_i = accs[i].first_i; - break; + reduce_acc_t acc; + if (scan_n < RAY_PARALLEL_THRESHOLD) { + reduce_acc_init(&acc); + reduce_range(input, 0, scan_n, &acc, has_nulls, sel_idx, op->opcode); + } else { + /* Fixed chunks folded in chunk order, pooled or not: the same + * result at any worker count (see red_chunk_rows). */ + struct ray_sym_domain_s* dom = ray_sym_vec_domain(input); + int64_t n_chunks = red_n_chunks(scan_n); + red_chunk_ctx_t ctx = { .input = input, .parts = NULL, + .has_nulls = has_nulls, .idx = sel_idx, + .n = scan_n, .rows = red_chunk_rows(scan_n), + .opcode = op->opcode }; + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, scan_n, RAY_PARALLEL_THRESHOLD)) { + ray_t* parts_hdr = NULL; + ctx.parts = (reduce_acc_t*)scratch_alloc(&parts_hdr, + (size_t)n_chunks * sizeof(reduce_acc_t)); + if (!ctx.parts) { + if (sel_idx_block) ray_release(sel_idx_block); + return ray_error("oom", NULL); } - } - for (int32_t i = (int32_t)nw - 1; i >= 0; i--) { - if (accs[i].has_first) { - if (in_type == RAY_F64 || in_type == RAY_F32) merged.last_f = accs[i].last_f; - else merged.last_i = accs[i].last_i; - break; + ray_pool_dispatch_n(pool, red_chunk_fn, &ctx, (uint32_t)n_chunks); + if (pool_cancelled(pool)) { + scratch_free(parts_hdr); + if (sel_idx_block) ray_release(sel_idx_block); + return ray_error("cancel", NULL); } - } - - ray_t* result; - switch (op->opcode) { - case OP_SUM: result = (in_type == RAY_F64 || in_type == RAY_F32) ? ray_f64(ray_f64_fin(merged.sum_f)) : (in_type == RAY_TIME ? ray_time(merged.sum_i) : ray_i64(merged.sum_i)); break; - case OP_PROD: result = (in_type == RAY_F64 || in_type == RAY_F32) ? ray_f64(ray_f64_fin(merged.prod_f)) : ray_i64(merged.prod_i); break; - case OP_ALL: result = ray_bool(merged.zero_count == 0); break; - case OP_ANY: result = ray_bool(merged.cnt > merged.zero_count); break; - case OP_MIN: result = reduction_extreme_result(op, in_type, merged.cnt > 0, merged.min_f, merged.min_i, input); break; - case OP_MAX: result = reduction_extreme_result(op, in_type, merged.cnt > 0, merged.max_f, merged.max_i, input); break; - /* COUNT returns total length including nulls — matches ray_count_fn's - * "count all elements" semantics, not SQL's COUNT(col) non-null count. */ - case OP_COUNT: result = ray_i64(scan_n); break; - case OP_AVG: result = merged.cnt > 0 ? ray_f64(ray_f64_fin((in_type == RAY_F64 || in_type == RAY_F32) ? merged.sum_f / merged.cnt : ray_i128_to_f64(merged.sum_hi, (uint64_t)merged.sum_i) / merged.cnt)) : ray_typed_null(-RAY_F64); break; - case OP_FIRST: result = merged.has_first ? (group_fp_type(in_type) ? ray_f64(merged.first_f) : reduction_i64_result(merged.first_i, in_type, in_type == RAY_SYM ? input : NULL)) : ray_typed_null(-(op->out_type ? op->out_type : in_type)); break; - case OP_LAST: result = merged.has_first ? (group_fp_type(in_type) ? ray_f64(merged.last_f) : reduction_i64_result(merged.last_i, in_type, in_type == RAY_SYM ? input : NULL)) : ray_typed_null(-(op->out_type ? op->out_type : in_type)); break; - case OP_VAR: case OP_VAR_POP: - case OP_STDDEV: case OP_STDDEV_POP: { - bool insufficient = (op->opcode == OP_VAR || op->opcode == OP_STDDEV) ? merged.cnt <= 1 : merged.cnt <= 0; - if (insufficient) { result = ray_typed_null(-RAY_F64); break; } - double mean, var_pop; - if (in_type == RAY_F64 || in_type == RAY_F32) { mean = merged.sum_f / merged.cnt; var_pop = merged.sum_sq_f / merged.cnt - mean * mean; } - else { mean = merged.sum_d / merged.cnt; var_pop = (double)merged.sum_sq_i / merged.cnt - mean * mean; } - if (var_pop < 0) var_pop = 0; - double val; - if (op->opcode == OP_VAR_POP) val = var_pop; - else if (op->opcode == OP_VAR) val = var_pop * merged.cnt / (merged.cnt - 1); - else if (op->opcode == OP_STDDEV_POP) val = sqrt(var_pop); - else val = sqrt(var_pop * merged.cnt / (merged.cnt - 1)); - result = ray_f64(ray_f64_fin(val)); - break; + acc = ctx.parts[0]; + for (int64_t k = 1; k < n_chunks; k++) + reduce_merge(&acc, &ctx.parts[k], in_type, dom, op->opcode); + scratch_free(parts_hdr); + } else { + reduce_acc_t part; + red_chunk_run(&ctx, 0, &acc); + for (int64_t k = 1; k < n_chunks; k++) { + red_chunk_run(&ctx, k, &part); + reduce_merge(&acc, &part, in_type, dom, op->opcode); } - default: result = ray_error("nyi", NULL); break; } - scratch_free(accs_hdr); - if (sel_idx_block) ray_release(sel_idx_block); - return result; } - - reduce_acc_t acc; - reduce_acc_init(&acc); - reduce_range(input, 0, scan_n, &acc, has_nulls, sel_idx, op->opcode); if (sel_idx_block) ray_release(sel_idx_block); switch (op->opcode) { @@ -4508,15 +4519,18 @@ bool ght_compute_layout(ght_layout_t* out, uint32_t n_keys, uint32_t n_aggs, } } /* Packed-tuple eligibility: every key is a plain fixed-width integer - * lane. This is a WHITELIST of exactly the types read_col_i64 - * decodes deliberately, not a `!= RAY_F64` blacklist: read_col_i64's + * lane. This is a WHITELIST of exactly the integer types + * read_col_i64 decodes, not a `!= RAY_F64` blacklist: read_col_i64's * `default` arm reads ONE BYTE, so an un-enumerated fixed-width type - * (RAY_F32 is the live example) would be silently mis-loaded, and a - * packed layout would then hash those wrong bits as the key identity. - * F64 is excluded by the same rule (read_col_i64 does not decode it), - * which additionally keeps the packed lanes clear of the -0.0 - * canonicalisation the F64 key builders apply (group_key_f64_bits, - * #407) — see ght_layout_t.packed_key. + * would be silently mis-loaded, and a packed layout would then hash + * those wrong bits as the key identity. F64 is excluded because + * read_col_i64 does not decode it, which additionally keeps the + * packed lanes clear of the -0.0 canonicalisation the F64 key + * builders apply (group_key_f64_bits, #407) — see + * ght_layout_t.packed_key. F32 stays off the list for the same + * reason: read_col_i64 does decode it (since #760, canonicalising + * -0.0 at the read), so the generic builders below group it + * correctly, but a packed region is meant to be raw bit identity. * GUID/STR are excluded by any_wide_key. n_keys == 0 is not a * tuple. */ if (n_keys >= 1 && !out->any_wide_key) { @@ -8454,7 +8468,10 @@ static bool group_materialize_prod_slots(agg_prod_t* prod, ray_t** agg_vecs, } /* ---- Scalar aggregate (n_keys==0): one flat scan, no GID, no hash ---- */ -typedef struct { +typedef struct scalar_ctx_s scalar_ctx_t; +typedef void (*scalar_range_fn_t)(scalar_ctx_t* c, da_accum_t* acc, + int64_t start, int64_t end); +struct scalar_ctx_s { void** agg_ptrs; int8_t* agg_types; ray_t** agg_cols; @@ -8466,16 +8483,36 @@ typedef struct { uint8_t need_flags; const int64_t* match_idx; /* NULL = no selection */ ray_t* rowsel; - /* per-worker accumulators (1 slot each) */ - da_accum_t* accums; - uint32_t n_accums; /* Per-agg integer-null sentinel + has-nulls flag. A per-element array * (not a bitmask, unlike da_ctx_t's agg_int_null_mask) because this * path's n_aggs is VLA-sized with no fixed cap — a 32/64-bit mask would * silently alias past that many aggregates. */ const bool* agg_int_null_has; int64_t* agg_int_null_sentinel; -} scalar_ctx_t; + /* One set of 1-slot accumulators per chunk of the scan (chunk shape: + * red_chunk_rows). Chunk k's arrays live in the k-th block of + * acc_words words, each at the word offset below; count is word 0, so + * an offset of 0 marks an array the query does not use. */ + int64_t* acc_base; + size_t acc_words; + size_t off_sum, off_sum_hi, off_min, off_max, off_sumsq, off_nn; + int64_t n_scan; + int64_t chunk_rows; + scalar_range_fn_t range_fn; +}; + +/* Aim acc's 1-slot arrays at chunk k's block. */ +static void scalar_chunk_acc(const scalar_ctx_t* c, int64_t k, da_accum_t* acc) { + int64_t* blk = c->acc_base + (size_t)k * c->acc_words; + memset(acc, 0, sizeof(*acc)); + acc->count = blk; + if (c->off_sum) acc->sum = (da_val_t*)(void*)(blk + c->off_sum); + if (c->off_sum_hi) acc->sum_hi = blk + c->off_sum_hi; + if (c->off_min) acc->min_val = (da_val_t*)(void*)(blk + c->off_min); + if (c->off_max) acc->max_val = (da_val_t*)(void*)(blk + c->off_max); + if (c->off_sumsq) acc->sumsq_f64 = (double*)(void*)(blk + c->off_sumsq); + if (c->off_nn) acc->nn_count = blk + c->off_nn; +} static inline int64_t scalar_i64_at(const void* ptr, int8_t type, int64_t r) { return read_col_i64(ptr, r, type, 0); /* attrs=0: agg columns are numeric, never SYM */ @@ -8529,9 +8566,7 @@ static inline void group_i128_sum_i64_range(const int64_t* restrict x, int64_t n /* Tight SIMD-friendly loop for single SUM/AVG on i64 (no mask). * Note: the int64 sum wraps (SUM's contract); an integer AVG also carries * the high word (acc->sum_hi) so it divides the exact 128-bit total. */ -static void scalar_sum_i64_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { - scalar_ctx_t* c = (scalar_ctx_t*)ctx; - da_accum_t* acc = &c->accums[worker_id]; +static void scalar_sum_i64_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t start, int64_t end) { const int64_t* restrict data = (const int64_t*)c->agg_ptrs[0]; if (acc->sum_hi) { group_i128_sum_i64_range(data + start, end - start, @@ -8546,9 +8581,7 @@ static void scalar_sum_i64_fn(void* ctx, uint32_t worker_id, int64_t start, int6 } /* Tight SIMD-friendly loop for single SUM/AVG on f64 (no mask) */ -static void scalar_sum_f64_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { - scalar_ctx_t* c = (scalar_ctx_t*)ctx; - da_accum_t* acc = &c->accums[worker_id]; +static void scalar_sum_f64_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t start, int64_t end) { const double* restrict data = (const double*)c->agg_ptrs[0]; double sum = 0.0; for (int64_t r = start; r < end; r++) @@ -8558,9 +8591,7 @@ static void scalar_sum_f64_fn(void* ctx, uint32_t worker_id, int64_t start, int6 } /* Tight loop for single SUM/AVG on integer linear expression (no mask). */ -static void scalar_sum_linear_i64_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { - scalar_ctx_t* c = (scalar_ctx_t*)ctx; - da_accum_t* acc = &c->accums[worker_id]; +static void scalar_sum_linear_i64_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t start, int64_t end) { const agg_linear_t* lin = &c->agg_linear[0]; int64_t n = end - start; @@ -8736,9 +8767,7 @@ static inline void scalar_accum_row(scalar_ctx_t* c, da_accum_t* acc, int64_t r) } } -static void scalar_accum_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { - scalar_ctx_t* c = (scalar_ctx_t*)ctx; - da_accum_t* acc = &c->accums[worker_id]; +static void scalar_accum_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t start, int64_t end) { const int64_t* match_idx = c->match_idx; for (int64_t i = start; i < end; i++) { @@ -8748,6 +8777,36 @@ static void scalar_accum_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ } } +/* Chunk k of the keyless scan into its own accumulators. Below the + * parallel threshold the scan is one chunk taken in one pass; above it each + * chunk is walked RED_BLOCK rows at a time, with scan read-ahead. */ +static void scalar_chunk_run(scalar_ctx_t* c, int64_t k) { + da_accum_t acc; + scalar_chunk_acc(c, k, &acc); + for (uint32_t a = 0; a < c->n_aggs; a++) { + bool fp = group_fp_type(c->agg_types[a]); + if (acc.min_val) { + if (fp) acc.min_val[a].f = DBL_MAX; else acc.min_val[a].i = INT64_MAX; + } + if (acc.max_val) { + if (fp) acc.max_val[a].f = -DBL_MAX; else acc.max_val[a].i = INT64_MIN; + } + } + int64_t lo = k * c->chunk_rows; + int64_t hi = c->n_scan - lo > c->chunk_rows ? lo + c->chunk_rows : c->n_scan; + int64_t step = c->n_scan < RAY_PARALLEL_THRESHOLD ? hi - lo : RED_BLOCK; + for (int64_t b = lo; b < hi; b += step) { + int64_t e = hi - b > step ? b + step : hi; + if (!c->match_idx) ray_pool_scan_at(c->n_scan, b, hi); + c->range_fn(c, &acc, b, e); + } +} + +static void scalar_chunk_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + (void)worker_id; + for (int64_t k = start; k < end; k++) scalar_chunk_run((scalar_ctx_t*)ctx, k); +} + /* Inner DA accumulation for a single row — shared by single-key and multi-key paths. * Fast path for SUM/AVG-only queries: eliminates op-code dispatch and da_read_val * dual-write overhead. The branch on c->all_sum is perfectly predicted (invariant @@ -10444,6 +10503,8 @@ typedef struct { * that computes SUM b (-1 = b runs its own loop). */ int8_t pair_sum[16]; int8_t fused_by[16]; + int64_t* wide; /* [workers * SG_CHUNK_ROWS]: widened + * narrow row ids (NULL if none narrow) */ } sg_ctx_t; /* Fused-product partial over a CONTIGUOUS row range — type-specialized @@ -10558,13 +10619,21 @@ static inline void sg_pair_accum(ray_t* x, ray_t* y, uint16_t op, } static void sg_accum_fn(void* raw, uint32_t wid, int64_t tstart, int64_t tend) { - (void)wid; sg_ctx_t* c = (sg_ctx_t*)raw; for (int64_t ti = tstart; ti < tend; ti++) { const sg_task_t* tk = &c->tasks[ti]; const ray_idx_slice_t* sl = &c->slices[tk->gi]; - const int64_t* restrict rows = sl->rows ? sl->rows + tk->lo : NULL; int64_t n = tk->hi - tk->lo; + const int64_t* rows = NULL; + if (sl->rows.p && !sl->rows.narrow) { + rows = (const int64_t*)sl->rows.p + tk->lo; + } else if (sl->rows.p) { + /* Narrow row ids: widen this task's chunk once. */ + int64_t* w = c->wide + (size_t)wid * SG_CHUNK_ROWS; + const uint32_t* src = (const uint32_t*)sl->rows.p + tk->lo; + for (int64_t j = 0; j < n; j++) w[j] = (int64_t)src[j]; + rows = w; + } /* Parted layout: each key's rows form one contiguous run — the * accumulate then streams raw column pointers and vectorizes. */ bool contig = (n > 0 && (!rows || rows[n - 1] - rows[0] + 1 == n)); @@ -10717,9 +10786,9 @@ static ray_t* sg_hint_to_selection(ray_graph_t* g, ray_t* tbl) { int64_t* ids = (int64_t*)ray_data(hdr); int64_t w = 0; for (int64_t i = 0; i < K; i++) { - if (sl[i].rows) { - memcpy(ids + w, sl[i].rows, - (size_t)sl[i].n * sizeof(int64_t)); + if (sl[i].rows.p) { + for (int64_t j = 0; j < sl[i].n; j++) + ids[w + j] = ray_idx_rows_at(sl[i].rows, j); } else { for (int64_t j = 0; j < sl[i].n; j++) ids[w + j] = sl[i].first + j; @@ -10946,7 +11015,7 @@ static ray_t* exec_group_slices(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } sg_ctx_t ctx = { slices, tasks, agg_vecs, agg_vecs2, prod, ext->agg_ops, n_aggs, partials, part_hi, part_sumsq, part_sum_y, - part_sumsq_y, part_sumxy, {0}, {0} }; + part_sumsq_y, part_sumxy, {0}, {0}, NULL }; /* Shared-stream pairing: a bare-scan SUM/AVG over the same column * a product's int side already streams rides the product loop — * one pass over the column instead of two. */ @@ -10975,13 +11044,34 @@ static ray_t* exec_group_slices(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } } ray_pool_t* pool = ray_pool_get(); + bool par = pool && n_tasks > 1 && total_rows >= RAY_PARALLEL_THRESHOLD; + ray_t* wide_hdr = NULL; + for (int64_t i = 0; i < K; i++) { + if (!slices[i].rows.narrow) continue; + size_t nw = par ? ray_pool_total_workers(pool) : 1; + ctx.wide = (int64_t*)scratch_alloc(&wide_hdr, + nw * SG_CHUNK_ROWS * sizeof(int64_t)); + if (!ctx.wide) { + scratch_free(sum_hdr); scratch_free(cnt_hdr); + scratch_free(sumsq_hdr); scratch_free(sum_y_hdr); + scratch_free(sumsq_y_hdr); scratch_free(sumxy_hdr); + scratch_free(sum_hi_hdr); scratch_free(part_hi_hdr); + ray_free(task_hdr); + scratch_free(part_hdr); + scratch_free(part_sumsq_hdr); scratch_free(part_sum_y_hdr); + scratch_free(part_sumsq_y_hdr); scratch_free(part_sumxy_hdr); + return NULL; /* OOM → generic path via fallback */ + } + break; + } /* dispatch_n: n_tasks is a task count (tens), far below the * element-grain of ray_pool_dispatch, which would lump them * into ONE serial task. */ - if (pool && n_tasks > 1 && total_rows >= RAY_PARALLEL_THRESHOLD) + if (par) ray_pool_dispatch_n(pool, sg_accum_fn, &ctx, (uint32_t)n_tasks); else sg_accum_fn(&ctx, 0, 0, n_tasks); + scratch_free(wide_hdr); /* Fold task partials in task order — chunk-sequential per group, * independent of worker count. */ for (int64_t ti = 0; ti < n_tasks; ti++) { @@ -11108,8 +11198,22 @@ static ray_t* exec_group_v2_exprs(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ok = false; break; /* user column shadows the synthetic name */ } ray_expr_t ex; - if (!expr_compile(g, tbl, in, &ex)) { ok = false; break; } - ray_t* v = expr_eval_full(&ex, nrows); + ray_t* v; + if (expr_compile(g, tbl, in, &ex)) { + v = expr_eval_full(&ex, nrows); + } else { + /* An input the element-wise compiler declines — an `if`, say: + * `(sum (if (== st 'bad) 1 0))` used to drop the whole group onto + * the legacy path, 6x slower under a WHERE selection (#756). The + * DAG executor materializes it row-wise over the whole table; the + * selection is cleared around the call so the vector comes back + * at full length (the final gather only compacts tables, but the + * node's own paths need not see the selection). */ + ray_t* saved_sel = g->selection; + g->selection = NULL; + v = ray_execute(g, in); + g->selection = saved_sel; + } if (!v || RAY_IS_ERR(v) || !ray_is_vec(v) || v->len != nrows) { if (v && !RAY_IS_ERR(v)) ray_release(v); else if (v) ray_release(v); @@ -11227,18 +11331,18 @@ typedef struct { ray_group_emit_filter_t emit_filter; } sp_dyn_ctx_t; -/* Parallel dense-count fill for the sp_dyn pure-count case: each worker - * scatters its row slice into a private uint32[bound] array; the caller - * merges them into range_count. The serial scatter was the Amdahl wall of - * every single-SYM-key "top-N by count" query (ClickBench q13: 88ms of a - * 110ms query in one thread's cache-miss loop; flat 8->16 core scaling). +/* Parallel dense-count fill for the legacy sparse-dynamic path: each worker + * scatters its row slice into a private uint32[stride] array with `bound` + * live counters and cache-line padding. The caller merges the live + * counters into range_count. * A key outside [0, bound) sets `fail` and the caller falls back to the * serial path — correctness never depends on the bound being right. */ typedef struct { const void* key_data; uint8_t key_esz; - uint32_t* counts; /* [n_workers * bound] */ + uint32_t* counts; /* 64-byte aligned [n_workers * stride] */ uint64_t bound; + size_t stride; /* counters per worker, padded to cache lines */ uint32_t n_workers; const int64_t* match_idx; ray_t* rowsel; @@ -11249,7 +11353,7 @@ static void sp_dyn_pcount_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { sp_dyn_pcount_ctx_t* c = (sp_dyn_pcount_ctx_t*)vctx; if (atomic_load_explicit(&c->fail, memory_order_relaxed)) return; - uint32_t* my = c->counts + (size_t)(wid % c->n_workers) * c->bound; + uint32_t* my = c->counts + (size_t)(wid % c->n_workers) * c->stride; const int64_t* match_idx = c->match_idx; const uint64_t bound = c->bound; const uint8_t esz = c->key_esz; @@ -11345,17 +11449,31 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { else if (key_esz == 2) bound = 1u << 16; ray_pool_t* dp = ray_pool_get(); uint32_t dnw = dp ? ray_pool_total_workers(dp) : 1; + /* Isolate adjacent workers' boundary counters even when + * bound is not a cache-line multiple. Pad each slice + * and align the base, retaining the scratch header for + * cleanup. The earlier dense path handles small spans. + * Include alignment slack in the memory cap; allocations + * just below the old cap may now fall back to serial. */ + const size_t pc_line = 64; + const size_t pc_per_line = pc_line / sizeof(uint32_t); + size_t stride = ((size_t)bound + pc_per_line - 1) + & ~(pc_per_line - 1); + uint64_t pc_bytes = (uint64_t)dnw * stride * sizeof(uint32_t) + + pc_line - 1; if (bound > 0 && dp && dnw >= 2 && - (uint64_t)dnw * bound * sizeof(uint32_t) <= (512u << 20)) { + pc_bytes <= (512u << 20)) { ray_t* pc_hdr = NULL; - uint32_t* pc = (uint32_t*)scratch_calloc(&pc_hdr, - (size_t)dnw * bound * sizeof(uint32_t)); - if (pc) { + void* raw = scratch_calloc(&pc_hdr, (size_t)pc_bytes); + if (raw) { + uint32_t* pc = (uint32_t*)(void*) + (((uintptr_t)raw + pc_line - 1) & ~(uintptr_t)(pc_line - 1)); sp_dyn_pcount_ctx_t pctx = { .key_data = key_data[0], .key_esz = key_esz, .counts = pc, .bound = bound, + .stride = stride, .n_workers = dnw, .match_idx = match_idx, .rowsel = rowsel, @@ -11380,7 +11498,7 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { } if (bound <= cap) { for (uint32_t w = 0; w < dnw; w++) { - const uint32_t* src = pc + (size_t)w * bound; + const uint32_t* src = pc + (size_t)w * stride; for (uint64_t o = 0; o < bound; o++) { uint64_t s = (uint64_t)range_count[o] + src[o]; range_count[o] = s > UINT32_MAX @@ -11691,6 +11809,13 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { return NULL; } +/* The error for a by: key that is no value: a function or null. Out of + * line and cold: exec_group_run is hot, and the error is rare. */ +static __attribute__((noinline, cold)) ray_t* group_key_not_value(int8_t t) { + return ray_error("domain", t != RAY_NULL ? "by: the key is a function, not a value" + : "by: the key is null, not a value"); +} + static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t group_limit) { if (!tbl || RAY_IS_ERR(tbl)) return tbl; @@ -11954,7 +12079,11 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* 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) { + if ((vec->type >= RAY_LAMBDA && vec->type <= RAY_VARY) || vec->type == RAY_NULL) { + /* A name bound to a function (`by: sum`) or to null: + * no value to group on, though ray_is_atom counts it. */ + wide = group_key_not_value(vec->type); + } else if (vec->type == -RAY_STR) { wide = broadcast_scalar(vec, tn); } else { ray_t* n_obj = make_i64(tn); @@ -12228,7 +12357,6 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (agg_is_binary_agg(ext->agg_ops[a])) { sc_has_binary = true; break; } if (n_keys == 0 && nrows > 0 && !sc_has_binary) { uint8_t need_flags = DA_NEED_COUNT; - bool has_first_last = false; for (uint32_t a = 0; a < n_aggs; a++) { uint16_t aop = ext->agg_ops[a]; if (aop == OP_SUM || aop == OP_PROD || aop == OP_AVG || aop == OP_ALL || aop == OP_ANY || aop == OP_FIRST || aop == OP_LAST) @@ -12237,7 +12365,6 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, { need_flags |= DA_NEED_SUM; need_flags |= DA_NEED_SUMSQ; } else if (aop == OP_MIN) need_flags |= DA_NEED_MIN; else if (aop == OP_MAX) need_flags |= DA_NEED_MAX; - if (aop == OP_FIRST || aop == OP_LAST) has_first_last = true; } /* Keyless path serves unbounded n_aggs — VLAs here scale with the query, @@ -12464,82 +12591,35 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } ray_pool_t* sc_pool = ray_pool_get(); - /* Pool dispatch is work-stealing: chunks may be processed out of - * row-index order across workers, so the "count[0]==1" sentinel - * scalar_accum_row uses for FIRST (and the always-overwrite for - * LAST) only yields the per-worker first/last, not the global - * one. The merge step then picks worker[0]'s FIRST regardless - * of which range it actually covered. Force serial execution - * when FIRST/LAST is in play; the DA path (which does track - * per-slot row bounds) is still preferred when we have keys. */ - uint32_t sc_n = (sc_pool && nrows >= RAY_PARALLEL_THRESHOLD && !has_first_last) - ? ray_pool_total_workers(sc_pool) : 1; - - ray_t* sc_hdr; - da_accum_t* sc_acc = (da_accum_t*)scratch_calloc(&sc_hdr, - sc_n * sizeof(da_accum_t)); - if (!sc_acc) { scratch_free(sc_vla_hdr); goto da_path; } - - /* One cache-line-aligned block per worker holding every 1-slot - * accumulator array (n_aggs entries each). Separate small - * allocations land next to each other on the heap, so adjacent - * workers' counters share cache lines and every row bounces the - * line across cores: on a two-socket 48-thread box the keyless - * SUM/COUNT/AVG over 100M rows took 8.8 s against 0.27 s on one - * socket. The block is padded to a whole number of lines and - * carried by _h_sum; the other headers stay NULL for - * da_accum_free. */ - bool alloc_ok = true; - const size_t sc_line = 64; + /* One accumulator set per chunk of the scan, chunk shape a function + * of the row count alone (red_chunk_rows), folded in chunk order + * below: float sums associate the same way at any worker count and + * every run, and FIRST/LAST/PROD take each chunk's value in row + * order. (Per-worker sets under dynamic dispatch did neither — + * FIRST/LAST had to force a serial scan.) */ + int64_t sc_n = red_n_chunks(n_scan); + if (sc_n < 1) sc_n = 1; + + /* Each chunk's 1-slot arrays (n_aggs entries each) fill one + * block aligned to a 128-byte line pair, padded to whole pairs: + * blocks that shared a line (or a pair the adjacent-line + * prefetcher fetches together) bounced it across cores on every row + * (on a two-socket 48-thread box the keyless SUM/COUNT/AVG over + * 100M rows took 8.8 s against 0.27 s on one socket). */ + const size_t sc_line = 128; size_t sc_words = 1; /* count[1] */ - if (need_flags & DA_NEED_SUM) sc_words += n_aggs; /* sum */ - if (sc_need_sum128) sc_words += n_aggs; /* sum_hi */ - if (need_flags & DA_NEED_MIN) sc_words += n_aggs; /* min_val */ - if (need_flags & DA_NEED_MAX) sc_words += n_aggs; /* max_val */ - if (need_flags & DA_NEED_SUMSQ) sc_words += n_aggs; /* sumsq_f64 */ - if (sc_any_nullable) sc_words += n_aggs; /* nn_count */ + size_t sc_off_sum = 0, sc_off_hi = 0, sc_off_min = 0, sc_off_max = 0; + size_t sc_off_sq = 0, sc_off_nn = 0; + if (need_flags & DA_NEED_SUM) { sc_off_sum = sc_words; sc_words += n_aggs; } + if (sc_need_sum128) { sc_off_hi = sc_words; sc_words += n_aggs; } + if (need_flags & DA_NEED_MIN) { sc_off_min = sc_words; sc_words += n_aggs; } + if (need_flags & DA_NEED_MAX) { sc_off_max = sc_words; sc_words += n_aggs; } + if (need_flags & DA_NEED_SUMSQ) { sc_off_sq = sc_words; sc_words += n_aggs; } + if (sc_any_nullable) { sc_off_nn = sc_words; sc_words += n_aggs; } size_t sc_bytes = ((sc_words * sizeof(int64_t)) + sc_line - 1) / sc_line * sc_line; - for (uint32_t w = 0; w < sc_n; w++) { - void* raw = scratch_calloc(&sc_acc[w]._h_sum, sc_bytes + sc_line); - if (!raw) { alloc_ok = false; break; } - /* 8-byte words from the first line boundary inside the block: - * every array below is a whole number of words. */ - int64_t* blk = (int64_t*)(void*)(((uintptr_t)raw + sc_line - 1) & ~(uintptr_t)(sc_line - 1)); - size_t off = 0; /* in words */ - sc_acc[w].count = blk + off; off += 1; - if (need_flags & DA_NEED_SUM) { - sc_acc[w].sum = (da_val_t*)(void*)(blk + off); off += n_aggs; - } - if (sc_need_sum128) { - sc_acc[w].sum_hi = blk + off; off += n_aggs; - } - if (need_flags & DA_NEED_MIN) { - sc_acc[w].min_val = (da_val_t*)(void*)(blk + off); off += n_aggs; - for (uint32_t a = 0; a < n_aggs; a++) { - if (group_fp_type(agg_types[a])) sc_acc[w].min_val[a].f = DBL_MAX; - else sc_acc[w].min_val[a].i = INT64_MAX; - } - } - if (need_flags & DA_NEED_MAX) { - sc_acc[w].max_val = (da_val_t*)(void*)(blk + off); off += n_aggs; - for (uint32_t a = 0; a < n_aggs; a++) { - if (group_fp_type(agg_types[a])) sc_acc[w].max_val[a].f = -DBL_MAX; - else sc_acc[w].max_val[a].i = INT64_MIN; - } - } - if (need_flags & DA_NEED_SUMSQ) { - sc_acc[w].sumsq_f64 = (double*)(void*)(blk + off); off += n_aggs; - } - if (sc_any_nullable) { - sc_acc[w].nn_count = blk + off; off += n_aggs; - } - } - if (!alloc_ok) { - for (uint32_t w = 0; w < sc_n; w++) da_accum_free(&sc_acc[w]); - scratch_free(sc_hdr); - scratch_free(sc_vla_hdr); - goto da_path; - } + ray_t* sc_hdr = NULL; + void* sc_raw = scratch_calloc(&sc_hdr, (size_t)sc_n * sc_bytes + sc_line); + if (!sc_raw) { scratch_free(sc_vla_hdr); goto da_path; } scalar_ctx_t sc_ctx = { .agg_ptrs = agg_ptrs, @@ -12553,10 +12633,19 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, .need_flags = need_flags, .match_idx = match_idx, .rowsel = rowsel, - .accums = sc_acc, - .n_accums = sc_n, .agg_int_null_has = sc_int_null_has, .agg_int_null_sentinel = sc_int_null_sentinel, + /* 8-byte words from the first line boundary of the carve */ + .acc_base = (int64_t*)(void*)(((uintptr_t)sc_raw + sc_line - 1) & ~(uintptr_t)(sc_line - 1)), + .acc_words = sc_bytes / sizeof(int64_t), + .off_sum = sc_off_sum, + .off_sum_hi = sc_off_hi, + .off_min = sc_off_min, + .off_max = sc_off_max, + .off_sumsq = sc_off_sq, + .off_nn = sc_off_nn, + .n_scan = n_scan, + .chunk_rows = red_chunk_rows(n_scan), }; /* Pick specialized tight loop when possible, else generic. @@ -12569,8 +12658,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * nulls. (try_linear_sumavg_input_i64 already refuses to build * a linear plan when any term column has nulls, so * agg_linear[0].enabled implies null-free.) */ - typedef void (*scalar_fn_t)(void*, uint32_t, int64_t, int64_t); - scalar_fn_t sc_fn = scalar_accum_fn; + scalar_range_fn_t sc_fn = scalar_accum_fn; bool agg0_has_nulls = n_aggs > 0 && (sc_int_null_has[0] || (agg_vecs[0] && group_fp_type(agg_vecs[0]->type) && @@ -12589,19 +12677,35 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, sc_fn = scalar_sum_linear_i64_fn; } - if (sc_n > 1) - ray_pool_dispatch(sc_pool, sc_fn, &sc_ctx, n_scan); - else - sc_fn(&sc_ctx, 0, 0, n_scan); + sc_ctx.range_fn = sc_fn; - /* Merge per-worker accumulators into sc_acc[0] */ - da_accum_t* m = &sc_acc[0]; - for (uint32_t w = 1; w < sc_n; w++) { - da_accum_t* wa = &sc_acc[w]; + if (sc_n > 1 && ray_pool_par_dispatch_ok(sc_pool, n_scan, RAY_PARALLEL_THRESHOLD)) { + ray_pool_dispatch_n(sc_pool, scalar_chunk_fn, &sc_ctx, (uint32_t)sc_n); + if (pool_cancelled(sc_pool)) { + scratch_free(sc_hdr); + scratch_free(sc_vla_hdr); + for (uint32_t a = 0; a < n_aggs; a++) + { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } + for (uint32_t k = 0; k < n_keys; k++) + if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); + return ray_error("cancel", NULL); + } + } else { + for (int64_t k = 0; k < sc_n; k++) scalar_chunk_run(&sc_ctx, k); + } + + /* Fold the chunks into chunk 0's accumulators, in chunk order */ + da_accum_t sc_m, sc_wa; + da_accum_t* m = &sc_m; + da_accum_t* wa = &sc_wa; + scalar_chunk_acc(&sc_ctx, 0, m); + for (int64_t w = 1; w < sc_n; w++) { + scalar_chunk_acc(&sc_ctx, w, wa); if (need_flags & DA_NEED_SUM) { for (uint32_t a = 0; a < n_aggs; a++) { uint16_t merge_op = ext->agg_ops[a]; - /* nn_count is per-agg; count is per worker. Fall back + /* nn_count is per-agg; count is per chunk. Fall back * to count when nn_count is absent (no nullable aggs). */ int64_t mnn = m->nn_count ? m->nn_count[a] : m->count[0]; int64_t wnn = wa->nn_count ? wa->nn_count[a] : wa->count[0]; @@ -12675,12 +12779,11 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } m->count[0] += wa->count[0]; } - for (uint32_t w = 1; w < sc_n; w++) da_accum_free(&sc_acc[w]); /* Emit 1-row result with no key columns */ ray_t* result = ray_table_new(n_aggs); if (!result || RAY_IS_ERR(result)) { - da_accum_free(&sc_acc[0]); scratch_free(sc_hdr); + scratch_free(sc_hdr); scratch_free(sc_vla_hdr); for (uint32_t a = 0; a < n_aggs; a++) { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } @@ -12797,7 +12900,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } } - da_accum_free(&sc_acc[0]); scratch_free(sc_hdr); + scratch_free(sc_hdr); scratch_free(sc_vla_hdr); for (uint32_t a = 0; a < n_aggs; a++) { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } @@ -15543,6 +15646,9 @@ v2_emit:; for (uint32_t k = 0; k < n_keys; k++) { if (!key_cols[k]) continue; grp_finalize_nulls(key_cols[k]); + /* The flag seeded from the source column above is a "may": a + * fused where: can have removed every null key row. */ + ray_group_key_settle_nulls(key_cols[k]); } /* Add key columns to result */ diff --git a/src/ops/idxop.c b/src/ops/idxop.c index 3ac15fc06..995c0c4a1 100644 --- a/src/ops/idxop.c +++ b/src/ops/idxop.c @@ -33,11 +33,11 @@ #include "ops/rowsel.h" #include "ops/hash.h" /* ray_hash_bytes: STR hash-index key word */ #include "core/pool.h" /* parallel hash-index build */ -#include "mem/sys.h" /* ray_sys_alloc: build scratch off the buddy heap */ #include #include #include #include +#include "core/platform.h" /* ray_io_counters: the hash build trace */ /* ── Routing observability counters (diagnostic, unsynchronized) ── */ uint64_t ray_idx_consults[IDX_SITE__N]; @@ -763,8 +763,8 @@ static ray_t* prepare_attach_ex(ray_t** vp, const char* what, if (numeric_elem_size(v->type) == 0 && !(allow_str && v->type == RAY_STR) && !(allow_sym && v->type == RAY_SYM)) { - return ray_error("nyi", "%s: only numeric/sym vectors supported (got type %d)", - what, (int)v->type); + return ray_error("nyi", "%s: only numeric/temporal%s%s vectors supported (got type %d)", + what, allow_sym ? "/sym" : "", allow_str ? "/str" : "", (int)v->type); } return v; } @@ -1294,6 +1294,7 @@ ray_t* ray_dict_acc_finish(ray_dict_acc_t* a, int64_t len) { * column frees the whole region with one munmap and never frees children by * pointer. All blocks are 32-aligned so each is a directly-usable ray_t. */ #define IDX_ALIGN32(n) (((n) + 31) & ~(int64_t)31) +#define IDX_HEAD_BYTES IDX_ALIGN32(32 + (int64_t)sizeof(ray_index_t)) /* the RAY_INDEX block */ /* Addresses of this kind's child ray_t* fields (so write/map read+patch them * uniformly). Returns count 0..4. */ @@ -1352,6 +1353,111 @@ int64_t ray_index_inline_size(const ray_index_t* ix) { * Generation 1 = the CSR grouped hash layout (table/gkeys/offs/rows); * generation-0 regions carried the retired chain layout. */ #define RAY_IDX_FORMAT_MAJOR ((uint8_t)1) +/* Generation 2: the same layout with the hash `table`, `offs` and `rows` + * stored narrow (see hx_get). Written only for indexes that carry a narrow + * array, so a binary that knows generation 1 alone loads such a column + * unindexed instead of misreading it; generation-1 regions read as before. */ +#define RAY_IDX_FORMAT_NARROW ((uint8_t)2) +/* Generation 3: a hash table whose home slots are the top hash bits + * (RAY_MARK_HASH_HIGH, groups in hash order); arrays narrow or I64 as in + * generation 2. Older binaries load such a column unindexed. */ +#define RAY_IDX_FORMAT_HASH_HIGH ((uint8_t)3) + +/* Hash index arrays whose values are group ids, positions or row ids + * (`table`, `offs`, `rows`) fit 32 bits on any column below 2^32 rows; they + * are stored as unsigned 32-bit values in an I32 vector when they do, + * halving them. Indexes built before, or too large, keep I64. Read either + * with hx_get; hand row-id slices out as ray_idx_rows_t (hx_rows). */ +static inline int64_t hx_get(const ray_t* v, int64_t i) { + const void* d = ray_data((ray_t*)v); + return v->type == RAY_I32 ? (int64_t)((const uint32_t*)d)[i] + : ((const int64_t*)d)[i]; +} +static inline void hx_set(ray_t* v, int64_t i, int64_t x) { + void* d = ray_data(v); + if (v->type == RAY_I32) ((uint32_t*)d)[i] = (uint32_t)x; + else ((int64_t*)d)[i] = x; +} +/* Copy `n` entries of `src` into `dst`, converting between widths. */ +static void hx_copy_into(ray_t* dst, const ray_t* src, int64_t n) { + if (dst->type == src->type) { + memcpy(ray_data(dst), ray_data((ray_t*)src), (size_t)n * (size_t)ray_elem_size(src->type)); + return; + } + for (int64_t i = 0; i < n; i++) hx_set(dst, i, hx_get(src, i)); +} +static inline ray_idx_rows_t hx_rows(const ray_t* rows, int64_t off) { + bool nw = rows->type == RAY_I32; + const uint8_t* d = (const uint8_t*)ray_data((ray_t*)rows); + return (ray_idx_rows_t){ d + off * (nw ? 4 : 8), nw }; +} +/* Copy `n` row ids from position `off` as int64. */ +static void hx_copy_rows(int64_t* dst, const ray_t* rows, int64_t off, int64_t n) { + if (rows->type != RAY_I32) { + memcpy(dst, (const int64_t*)ray_data((ray_t*)rows) + off, (size_t)n * sizeof(int64_t)); + return; + } + const uint32_t* src = (const uint32_t*)ray_data((ray_t*)rows) + off; + for (int64_t i = 0; i < n; i++) dst[i] = (int64_t)src[i]; +} +/* Home slot of mixed hash `h` in a table of `mask + 1` slots: its top bits + * when the table is RAY_MARK_HASH_HIGH, else its low bits. */ +static inline uint64_t hx_home_m(uint8_t markers, uint64_t mask, uint64_t h) { + return (markers & RAY_MARK_HASH_HIGH) ? h >> __builtin_clzll(mask) : h & mask; +} +static inline uint64_t hx_home(const ray_index_t* ix, uint64_t h) { + return hx_home_m(ix->markers, ix->u.hash.mask, h); +} +static inline bool hx_narrow_ok(const ray_t* v) { + return v && !RAY_IS_ERR(v) && (v->type == RAY_I64 || v->type == RAY_I32); +} +typedef struct { const int64_t* src; uint32_t* dst; } hx_narrow_ctx_t; +static void hx_narrow_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + hx_narrow_ctx_t* c = (hx_narrow_ctx_t*)raw; + for (int64_t i = start; i < end; i++) c->dst[i] = (uint32_t)c->src[i]; +} +/* The narrow copy of an I64 array whose values all lie in [0, bound] + * (bound below 2^32, known to the caller), consuming `v`; `v` itself when it + * cannot be narrowed or the copy cannot be allocated. */ +static ray_t* hx_narrow(ray_t* v, int64_t bound) { + if (!v || RAY_IS_ERR(v) || v->type != RAY_I64 || bound < 0 || bound > (int64_t)UINT32_MAX) return v; + ray_t* n = ray_vec_new(RAY_I32, v->len > 0 ? v->len : 1); + if (!n || RAY_IS_ERR(n)) { if (n) ray_error_free(n); return v; } + n->len = v->len; + hx_narrow_ctx_t c = { (const int64_t*)ray_data(v), (uint32_t*)ray_data(n) }; + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, v->len, RAY_PARALLEL_THRESHOLD)) { + ray_pool_dispatch(pool, hx_narrow_fn, &c, v->len); + /* An interrupt makes the dispatch skip its tasks, leaving the copy + * unfilled: keep the wide array. */ + if (atomic_load_explicit(&pool->cancelled, memory_order_acquire)) { + ray_release(n); + return v; + } + } else { + hx_narrow_fn(&c, 0, 0, v->len); + } + ray_release(v); + return n; +} +/* Narrow a freshly built hash payload in place. */ +static void hx_narrow_payload(ray_index_t* ix) { + ix->u.hash.table = hx_narrow(ix->u.hash.table, ix->u.hash.n_groups); + ix->u.hash.offs = hx_narrow(ix->u.hash.offs, ix->u.hash.n_keys); + ix->u.hash.rows = hx_narrow(ix->u.hash.rows, ix->built_for_len); +} +static uint8_t idx_format_of(const ray_index_t* ix) { + if (ix->kind == RAY_IDX_HASH && (ix->markers & RAY_MARK_HASH_HIGH)) + return RAY_IDX_FORMAT_HASH_HIGH; + if (ix->kind == RAY_IDX_HASH) { + const ray_t* a[3] = { ix->u.hash.table, ix->u.hash.offs, ix->u.hash.rows }; + for (int i = 0; i < 3; i++) + if (a[i] && !RAY_IS_ERR(a[i]) && a[i]->type == RAY_I32) + return RAY_IDX_FORMAT_NARROW; + } + return RAY_IDX_FORMAT_MAJOR; +} /* Serialize `ix` into `dst` (>= ray_index_inline_size bytes, pre-zeroed by the * caller for clean 32-pad). Child pointers become region-relative offsets. */ @@ -1360,7 +1466,7 @@ void ray_index_inline_write(uint8_t* dst, const ray_index_t* ix) { 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; + blkhdr.order = idx_format_of(ix); memcpy(dst, &blkhdr, 32); ray_index_t* on = (ray_index_t*)(dst + 32); @@ -1386,15 +1492,16 @@ 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)); +/* The head block of `ix`'s region (IDX_HEAD_BYTES at `head`): the RAY_INDEX + * block with the child pointers turned into region offsets, the children + * following it in slot order. */ +static void idx_inline_head(uint8_t* head, const ray_index_t* ix) { + memset(head, 0, (size_t)IDX_HEAD_BYTES); 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; + blkhdr.order = idx_format_of(ix); memcpy(head, &blkhdr, 32); ray_index_t* on = (ray_index_t*)(head + 32); memcpy(on, ix, sizeof(ray_index_t)); @@ -1404,13 +1511,21 @@ bool ray_index_inline_write_file(FILE* f, const ray_index_t* ix) { 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); + int64_t off = IDX_HEAD_BYTES; 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); } +} + +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_HEAD_BYTES]; + idx_inline_head(head, ix); + ray_t** src_slots[4]; + int nch = idx_child_slots((ray_index_t*)ix, src_slots); if (fwrite(head, 1, sizeof(head), f) != sizeof(head)) return false; for (int i = 0; i < nch; i++) { ray_t* c = *src_slots[i]; @@ -1436,7 +1551,8 @@ ray_t* ray_index_inline_map(uint8_t* region, int64_t region_size) { int64_t head = IDX_ALIGN32(32 + (int64_t)sizeof(ray_index_t)); if (region_size < head) return NULL; ray_t* idx = (ray_t*)region; - if (idx->order != RAY_IDX_FORMAT_MAJOR) return NULL; + if (idx->order != RAY_IDX_FORMAT_MAJOR && idx->order != RAY_IDX_FORMAT_NARROW && + idx->order != RAY_IDX_FORMAT_HASH_HIGH) return NULL; if (idx->len != (int64_t)sizeof(ray_index_t)) return NULL; ray_index_t* ix = ray_index_payload(idx); ray_t** slots[4]; @@ -1465,6 +1581,25 @@ ray_t* ray_index_inline_map(uint8_t* region, int64_t region_size) { } *slots[i] = c; } + /* Hash arrays: I64 (generation 1), or I32 for the narrow ones. */ + if (ix->kind == RAY_IDX_HASH && + ((ix->u.hash.table && !hx_narrow_ok(ix->u.hash.table)) || + (ix->u.hash.offs && !hx_narrow_ok(ix->u.hash.offs)) || + (ix->u.hash.rows && !hx_narrow_ok(ix->u.hash.rows)) || + (ix->u.hash.gkeys && ix->u.hash.gkeys->type != RAY_I64) || + (idx->order == RAY_IDX_FORMAT_MAJOR && + ((ix->u.hash.table && ix->u.hash.table->type != RAY_I64) || + (ix->u.hash.offs && ix->u.hash.offs->type != RAY_I64) || + (ix->u.hash.rows && ix->u.hash.rows->type != RAY_I64))))) + return NULL; + /* Generation 3 is exactly the hash tables with top-bit homes; their + * home shift comes from the mask, so it must match the table. */ + bool high = ix->kind == RAY_IDX_HASH && (ix->markers & RAY_MARK_HASH_HIGH); + if (high != (idx->order == RAY_IDX_FORMAT_HASH_HIGH)) return NULL; + if (high && (ix->u.hash.mask < 7 || (ix->u.hash.mask & (ix->u.hash.mask + 1)) || + !ix->u.hash.table || + (uint64_t)ix->u.hash.table->len != ix->u.hash.mask + 1)) + return NULL; /* two layouts: [lo | nn] (2 per chunk) and [lo | nn | hi] (3 per chunk) */ if (ix->kind == RAY_IDX_CHUNK_ZONE && ix->u.chunk_zone.aggs && (ix->u.chunk_zone.aggs->type != RAY_I64 || ix->u.chunk_zone.is_f64 || @@ -1479,334 +1614,688 @@ ray_t* ray_index_inline_map(uint8_t* region, int64_t region_size) { /* -------------------------------------------------------------------------- * Hash index — CSR grouped layout * - * Build: one pass assigns every non-null row a group id via an open- - * addressing probe on its i64-canonical key (SYM: column-domain id), then a - * counting pass lays the row ids out as contiguous ascending slices (CSR: - * offs[] + rows[]). The build-time bucket table is sized by ROW count so - * insertion stays O(1); the attached/persisted table is rebuilt at - * DISTINCT-key size — it indexes groups, not rows, so a high-duplication - * column (the whole point of a grouped index) keeps a tiny footprint. + * Build: every non-null row gets a group id from an open-addressing probe on + * its i64-canonical key (SYM: column-domain id), and the row ids are laid out + * as contiguous ascending slices (CSR: offs[] + rows[]). Numeric and SYM + * columns use the partitioned builder below; STR keeps a serial walk. The + * persisted table is sized by DISTINCT keys — it indexes groups, not rows, + * so a high-duplication column (the whole point of a grouped index) keeps a + * tiny footprint. * - * Lookup `k`: slot-walk table[hash(k) & mask] comparing gkeys[gid] == k; a - * hit yields the contiguous ascending slice rows[offs[gid]..offs[gid+1]). + * Lookup `k`: slot-walk table from hx_home(mix64(k)) comparing + * gkeys[gid] == k; a hit yields the contiguous ascending slice + * rows[offs[gid]..offs[gid+1]). * -------------------------------------------------------------------------- */ -/* Parallel build of the CSR hash layout for numeric / SYM keys. The - * result is the serial walk's: groups numbered by first occurrence, rows - * ascending inside a group, nulls excluded — assembled in - * partition-parallel passes: +/* ── Hash-index build trace ── */ +ray_hash_mark_t ray_hash_trace_mark(void) { + ray_hash_mark_t m = { ray_profile_now_ns(), 0, 0, 0, 0 }; + ray_io_counters_t io; + ray_io_counters(false, &io); + m.majflt = io.majflt; m.rd = io.rd; m.wr = io.wr; m.cwr = io.cwr; + return m; +} + +void ray_hash_trace_add(ray_hash_trace_t* t, int ph, ray_hash_mark_t since, int64_t moved) { + if (!t || ph < 0 || ph >= RAY_HXT_N) return; + ray_hash_mark_t now = ray_hash_trace_mark(); + t->ns[ph] += now.ns - since.ns; + t->majflt[ph] += now.majflt - since.majflt; + t->rd[ph] += now.rd - since.rd; + t->wr[ph] += now.wr - since.wr; + t->cwr[ph] += now.cwr - since.cwr; + t->moved[ph] += moved; +} + +void ray_hash_trace_print(FILE* f, const char* what, const ray_hash_trace_t* t, int64_t col_bytes) { + static const char* names[RAY_HXT_N] = { + "count", "bucket", "distinct", "groups", "table", "append" }; + int64_t moved = 0; + fprintf(f, "%s:", what); + for (int p = 0; p < RAY_HXT_N; p++) { + if (!t->ns[p] && !t->moved[p]) continue; + moved += t->moved[p]; + fprintf(f, " %s=%.1fms/%lldflt/%.1fMBr/%.1fMBw/%.1fMBcw/moved=%.1fMB(%.2fx)", names[p], + (double)t->ns[p] / 1e6, (long long)t->majflt[p], + (double)t->rd[p] / 1048576.0, (double)t->wr[p] / 1048576.0, + (double)t->cwr[p] / 1048576.0, (double)t->moved[p] / 1048576.0, + col_bytes > 0 ? (double)t->moved[p] / (double)col_bytes : 0.0); + } + fprintf(f, " total_moved=%.1fMB(%.2fx)\n", (double)moved / 1048576.0, + col_bytes > 0 ? (double)moved / (double)col_bytes : 0.0); +} + +/* Partitioned build of the CSR hash layout for numeric / SYM keys. + * + * Groups are numbered in ascending order of mix64(key word) — for these key + * types distinct keys have distinct words, so the order is strict — and a + * group's home slot is the TOP bits of that hash (RAY_MARK_HASH_HIGH). Both + * follow from the data alone, so the arrays are the same bytes whatever the + * partition count, memory budget or core count, and every output array is + * written front to back: * - * A row ranges: key word per row, rows bucketed by hash partition - * (a partition's rows stay ascending: the ranges are in row order); - * B per partition: open-addressing dedupe into local groups, each - * group's first row marked in a bitmap; - * C a group's number is the rank of its first row among all marked - * rows (block popcounts + one prefix) — exactly the order the - * serial walk assigns; - * D per partition: keys and counts into the group's slots; - * E per partition: row scatter (of[] as cursor); then the key table, - * filled in group order on the calling thread so its bytes match the - * serial build. + * 1 row ranges: key words and row ids bucketed by the top hash bits into + * contiguous partitions (rows stay ascending inside each); + * 2 the number of groups, when the arrays are to be laid out at their + * final size before they are written (one batch: its own dedupe; + * several, into a persisted region: a counting pass per partition); + * 3 partitions in batches that fit the memory budget: per partition a + * local dedupe, its groups sorted by hash, then its keys, row offsets + * and row slices stored at the partition's place in gkeys/offs/rows — + * a partition's groups follow every group of the partitions before it — + * and the batch's key words and row ids punched out of their spill + * files when they spilled; + * 4 the slot table: groups in order, each in the first free slot from its + * home. Homes ascend with the group number, so this is one forward + * sweep (a run past the last slot continues from slot 0) and gives + * exactly the table that inserting the groups in order would; with the + * size known it runs batch by batch in step 3. * - * Every array a pass writes at random is faulted in beforehand from all - * workers in slices: a fresh mapping faulted at random from every worker - * serialises on the page-table locks. Returns false (nothing allocated) - * when the pool cannot be used; the caller then runs the serial walk. */ + * Only a batch of partitions is accessed at random; the bucketed input and + * the outputs are streamed, so past the spill watermark they page through + * their files sequentially instead of thrashing. Returns 1 on success, + * -1 when out of memory or interrupted (nothing left allocated; a region's + * memory holds no complete index). */ +#define HB_ROW_BYTES 128 /* batch working set per row, worst case in heap blocks */ +#define HB_PART_ROWS (1 << 17) /* rows per partition: its dedupe table stays cache-sized */ +#define HB_MAX_PARTS 4096 +#define HB_MAX_TASKS 256 + +typedef struct { + uint32_t* tab; /* slot -> local group + 1 */ + uint64_t tmask; + uint64_t* gk; /* [cap] key word per local group */ + int64_t* gc; /* [cap] rows per local group, then its row cursor */ + uint32_t* ord; /* [ng] local groups in ascending hash order */ + uint32_t* lg; /* [rows] local group of each of the partition's rows */ + int64_t ng, cap; + int64_t g0; /* number of the partition's first group */ +} hb_part_t; + typedef struct { ray_t* v; const uint8_t* base; int64_t n; - int n_tasks; - int n_part; - int part_shift; /* partition = mix64(key) >> shift */ - uint64_t* kw; /* [n] key word (non-null rows) */ - int64_t* pr; /* [n_keys] row ids grouped by partition */ - int64_t* lg; /* [n_keys] local group of pr[j] */ - int64_t* cnt; /* [n_tasks * n_part] rows per (task, partition) */ + int64_t n_tasks; + int64_t n_part; + int part_shift; /* partition = mix64(key) >> part_shift */ + bool wide; /* row ids past 32 bits */ + int64_t* cnt; /* [n_tasks * n_part] rows per (task, partition), then cursors */ int64_t* part_off; /* [n_part + 1] */ - int64_t* ng_p; /* [n_part] local groups per partition */ - int64_t* gfirst; /* [n_keys] first row per local group (partition-relative) */ - int64_t* gcount; /* [n_keys] rows per local group, then its global number */ - uint64_t* bits; /* [n/64 + 1] first-row marks */ - int64_t* blk_rank; /* [n/HP_BLOCK + 1] exclusive prefix of block popcounts */ - int64_t* gk; /* [n_groups] keys */ - int64_t* of; /* [n_groups + 1] */ - int64_t* rw; /* [n_keys] */ - int64_t* tbl; /* [cap] */ - uint64_t tmask; + uint64_t* kw; /* [n_keys] key words, bucketed */ + void* rid; /* [n_keys] row ids, bucketed (u32 or i64) */ + int64_t* gk; /* gkeys data */ + ray_t* offs; + ray_t* rows; + int64_t b_lo; /* first partition of the batch */ + int64_t part_cap0; /* rows of a batch: a larger partition is alone in its batch */ + hb_part_t* part; /* [batch] */ + int64_t* part_ng; /* [n_part] groups per partition, once counted; else NULL */ + bool counting; /* the dedupe only counts its groups into part_ng */ _Atomic(bool) oom; -} hash_par_t; - -#define HP_BLOCK 4096 +} hash_bld_t; -static inline int64_t hp_task_lo(const hash_par_t* h, int64_t t) { return h->n * t / h->n_tasks; } +static inline int64_t hb_task_lo(const hash_bld_t* h, int64_t t) { return h->n * t / h->n_tasks; } +static inline int64_t hb_rid(const hash_bld_t* h, int64_t k) { + return h->wide ? ((const int64_t*)h->rid)[k] : (int64_t)((const uint32_t*)h->rid)[k]; +} -static void hp_pass_a(void* raw, uint32_t wid, int64_t start, int64_t end) { +static void hb_count(void* raw, uint32_t wid, int64_t start, int64_t end) { (void)wid; (void)end; - hash_par_t* h = (hash_par_t*)raw; - int64_t lo = hp_task_lo(h, start), hi = hp_task_lo(h, start + 1); + hash_bld_t* h = (hash_bld_t*)raw; + int64_t lo = hb_task_lo(h, start), hi = hb_task_lo(h, start + 1); int64_t* cnt = h->cnt + start * h->n_part; for (int64_t i = lo; i < hi; i++) { - if (ray_vec_is_null(h->v, i)) { h->kw[i] = 0; continue; } - uint64_t k = hash_row_key_word(h->v, h->base, i); - h->kw[i] = k; - cnt[mix64(k) >> h->part_shift]++; + if (ray_vec_is_null(h->v, i)) continue; + cnt[mix64(hash_row_key_word(h->v, h->base, i)) >> h->part_shift]++; } } -static void hp_pass_a2(void* raw, uint32_t wid, int64_t start, int64_t end) { +static void hb_bucket(void* raw, uint32_t wid, int64_t start, int64_t end) { (void)wid; (void)end; - hash_par_t* h = (hash_par_t*)raw; - int64_t lo = hp_task_lo(h, start), hi = hp_task_lo(h, start + 1); - int64_t* cur = h->cnt + start * h->n_part; /* now the write cursors */ + hash_bld_t* h = (hash_bld_t*)raw; + int64_t lo = hb_task_lo(h, start), hi = hb_task_lo(h, start + 1); + int64_t* cur = h->cnt + start * h->n_part; for (int64_t i = lo; i < hi; i++) { if (ray_vec_is_null(h->v, i)) continue; - h->pr[cur[mix64(h->kw[i]) >> h->part_shift]++] = i; + uint64_t k = hash_row_key_word(h->v, h->base, i); + int64_t j = cur[mix64(k) >> h->part_shift]++; + h->kw[j] = k; + if (h->wide) ((int64_t*)h->rid)[j] = i; + else ((uint32_t*)h->rid)[j] = (uint32_t)i; + } +} + +static void hb_part_free(hb_part_t* s) { + ray_free_raw(s->tab); ray_free_raw(s->gk); ray_free_raw(s->gc); ray_free_raw(s->ord); + ray_free_raw(s->lg); + memset(s, 0, sizeof(*s)); +} + +/* Size the group arrays for `cap` groups and re-place the groups so far. */ +static bool hb_part_reserve(hb_part_t* s, int64_t cap) { + uint64_t tcap = next_pow2((uint64_t)cap * 2); + uint64_t* gk = (uint64_t*)ray_alloc_raw((size_t)cap * sizeof(uint64_t)); + int64_t* gc = (int64_t*)ray_alloc_raw((size_t)cap * sizeof(int64_t)); + uint32_t* tab = (uint32_t*)ray_alloc_raw((size_t)tcap * sizeof(uint32_t)); + if (!gk || !gc || !tab) { ray_free_raw(gk); ray_free_raw(gc); ray_free_raw(tab); return false; } + memset(tab, 0, (size_t)tcap * sizeof(uint32_t)); + if (s->ng) { + memcpy(gk, s->gk, (size_t)s->ng * sizeof(uint64_t)); + memcpy(gc, s->gc, (size_t)s->ng * sizeof(int64_t)); + } + for (int64_t g = 0; g < s->ng; g++) { + uint64_t slot = mix64(gk[g]) & (tcap - 1); + while (tab[slot]) slot = (slot + 1) & (tcap - 1); + tab[slot] = (uint32_t)(g + 1); + } + ray_free_raw(s->gk); ray_free_raw(s->gc); ray_free_raw(s->tab); + s->gk = gk; s->gc = gc; s->tab = tab; s->tmask = tcap - 1; s->cap = cap; + return true; +} + +static inline int64_t hb_part_find(const hb_part_t* s, uint64_t k) { + uint64_t slot = mix64(k) & s->tmask; + for (;;) { + uint32_t g1 = s->tab[slot]; + if (s->gk[g1 - 1] == k) return g1 - 1; /* every probed key is present */ + slot = (slot + 1) & s->tmask; + } +} + +/* LSD radix sort of `n` hashes with their group payload; constant digits + * (the partition's own top bits among them) are skipped. */ +static void hb_sort(uint64_t* k, uint32_t* v, uint64_t* tk, uint32_t* tv, int64_t n) { + if (n < 64) { + for (int64_t i = 1; i < n; i++) { + uint64_t x = k[i]; uint32_t y = v[i]; int64_t j = i; + for (; j > 0 && k[j - 1] > x; j--) { k[j] = k[j - 1]; v[j] = v[j - 1]; } + k[j] = x; v[j] = y; + } + return; + } + int64_t hist[8][256]; + memset(hist, 0, sizeof(hist)); + for (int64_t i = 0; i < n; i++) + for (int d = 0; d < 8; d++) hist[d][(k[i] >> (8 * d)) & 0xFF]++; + uint64_t *sk = k, *dk = tk; + uint32_t *sv = v, *dv = tv; + for (int d = 0; d < 8; d++) { + int64_t* hd = hist[d]; + if (hd[(sk[0] >> (8 * d)) & 0xFF] == n) continue; + int64_t run = 0; + for (int b = 0; b < 256; b++) { int64_t c = hd[b]; hd[b] = run; run += c; } + for (int64_t i = 0; i < n; i++) { + int64_t j = hd[(sk[i] >> (8 * d)) & 0xFF]++; + dk[j] = sk[i]; dv[j] = sv[i]; + } + uint64_t* t1 = sk; sk = dk; dk = t1; + uint32_t* t2 = sv; sv = dv; dv = t2; + } + if (sk != k) { + memcpy(k, sk, (size_t)n * sizeof(uint64_t)); + memcpy(v, sv, (size_t)n * sizeof(uint32_t)); } } -static void hp_pass_b(void* raw, uint32_t wid, int64_t start, int64_t end) { +/* Batch task: dedupe partition b_lo + start, then order its groups by hash + * (counting: only record how many groups it has). */ +static void hb_dedupe(void* raw, uint32_t wid, int64_t start, int64_t end) { (void)wid; (void)end; - hash_par_t* h = (hash_par_t*)raw; - int64_t p = start; + hash_bld_t* h = (hash_bld_t*)raw; + hb_part_t* s = &h->part[start]; + int64_t p = h->b_lo + start; int64_t lo = h->part_off[p], hi = h->part_off[p + 1]; - int64_t cnt = hi - lo; - h->ng_p[p] = 0; - if (cnt == 0) return; - uint64_t cap = next_pow2((uint64_t)cnt * 2 + 1); - if (cap < 16) cap = 16; - int64_t* tab = (int64_t*)ray_sys_alloc((size_t)cap * sizeof(int64_t)); - if (!tab) { atomic_store_explicit(&h->oom, true, memory_order_relaxed); return; } - memset(tab, 0, (size_t)cap * sizeof(int64_t)); - uint64_t mask = cap - 1; - int64_t* gfirst = h->gfirst + lo; - int64_t* gcount = h->gcount + lo; - int64_t ng = 0; + if (hi == lo) return; + /* groups are at most the rows; a partition larger than a batch (a hot + * key's) starts at the batch size and grows. Counted before, it is + * sized for its groups exactly. */ + int64_t cap0 = hi - lo < h->part_cap0 ? hi - lo : h->part_cap0; + if (h->part_ng && !h->counting) cap0 = h->part_ng[p] > 0 ? h->part_ng[p] : 1; + /* each row's group, kept for the row pass when the partition fits a + * batch; past it the row pass probes again */ + if (!h->counting && hi - lo <= h->part_cap0) { + s->lg = (uint32_t*)ray_alloc_raw((size_t)(hi - lo) * sizeof(uint32_t)); + if (!s->lg) goto oom; + } + if (!hb_part_reserve(s, cap0)) goto oom; for (int64_t j = lo; j < hi; j++) { - int64_t i = h->pr[j]; - uint64_t k = h->kw[i]; - uint64_t slot = mix64(k) & mask; + if (RAY_UNLIKELY(((j - lo) & 0xFFFF) == 0xFFFF && ray_interrupted())) return; + uint64_t k = h->kw[j]; + uint64_t slot = mix64(k) & s->tmask; for (;;) { - int64_t g1 = tab[slot]; + uint32_t g1 = s->tab[slot]; if (g1 == 0) { - tab[slot] = ng + 1; - gfirst[ng] = i; - gcount[ng] = 1; - h->lg[j] = ng; - /* the partition's rows are ascending, so i is this group's - * first row; the word is shared with other partitions */ - atomic_fetch_or_explicit((_Atomic(uint64_t)*)&h->bits[i >> 6], - (uint64_t)1 << (i & 63), memory_order_relaxed); - ng++; + if (s->ng == s->cap) { + if (s->cap >= (int64_t)UINT32_MAX / 2 || !hb_part_reserve(s, s->cap * 2)) goto oom; + slot = mix64(k) & s->tmask; + continue; + } + s->tab[slot] = (uint32_t)(s->ng + 1); + s->gk[s->ng] = k; + s->gc[s->ng] = 1; + if (s->lg) s->lg[j - lo] = (uint32_t)s->ng; + s->ng++; break; } - if (h->kw[gfirst[g1 - 1]] == k) { h->lg[j] = g1 - 1; gcount[g1 - 1]++; break; } - slot = (slot + 1) & mask; + if (s->gk[g1 - 1] == k) { + s->gc[g1 - 1]++; + if (s->lg) s->lg[j - lo] = g1 - 1; + break; + } + slot = (slot + 1) & s->tmask; } } - h->ng_p[p] = ng; - ray_sys_free(tab); + if (h->counting) { + h->part_ng[p] = s->ng; + hb_part_free(s); + return; + } + { + int64_t ng = s->ng; + uint64_t* hs = (uint64_t*)ray_alloc_raw((size_t)ng * sizeof(uint64_t)); + uint64_t* th = (uint64_t*)ray_alloc_raw((size_t)ng * sizeof(uint64_t)); + uint32_t* tv = (uint32_t*)ray_alloc_raw((size_t)ng * sizeof(uint32_t)); + s->ord = (uint32_t*)ray_alloc_raw((size_t)ng * sizeof(uint32_t)); + if (!hs || !th || !tv || !s->ord) { + ray_free_raw(hs); ray_free_raw(th); ray_free_raw(tv); + goto oom; + } + for (int64_t g = 0; g < ng; g++) { hs[g] = mix64(s->gk[g]); s->ord[g] = (uint32_t)g; } + hb_sort(hs, s->ord, th, tv, ng); + ray_free_raw(hs); ray_free_raw(th); ray_free_raw(tv); + } + return; +oom: + atomic_store_explicit(&h->oom, true, memory_order_relaxed); } -/* per-block popcount of the first-row marks (prefixed serially after) */ -static void hp_pass_c(void* raw, uint32_t wid, int64_t start, int64_t end) { +/* Batch task: store partition b_lo + start's keys, row offsets and rows. */ +static void hb_emit(void* raw, uint32_t wid, int64_t start, int64_t end) { (void)wid; (void)end; - hash_par_t* h = (hash_par_t*)raw; - int64_t w0 = start * (HP_BLOCK / 64), w1 = w0 + HP_BLOCK / 64; - int64_t nw = (h->n + 63) / 64; - if (w1 > nw) w1 = nw; - int64_t c = 0; - for (int64_t w = w0; w < w1; w++) c += __builtin_popcountll(h->bits[w]); - h->blk_rank[start] = c; + hash_bld_t* h = (hash_bld_t*)raw; + hb_part_t* s = &h->part[start]; + int64_t p = h->b_lo + start; + int64_t lo = h->part_off[p], hi = h->part_off[p + 1]; + int64_t r = lo; + for (int64_t j = 0; j < s->ng; j++) { + uint32_t g = s->ord[j]; + h->gk[s->g0 + j] = (int64_t)s->gk[g]; + hx_set(h->offs, s->g0 + j, r); + int64_t c = s->gc[g]; + s->gc[g] = r; + r += c; + } + /* rows ascend inside the partition, so inside each group too */ + for (int64_t j = lo; j < hi; j++) + hx_set(h->rows, s->gc[s->lg ? (int64_t)s->lg[j - lo] : hb_part_find(s, h->kw[j])]++, + hb_rid(h, j)); + hb_part_free(s); } -static inline int64_t hp_rank(const hash_par_t* h, int64_t i) { - int64_t blk = i / HP_BLOCK; - int64_t r = h->blk_rank[blk]; - int64_t w = i >> 6; - for (int64_t x = blk * (HP_BLOCK / 64); x < w; x++) r += __builtin_popcountll(h->bits[x]); - return r + __builtin_popcountll(h->bits[w] & (((uint64_t)1 << (i & 63)) - 1)); +/* An interrupt makes a dispatch skip its tasks, so the outputs may be + * incomplete: stop on either signal. */ +static bool hb_stopped(ray_pool_t* pool) { + return ray_interrupted() || + (pool && atomic_load_explicit(&pool->cancelled, memory_order_acquire)); } -static void hp_pass_d(void* raw, uint32_t wid, int64_t start, int64_t end) { - (void)wid; (void)end; - hash_par_t* h = (hash_par_t*)raw; - int64_t p = start; - int64_t lo = h->part_off[p]; - const int64_t* gfirst = h->gfirst + lo; - int64_t* gcount = h->gcount + lo; - int64_t ng = h->ng_p[p]; - for (int64_t g = 0; g < ng; g++) { - int64_t G = hp_rank(h, gfirst[g]); - h->gk[G] = (int64_t)h->kw[gfirst[g]]; - h->of[G + 1] = gcount[g]; - gcount[g] = G; /* local -> global from here on */ +/* Is an array of `len` entries of `es` bytes, allocated for `cap`, worth + * cutting to size? */ +static bool hb_cut(int64_t len, int64_t cap, size_t es) { + size_t slack = (size_t)(cap - len) * es; + return !(slack < ((size_t)1 << 20) || (2 * len > cap && slack < ((size_t)64 << 20))); +} + +/* `v` (room for `cap` entries, `len` used) cut to size when the slack is + * worth a copy; `v` itself when it is not or the copy cannot be made. */ +static ray_t* hb_trim(ray_t* v, int64_t len, int64_t cap) { + size_t es = (size_t)ray_elem_size(v->type); + if (!hb_cut(len, cap, es)) return v; + ray_t* t = ray_vec_new(v->type, len > 0 ? len : 1); + if (!t || RAY_IS_ERR(t)) { if (t) ray_error_free(t); return v; } + t->len = len; + memcpy(ray_data(t), ray_data(v), (size_t)len * es); + ray_release(v); + return t; +} + +static void hb_zero(ray_t* v, int64_t lo, int64_t hi) { + if (hi <= lo) return; + size_t es = (size_t)ray_elem_size(v->type); + memset((uint8_t*)ray_data(v) + (size_t)lo * es, 0, (size_t)(hi - lo) * es); +} + +/* Where the build puts its four arrays: heap vectors (`map` NULL), or the + * persisted region itself — `map(ctx, bytes)` hands back the region's + * zero-filled memory once its size is known, laid out as + * ray_index_inline_write lays an index out (the head block, then the + * table, gkeys, offs and rows blocks), and the arrays are the block bodies. */ +typedef struct { + ray_index_region_fn map; + void* ctx; + uint8_t* base; /* the region: map's result */ + bool zeroed; /* the arrays start zero-filled */ + ray_err_t err; /* why the build failed when map did */ + ray_t *table, *gkeys, *offs, *rows; +} hb_dst_t; + +/* The order a heap block for `bytes` of vector data gets. A vector's + * header carries it, and the region keeps each array's header. */ +static uint8_t hb_alloc_order(size_t bytes) { + uint8_t o = ray_order_for_size(bytes); + return o >= RAY_HEAP_POOL_ORDER ? (uint8_t)RAY_ORDER_DIRECT : o; +} + +/* The block header at `at`: what ray_index_inline_write stores for a heap + * vector of `type` holding `len` entries in room for `cap`. */ +static ray_t* hb_region_vec(uint8_t* at, int8_t type, int64_t len, int64_t cap) { + ray_t* b = (ray_t*)at; + memset(b, 0, 32); + b->mmod = 1; b->rc = 1; + b->order = hb_alloc_order((size_t)cap * (size_t)ray_elem_size(type)); + b->type = type; + b->len = len; + return b; +} + +static void hb_dst_drop(hb_dst_t* d) { + ray_t** a[4] = { &d->table, &d->gkeys, &d->offs, &d->rows }; + for (int i = 0; i < 4; i++) { + if (!d->map && *a[i]) { + if (RAY_IS_ERR(*a[i])) ray_error_free(*a[i]); else ray_release(*a[i]); + } + *a[i] = NULL; } } -static void hp_pass_e(void* raw, uint32_t wid, int64_t start, int64_t end) { - (void)wid; (void)end; - hash_par_t* h = (hash_par_t*)raw; - int64_t p = start; - int64_t lo = h->part_off[p], hi = h->part_off[p + 1]; - const int64_t* gmap = h->gcount + lo; - /* rows of a partition are ascending -> ascending inside each group; - * of[] doubles as the fill cursor (the caller shifts it back); the - * partition's groups are nobody else's, so the cursors are private */ - for (int64_t j = lo; j < hi; j++) - h->rw[h->of[gmap[h->lg[j]]]++] = h->pr[j]; +/* The arrays of `n_keys` keys in `n_groups` groups and a table of `cap` + * slots. Each is allocated at the capacity the in-memory build ends with + * (gkeys and offs sized for the keys and cut to the groups when that pays, + * hb_trim), so a region written in place holds the bytes a heap-built + * index persists. */ +static bool hb_dst_open(hb_dst_t* d, int8_t aw, int64_t n_keys, int64_t n_groups, uint64_t cap) { + size_t es = (size_t)ray_elem_size(aw); + int64_t gcap = hb_cut(n_groups, n_keys, 8) ? n_groups : n_keys; + int64_t ocap = hb_cut(n_groups + 1, n_keys + 1, es) ? n_groups + 1 : n_keys + 1; + int64_t rcap = n_keys > 0 ? n_keys : 1; + if (gcap < 1) gcap = 1; + if (!d->map) { + d->table = ray_vec_new(aw, (int64_t)cap); + d->gkeys = ray_vec_new(RAY_I64, gcap); + d->offs = ray_vec_new(aw, ocap); + d->rows = ray_vec_new(aw, rcap); + if (!d->table || RAY_IS_ERR(d->table) || !d->gkeys || RAY_IS_ERR(d->gkeys) || + !d->offs || RAY_IS_ERR(d->offs) || !d->rows || RAY_IS_ERR(d->rows)) { + hb_dst_drop(d); + return false; + } + d->table->len = (int64_t)cap; + d->gkeys->len = n_groups; + d->offs->len = n_groups + 1; + d->rows->len = n_keys; + return true; + } + int64_t tb = IDX_ALIGN32(32 + (int64_t)cap * (int64_t)es); + int64_t gb = IDX_ALIGN32(32 + n_groups * 8); + int64_t ob = IDX_ALIGN32(32 + (n_groups + 1) * (int64_t)es); + int64_t rb = IDX_ALIGN32(32 + n_keys * (int64_t)es); + d->base = d->map(d->ctx, IDX_HEAD_BYTES + tb + gb + ob + rb); + if (!d->base) { d->err = RAY_ERR_IO; return false; } + d->zeroed = true; + uint8_t* at = d->base + IDX_HEAD_BYTES; + d->table = hb_region_vec(at, aw, (int64_t)cap, (int64_t)cap); at += tb; + d->gkeys = hb_region_vec(at, RAY_I64, n_groups, gcap); at += gb; + d->offs = hb_region_vec(at, aw, n_groups + 1, ocap); at += ob; + d->rows = hb_region_vec(at, aw, n_keys, rcap); + return true; } -/* Zero (and so fault in) up to 8 fresh regions in parallel slices: each - * task owns one contiguous slice per region, so the page faults spread - * over the workers without two of them ever meeting on a page. */ -typedef struct { void* p[8]; size_t bytes[8]; int n; int n_tasks; } hp_touch_t; -static void hp_touch_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { - (void)wid; (void)end; - hp_touch_t* t = (hp_touch_t*)raw; - for (int r = 0; r < t->n; r++) { - size_t lo = t->bytes[r] * (size_t)start / (size_t)t->n_tasks; - size_t hi = t->bytes[r] * (size_t)(start + 1) / (size_t)t->n_tasks; - if (hi > lo) memset((char*)t->p[r] + lo, 0, hi - lo); +/* The slot table, filled as the groups come in group order: each group in + * the first free slot from its home. Homes ascend with the group number, + * so this is one forward sweep; the run that passes the last slot goes on + * from slot 0 once every group is in (hb_sweep_finish). */ +typedef struct { uint64_t cap; int shift; int64_t next, wrap; bool zeroed; } hb_sweep_t; + +static void hb_sweep_init(hb_sweep_t* w, uint64_t cap, bool zeroed) { + w->cap = cap; w->shift = __builtin_clzll(cap - 1); + w->next = 0; w->wrap = -1; w->zeroed = zeroed; +} + +/* Groups [g_lo, g_hi); false when interrupted. */ +static bool hb_sweep(hb_sweep_t* w, ray_t* table, const int64_t* gk, int64_t g_lo, int64_t g_hi, + ray_pool_t* pool) { + for (int64_t g = g_lo; g < g_hi && w->wrap < 0; g++) { + if (RAY_UNLIKELY(((g - g_lo) & 0xFFFFF) == 0xFFFFF && hb_stopped(pool))) return false; + int64_t home = (int64_t)(mix64((uint64_t)gk[g]) >> w->shift); + int64_t s = home > w->next ? home : w->next; + if (s >= (int64_t)w->cap) { w->wrap = g; break; } + if (!w->zeroed) hb_zero(table, w->next, s); + hx_set(table, s, g + 1); + w->next = s + 1; + } + return true; +} + +static void hb_sweep_finish(hb_sweep_t* w, ray_t* table, int64_t n_groups) { + if (!w->zeroed) hb_zero(table, w->next, (int64_t)w->cap); + if (w->wrap < 0) return; + for (int64_t s = 0, g = w->wrap; g < n_groups; g++) { /* the run that wrapped */ + while (hx_get(table, s) != 0) s++; + hx_set(table, s, g + 1); } } -static void hp_touch(ray_pool_t* pool, int n_tasks, hp_touch_t* t) { - t->n_tasks = n_tasks; - ray_pool_dispatch_n(pool, hp_touch_fn, t, (uint32_t)n_tasks); + +/* The end of the batch of partitions that starts at `p`: as many as fit + * `batch_rows` (at least one) and the batch's task slots. */ +static int64_t hb_batch_end(const hash_bld_t* h, int64_t p, int64_t max_batch, int64_t batch_rows) { + int64_t q = p, br = 0; + do { br += h->part_off[q + 1] - h->part_off[q]; q++; } + while (q < h->n_part && q - p < max_batch && + br + h->part_off[q + 1] - h->part_off[q] <= batch_rows); + return q; +} + +/* Dedupe (or count) the partitions [p, q); false when interrupted or out of + * memory. */ +static bool hb_dedupe_batch(hash_bld_t* h, ray_pool_t* pool, bool par, int64_t p, int64_t q) { + h->b_lo = p; + if (par && q - p > 1) ray_pool_dispatch_n(pool, hb_dedupe, h, (uint32_t)(q - p)); + else for (int64_t i = 0; i < q - p; i++) hb_dedupe(h, 0, i, i + 1); + return !hb_stopped(pool) && !atomic_load_explicit(&h->oom, memory_order_relaxed); +} + +/* Debug builds: the row count past which row ids are 64-bit, lowered by + * RAY_HASH_WIDE_ROWS so the wide layout runs on small columns in tests. */ +static int64_t hb_wide_rows(void) { +#if defined(DEBUG) + const char* e = getenv("RAY_HASH_WIDE_ROWS"); + if (e && *e) { long long x = strtoll(e, NULL, 10); if (x >= 0) return x; } +#endif + return (int64_t)UINT32_MAX; } -static bool hash_build_par(ray_t* v, ray_t** gkeys_out, ray_t** offs_out, - ray_t** rows_out, ray_t** table_out, uint64_t* mask_out, - int64_t* n_keys_out, int64_t* n_groups_out) { +static int hash_build_part(ray_t* v, hb_dst_t* d, uint64_t* mask_out, + int64_t* n_keys_out, int64_t* n_groups_out, ray_hash_trace_t* tr) { int64_t n = v->len; ray_pool_t* pool = ray_pool_get(); - if (!ray_pool_par_dispatch_ok(pool, n, 1 << 16)) return false; - int workers = (int)ray_pool_total_workers(pool); - - hash_par_t h; + bool par = ray_pool_par_dispatch_ok(pool, n, 1 << 16); + int64_t workers = par ? (int64_t)ray_pool_total_workers(pool) : 1; + + /* Rows of a batch: the random-access working set within the budget. */ + int64_t budget = ray_heap_anon_watermark() / 4; + if (budget < (INT64_C(16) << 20)) budget = INT64_C(16) << 20; + int64_t batch_rows = budget / HB_ROW_BYTES; + int64_t part_rows = batch_rows / workers; + if (part_rows > HB_PART_ROWS) part_rows = HB_PART_ROWS; + if (part_rows < 4096) part_rows = 4096; + + hash_bld_t h; memset(&h, 0, sizeof(h)); h.v = v; h.base = (const uint8_t*)ray_data(v); h.n = n; - h.n_tasks = workers * 4; - if (h.n_tasks > 512) h.n_tasks = 512; + h.wide = n > hb_wide_rows(); + h.n_tasks = par ? workers * 4 : 1; + if (h.n_tasks > HB_MAX_TASKS) h.n_tasks = HB_MAX_TASKS; h.n_part = 2; - while (h.n_part < workers * 4 && h.n_part < 512) h.n_part <<= 1; + while (((par && h.n_part < workers * 4) || h.n_part * part_rows < n) && + h.n_part < HB_MAX_PARTS) + h.n_part <<= 1; h.part_shift = 64; - for (int q = h.n_part; q > 1; q >>= 1) h.part_shift--; + for (int64_t q = h.n_part; q > 1; q >>= 1) h.part_shift--; - int64_t nw = (n + 63) / 64; - int64_t nblk = (n + HP_BLOCK - 1) / HP_BLOCK; + int8_t aw = h.wide ? RAY_I64 : RAY_I32; + int64_t es = h.wide ? 8 : 4; size_t cnt_b = (size_t)h.n_tasks * (size_t)h.n_part * sizeof(int64_t); - size_t po_b = (size_t)(h.n_part + 1) * sizeof(int64_t); - size_t bits_b = (size_t)(nw + 1) * sizeof(uint64_t); - h.kw = (uint64_t*)ray_sys_alloc((size_t)n * sizeof(uint64_t)); - h.cnt = (int64_t*)ray_sys_alloc(cnt_b); - h.part_off = (int64_t*)ray_sys_alloc(po_b); - h.ng_p = (int64_t*)ray_sys_alloc(po_b); - h.bits = (uint64_t*)ray_sys_alloc(bits_b); - h.blk_rank = (int64_t*)ray_sys_alloc((size_t)(nblk + 1) * sizeof(int64_t)); - ray_t *gkeys = NULL, *offs = NULL, *rows = NULL, *table = NULL; - bool ok = h.kw && h.cnt && h.part_off && h.ng_p && h.bits && h.blk_rank; - if (!ok) goto done; - memset(h.cnt, 0, cnt_b); memset(h.part_off, 0, po_b); memset(h.ng_p, 0, po_b); - memset(h.blk_rank, 0, (size_t)(nblk + 1) * sizeof(int64_t)); - { - hp_touch_t t = { .p = { h.kw, h.bits }, .bytes = { (size_t)n * sizeof(uint64_t), bits_b }, .n = 2 }; - hp_touch(pool, h.n_tasks, &t); - } - - /* A: key words + partition counts, then the bucketed row ids */ - ray_pool_dispatch_n(pool, hp_pass_a, &h, (uint32_t)h.n_tasks); - if (ray_interrupted()) { ok = false; goto done; } + int64_t n_keys = 0, n_groups = 0, ng_run = 0, kw_done = 0; + int64_t max_batch = h.n_part < workers * 4 ? h.n_part : workers * 4; + h.part_cap0 = batch_rows; + bool ok = false, known = false, one = false; + uint64_t cap = 0; + hb_sweep_t sw; + memset(&sw, 0, sizeof(sw)); + ray_hash_mark_t tm = tr ? ray_hash_trace_mark() : (ray_hash_mark_t){0}; + int64_t colb = n * (int64_t)ray_sym_elem_size(v->type, v->attrs); + h.cnt = (int64_t*)ray_alloc_raw(cnt_b); + h.part_off = (int64_t*)ray_alloc_raw((size_t)(h.n_part + 1) * sizeof(int64_t)); + h.part = (hb_part_t*)ray_calloc_raw((size_t)max_batch * sizeof(hb_part_t)); + if (!h.cnt || !h.part_off || !h.part) goto done; + memset(h.cnt, 0, cnt_b); + + /* 1: bucket the key words and row ids by partition */ + if (par) ray_pool_dispatch_n(pool, hb_count, &h, (uint32_t)h.n_tasks); + else hb_count(&h, 0, 0, 1); + if (tr) { ray_hash_trace_add(tr, RAY_HXT_COUNT, tm, colb); tm = ray_hash_trace_mark(); } + if (hb_stopped(pool)) goto done; { int64_t run = 0; - for (int p = 0; p < h.n_part; p++) { + for (int64_t p = 0; p < h.n_part; p++) { h.part_off[p] = run; - for (int t = 0; t < h.n_tasks; t++) { - int64_t c = h.cnt[(int64_t)t * h.n_part + p]; - h.cnt[(int64_t)t * h.n_part + p] = run; + for (int64_t t = 0; t < h.n_tasks; t++) { + int64_t c = h.cnt[t * h.n_part + p]; + h.cnt[t * h.n_part + p] = run; run += c; } } h.part_off[h.n_part] = run; + n_keys = run; + } + h.kw = (uint64_t*)ray_alloc_raw((size_t)(n_keys > 0 ? n_keys : 1) * sizeof(uint64_t)); + h.rid = ray_alloc_raw((size_t)(n_keys > 0 ? n_keys : 1) * (size_t)es); + if (!h.kw || !h.rid) goto done; + if (par) ray_pool_dispatch_n(pool, hb_bucket, &h, (uint32_t)h.n_tasks); + else hb_bucket(&h, 0, 0, 1); + if (tr) { ray_hash_trace_add(tr, RAY_HXT_BUCKET, tm, colb + n_keys * (8 + es)); tm = ray_hash_trace_mark(); } + if (hb_stopped(pool)) goto done; + + /* 2: the group count before any array, so each is allocated — or laid + * out in the persisted region — once, at its final size, and written + * once, front to back. One batch: its dedupe gives the count. Several, + * into a region: each partition's groups are counted first (one more + * read of the key words, where the arrays would otherwise go through + * memory at the key count's size and be copied into the file). Several, + * in memory: the group arrays are sized for the keys and cut after. */ + one = hb_batch_end(&h, 0, max_batch, batch_rows) >= h.n_part; + if (one) { + if (!hb_dedupe_batch(&h, pool, par, 0, h.n_part)) goto done; + for (int64_t i = 0; i < h.n_part; i++) n_groups += h.part[i].ng; + known = true; + } else if (d->map) { + h.part_ng = (int64_t*)ray_calloc_raw((size_t)h.n_part * sizeof(int64_t)); + if (!h.part_ng) goto done; + h.counting = true; + for (int64_t p = 0, q; p < h.n_part; p = q) { + q = hb_batch_end(&h, p, max_batch, batch_rows); + if (!hb_dedupe_batch(&h, pool, par, p, q)) goto done; + } + h.counting = false; + for (int64_t p = 0; p < h.n_part; p++) n_groups += h.part_ng[p]; + known = true; + if (tr) { ray_hash_trace_add(tr, RAY_HXT_DISTINCT, tm, n_keys * 8); tm = ray_hash_trace_mark(); } } - int64_t n_keys = h.part_off[h.n_part]; - size_t kb = (size_t)(n_keys > 0 ? n_keys : 1) * sizeof(int64_t); - h.pr = (int64_t*)ray_sys_alloc(kb); - h.lg = (int64_t*)ray_sys_alloc(kb); - h.gfirst = (int64_t*)ray_sys_alloc(kb); - h.gcount = (int64_t*)ray_sys_alloc(kb); - if (!h.pr || !h.lg || !h.gfirst || !h.gcount) { ok = false; goto done; } - { - hp_touch_t t = { .p = { h.pr, h.lg, h.gfirst, h.gcount }, .bytes = { kb, kb, kb, kb }, .n = 4 }; - hp_touch(pool, h.n_tasks, &t); - } - ray_pool_dispatch_n(pool, hp_pass_a2, &h, (uint32_t)h.n_tasks); - if (ray_interrupted()) { ok = false; goto done; } - - /* B: per-partition dedupe */ - ray_pool_dispatch_n(pool, hp_pass_b, &h, (uint32_t)h.n_part); - if (ray_interrupted() || atomic_load_explicit(&h.oom, memory_order_relaxed)) { ok = false; goto done; } - int64_t n_groups = 0; - for (int p = 0; p < h.n_part; p++) n_groups += h.ng_p[p]; - - /* C: first-occurrence numbering = rank of the group's first row */ - ray_pool_dispatch_n(pool, hp_pass_c, &h, (uint32_t)nblk); - { - int64_t run = 0; - for (int64_t b = 0; b < nblk; b++) { int64_t c = h.blk_rank[b]; h.blk_rank[b] = run; run += c; } - h.blk_rank[nblk] = run; - } - - gkeys = ray_vec_new(RAY_I64, n_groups > 0 ? n_groups : 1); - offs = ray_vec_new(RAY_I64, n_groups + 1); - rows = ray_vec_new(RAY_I64, n_keys > 0 ? n_keys : 1); - uint64_t cap = next_pow2((uint64_t)(n_groups < 4 ? 8 : 2 * n_groups)); - if (cap < 8) cap = 8; - table = ray_vec_new(RAY_I64, (int64_t)cap); - if (!gkeys || RAY_IS_ERR(gkeys) || !offs || RAY_IS_ERR(offs) || - !rows || RAY_IS_ERR(rows) || !table || RAY_IS_ERR(table)) { ok = false; goto done; } - gkeys->len = n_groups; offs->len = n_groups + 1; rows->len = n_keys; table->len = (int64_t)cap; - h.gk = (int64_t*)ray_data(gkeys); h.of = (int64_t*)ray_data(offs); - h.rw = (int64_t*)ray_data(rows); h.tbl = (int64_t*)ray_data(table); - h.tmask = cap - 1; - { - hp_touch_t t = { .p = { h.gk, h.of, h.rw, h.tbl }, - .bytes = { (size_t)(n_groups > 0 ? n_groups : 1) * sizeof(int64_t), - (size_t)(n_groups + 1) * sizeof(int64_t), kb, - (size_t)cap * sizeof(int64_t) }, .n = 4 }; - hp_touch(pool, h.n_tasks, &t); - } - - /* D: keys and counts; E: rows and the key table */ - ray_pool_dispatch_n(pool, hp_pass_d, &h, (uint32_t)h.n_part); - for (int64_t g = 0; g < n_groups; g++) h.of[g + 1] += h.of[g]; - ray_pool_dispatch_n(pool, hp_pass_e, &h, (uint32_t)h.n_part); - for (int64_t g = n_groups; g > 0; g--) h.of[g] = h.of[g - 1]; - h.of[0] = 0; - /* Key table filled in group order, exactly as the serial build does: - * the persisted index is then the same bytes whatever the core count. */ - for (int64_t g = 0; g < n_groups; g++) { - uint64_t slot = mix64((uint64_t)h.gk[g]) & h.tmask; - while (h.tbl[slot] != 0) slot = (slot + 1) & h.tmask; - h.tbl[slot] = g + 1; + if (known) { + cap = next_pow2((uint64_t)(n_groups < 4 ? 8 : 2 * n_groups)); + if (cap < 8) cap = 8; + if (!hb_dst_open(d, aw, n_keys, n_groups, cap)) goto done; + hb_sweep_init(&sw, cap, d->zeroed); + } else { + d->gkeys = ray_vec_new(RAY_I64, n_keys > 0 ? n_keys : 1); + d->offs = ray_vec_new(aw, n_keys + 1); + d->rows = ray_vec_new(aw, n_keys > 0 ? n_keys : 1); + if (!d->gkeys || RAY_IS_ERR(d->gkeys) || !d->offs || RAY_IS_ERR(d->offs) || + !d->rows || RAY_IS_ERR(d->rows)) goto done; + } + h.gk = (int64_t*)ray_data(d->gkeys); h.offs = d->offs; h.rows = d->rows; + + /* 3: partitions in batches: dedupe, store, and the batch's groups into + * the slot table while they are at hand */ + for (int64_t p = 0, q; p < h.n_part; p = q) { + q = one ? h.n_part : hb_batch_end(&h, p, max_batch, batch_rows); + if (!one && !hb_dedupe_batch(&h, pool, par, p, q)) goto done; + int64_t g_lo = ng_run; + for (int64_t i = 0; i < q - p; i++) { h.part[i].g0 = ng_run; ng_run += h.part[i].ng; } + if (par && q - p > 1) ray_pool_dispatch_n(pool, hb_emit, &h, (uint32_t)(q - p)); + else for (int64_t i = 0; i < q - p; i++) hb_emit(&h, 0, i, i + 1); + /* an interrupted dispatch skips tasks: their partitions are still + * held and their outputs unwritten */ + for (int64_t i = 0; i < q - p; i++) hb_part_free(&h.part[i]); + if (hb_stopped(pool)) goto done; + if (known && !hb_sweep(&sw, d->table, h.gk, g_lo, ng_run, pool)) goto done; + /* The batch's key words and row ids are not read again: past the + * watermark their pages leave the spill files now instead of being + * written back, and make room for the arrays still to come. */ + ray_raw_discard(h.kw, (size_t)kw_done * 8, (size_t)h.part_off[q] * 8); + ray_raw_discard(h.rid, (size_t)(kw_done * es), (size_t)(h.part_off[q] * es)); + kw_done = h.part_off[q]; + } + if (known && ng_run != n_groups) goto done; /* the counts disagree: never */ + n_groups = ng_run; + hx_set(d->offs, n_groups, n_keys); + d->gkeys->len = n_groups; d->offs->len = n_groups + 1; d->rows->len = n_keys; + ray_free_raw(h.kw); h.kw = NULL; + ray_free_raw(h.rid); h.rid = NULL; + if (tr) { + ray_hash_trace_add(tr, RAY_HXT_GROUPS, tm, n_keys * (8 + es) + n_groups * 8 + + (n_groups + 1) * es + n_keys * es + (known ? (int64_t)cap * es : 0)); + tm = ray_hash_trace_mark(); + } + + /* 4: the slot table, unless swept batch by batch above */ + if (!known) { + cap = next_pow2((uint64_t)(n_groups < 4 ? 8 : 2 * n_groups)); + if (cap < 8) cap = 8; + d->table = ray_vec_new(aw, (int64_t)cap); + if (!d->table || RAY_IS_ERR(d->table)) goto done; + d->table->len = (int64_t)cap; + hb_sweep_init(&sw, cap, false); + if (!hb_sweep(&sw, d->table, h.gk, 0, n_groups, pool)) goto done; } - if (ray_interrupted()) { ok = false; goto done; } - - *gkeys_out = gkeys; *offs_out = offs; *rows_out = rows; *table_out = table; - *mask_out = h.tmask; *n_keys_out = n_keys; *n_groups_out = n_groups; + hb_sweep_finish(&sw, d->table, n_groups); + *mask_out = cap - 1; + ok = true; done: + if (h.part) + for (int64_t i = 0; i < max_batch; i++) hb_part_free(&h.part[i]); + ray_free_raw(h.cnt); ray_free_raw(h.part_off); ray_free_raw(h.part); + ray_free_raw(h.kw); ray_free_raw(h.rid); ray_free_raw(h.part_ng); if (!ok) { - if (gkeys && !RAY_IS_ERR(gkeys)) ray_release(gkeys); - if (offs && !RAY_IS_ERR(offs)) ray_release(offs); - if (rows && !RAY_IS_ERR(rows)) ray_release(rows); - if (table && !RAY_IS_ERR(table)) ray_release(table); + hb_dst_drop(d); + return -1; } - ray_sys_free(h.kw); ray_sys_free(h.pr); ray_sys_free(h.lg); - ray_sys_free(h.gfirst); ray_sys_free(h.gcount); ray_sys_free(h.cnt); - ray_sys_free(h.part_off); ray_sys_free(h.ng_p); ray_sys_free(h.bits); - ray_sys_free(h.blk_rank); - return ok; + if (!known) { + ray_t *g0 = d->gkeys, *o0 = d->offs; + d->gkeys = hb_trim(d->gkeys, n_groups, n_keys); + d->offs = hb_trim(d->offs, n_groups + 1, n_keys + 1); + if (tr) { + int64_t mv = n_groups * 8 + (int64_t)cap * es; /* the sweep */ + if (d->gkeys != g0) mv += 2 * n_groups * 8; + if (d->offs != o0) mv += 2 * (n_groups + 1) * es; + ray_hash_trace_add(tr, RAY_HXT_TABLE, tm, mv); + } + } + if (tr) { tr->n_keys = n_keys; tr->n_groups = n_groups; } + *n_keys_out = n_keys; *n_groups_out = n_groups; + return 1; } ray_t* ray_index_attach_hash(ray_t** vp) { @@ -1819,33 +2308,33 @@ ray_t* ray_index_attach_hash(ray_t** vp) { int64_t n = v->len; ray_t* table = NULL; uint64_t mask = 0; - { - ray_t *pg = NULL, *po = NULL, *pr = NULL, *pt = NULL; - int64_t pk = 0, pn = 0; + if (!is_str) { + hb_dst_t d; + memset(&d, 0, sizeof(d)); uint64_t pm = 0; - if (!is_str && hash_build_par(v, &pg, &po, &pr, &pt, &pm, &pk, &pn)) { - if (ray_interrupted()) { - ray_release(pg); ray_release(po); ray_release(pr); ray_release(pt); - return ray_error("cancel", "interrupted"); - } - ray_t* idx = ray_index_alloc(RAY_IDX_HASH, v->type, n); - if (!idx || RAY_IS_ERR(idx)) { - ray_release(pg); ray_release(po); ray_release(pr); ray_release(pt); - return idx ? idx : ray_error("oom", NULL); - } - ray_index_t* ix = ray_index_payload(idx); - ix->u.hash.table = pt; - ix->u.hash.gkeys = pg; - ix->u.hash.offs = po; - ix->u.hash.rows = pr; - ix->u.hash.mask = pm; - ix->u.hash.n_keys = pk; - ix->u.hash.n_groups = pn; - ix->u.hash.order_sym = -1; - return attach_finalize(v, idx); + int64_t pk = 0, pn = 0; + if (hash_build_part(v, &d, &pm, &pk, &pn, NULL) < 0) + return hb_stopped(ray_pool_get()) ? ray_error("cancel", "interrupted") + : ray_error("oom", NULL); + ray_t* idx = ray_index_alloc(RAY_IDX_HASH, v->type, n); + if (!idx || RAY_IS_ERR(idx)) { + hb_dst_drop(&d); + return idx ? idx : ray_error("oom", NULL); } - } - /* Build-time capacity: sized by rows for O(1) inserts. */ + ray_index_t* ix = ray_index_payload(idx); + ix->u.hash.table = d.table; + ix->u.hash.gkeys = d.gkeys; + ix->u.hash.offs = d.offs; + ix->u.hash.rows = d.rows; + ix->u.hash.mask = pm; + ix->u.hash.n_keys = pk; + ix->u.hash.n_groups = pn; + ix->u.hash.order_sym = -1; + ix->markers |= RAY_MARK_HASH_HIGH; + return attach_finalize(v, idx); + } + /* STR: a serial walk, groups numbered by first occurrence. Build-time + * capacity: sized by rows for O(1) inserts. */ uint64_t bcap = next_pow2((uint64_t)(n < 4 ? 8 : 2 * n)); if (bcap < 8) bcap = 8; uint64_t bmask = bcap - 1; @@ -1983,6 +2472,7 @@ ray_t* ray_index_attach_hash(ray_t** vp) { ix->u.hash.n_keys = n_keys; ix->u.hash.n_groups = n_groups; ix->u.hash.order_sym = -1; + hx_narrow_payload(ix); return attach_finalize(v, idx); @@ -1994,6 +2484,44 @@ ray_t* ray_index_attach_hash(ray_t** vp) { return ray_error("cancel", "interrupted"); } +ray_err_t ray_index_hash_build_region(ray_t* v, ray_index_region_fn map, void* ctx, + ray_hash_trace_t* tr) { + if (!v || RAY_IS_ERR(v) || !map) return RAY_ERR_DOMAIN; + if (!ray_is_vec(v) || (v->attrs & RAY_ATTR_SLICE) || + (numeric_elem_size(v->type) == 0 && v->type != RAY_SYM)) + return RAY_ERR_NYI; + hb_dst_t d; + memset(&d, 0, sizeof(d)); + d.map = map; d.ctx = ctx; + uint64_t mask = 0; + int64_t n_keys = 0, n_groups = 0; + if (hash_build_part(v, &d, &mask, &n_keys, &n_groups, tr) < 0) + return d.err != RAY_OK ? d.err + : hb_stopped(ray_pool_get()) ? RAY_ERR_CANCEL : RAY_ERR_OOM; + /* The head as ray_index_attach_hash fills it: the parent's aux and + * HAS_NULLS snapshot — the aux it had before any index of its own, which + * an attach drops first. */ + ray_index_t ix; + memset(&ix, 0, sizeof(ix)); + ix.kind = RAY_IDX_HASH; + ix.parent_type = v->type; + ix.built_for_len = v->len; + ix.markers = RAY_MARK_HASH_HIGH; + bool has_ix = (v->attrs & RAY_ATTR_HAS_INDEX) && v->index && !RAY_IS_ERR(v->index); + memcpy(ix.saved_aux, has_ix ? ray_index_payload(v->index)->saved_aux : v->aux, 16); + ix.saved_attrs = v->attrs & RAY_ATTR_HAS_NULLS; + ix.u.hash.table = d.table; + ix.u.hash.gkeys = d.gkeys; + ix.u.hash.offs = d.offs; + ix.u.hash.rows = d.rows; + ix.u.hash.mask = mask; + ix.u.hash.n_keys = n_keys; + ix.u.hash.n_groups = n_groups; + ix.u.hash.order_sym = -1; + idx_inline_head(d.base, &ix); + return RAY_OK; +} + /* -------------------------------------------------------------------------- * Hash-index point-lookup probe — public entry point for the eq-filter * fast path (ray_index_hash_eq_rowsel). @@ -2084,11 +2612,11 @@ static ray_index_t* hash_probe_setup(ray_t* col, int64_t key, int64_t kw = (col->type == RAY_SYM) ? key : (int64_t)hash_key_bits(numeric_elem_size(col->type), key); - uint64_t slot = mix64((uint64_t)kw) & ix->u.hash.mask; - const int64_t* tbl = (const int64_t*)ray_data(ix->u.hash.table); + uint64_t slot = hx_home(ix, mix64((uint64_t)kw)); + const ray_t* tab = ix->u.hash.table; const int64_t* gk = (const int64_t*)ray_data(ix->u.hash.gkeys); for (;;) { - int64_t gp1 = tbl[slot]; + int64_t gp1 = hx_get(tab, slot); if (gp1 == 0) break; /* key absent */ if (gk[gp1 - 1] == kw) { *gid = gp1 - 1; break; } slot = (slot + 1) & ix->u.hash.mask; @@ -2112,16 +2640,16 @@ static ray_index_t* hash_probe_setup_str(ray_t* col, const char* p, size_t l, !ix->u.hash.offs || !ix->u.hash.rows) return NULL; int64_t kw = (int64_t)str_key_word(p, l); - uint64_t slot = mix64((uint64_t)kw) & ix->u.hash.mask; - const int64_t* tbl = (const int64_t*)ray_data(ix->u.hash.table); + uint64_t slot = hx_home(ix, mix64((uint64_t)kw)); + const ray_t* tab = ix->u.hash.table; const int64_t* gk = (const int64_t*)ray_data(ix->u.hash.gkeys); - const int64_t* of = (const int64_t*)ray_data(ix->u.hash.offs); - const int64_t* rw = (const int64_t*)ray_data(ix->u.hash.rows); + const ray_t* ofv = ix->u.hash.offs; + const ray_t* rwv = ix->u.hash.rows; for (;;) { - int64_t gp1 = tbl[slot]; + int64_t gp1 = hx_get(tab, slot); if (gp1 == 0) break; /* key absent */ if (gk[gp1 - 1] == kw && - str_row_eq_bytes(col, rw[of[gp1 - 1]], p, l)) { *gid = gp1 - 1; break; } + str_row_eq_bytes(col, hx_get(rwv, hx_get(ofv, gp1 - 1)), p, l)) { *gid = gp1 - 1; break; } slot = (slot + 1) & ix->u.hash.mask; } return ix; @@ -2235,7 +2763,8 @@ static int hash_match_cmp_i64(const void* a, const void* b) { * over a column of n rows. Returns fresh rowsel (rc=1) or NULL on OOM. * mcnt==0 yields a valid all-NONE rowsel, NOT NULL — NULL means "no fast * path" to every consumer (idxop.h contract). */ -static ray_t* rowsel_from_sorted_ids(int64_t n, const int64_t* ids, int64_t mcnt) { +static inline __attribute__((always_inline)) +ray_t* rowsel_sorted_body(int64_t n, ray_idx_rows_t ids, int64_t mcnt) { ray_t* block = ray_rowsel_new(n, mcnt, mcnt); if (!block) return NULL; @@ -2274,7 +2803,7 @@ static ray_t* rowsel_from_sorted_ids(int64_t n, const int64_t* ids, int64_t mcnt int64_t seg_end = seg_start + RAY_MORSEL_ELEMS; if (seg_end > n) seg_end = n; int64_t mi0 = mi; - while (mi < mcnt && ids[mi] < seg_end) mi++; + while (mi < mcnt && ray_idx_rows_at(ids, mi) < seg_end) mi++; int64_t pc = mi - mi0; if (pc == 0) continue; /* NONE — preset by memset */ if (pc == seg_end - seg_start) { @@ -2283,7 +2812,7 @@ static ray_t* rowsel_from_sorted_ids(int64_t n, const int64_t* ids, int64_t mcnt seg_flags[s] = RAY_SEL_MIX; for (int64_t i = mi0; i < mi; i++) idx_arr[cum + (uint32_t)(i - mi0)] = - (uint16_t)(ids[i] - seg_start); + (uint16_t)(ray_idx_rows_at(ids, i) - seg_start); cum += (uint32_t)pc; } } @@ -2295,6 +2824,13 @@ static ray_t* rowsel_from_sorted_ids(int64_t n, const int64_t* ids, int64_t mcnt return block; } +static ray_t* rowsel_from_sorted_ids(int64_t n, const int64_t* ids, int64_t mcnt) { + return rowsel_sorted_body(n, (ray_idx_rows_t){ ids, false }, mcnt); +} +static ray_t* rowsel_from_sorted_rows(int64_t n, ray_idx_rows_t ids, int64_t mcnt) { + return ids.narrow ? rowsel_sorted_body(n, (ray_idx_rows_t){ ids.p, true }, mcnt) + : rowsel_sorted_body(n, (ray_idx_rows_t){ ids.p, false }, mcnt); +} /* Public wrapper: build an all-NONE rowsel for n rows. Returns NULL on OOM. */ ray_t* ray_index_empty_rowsel(int64_t n) { @@ -2318,13 +2854,12 @@ ray_t* ray_index_hash_eq_rowsel(ray_t* col, int64_t key) { * it to the rowsel builder directly. Group size is known up front; * a dense key (where the SIMD scan would win) returns NULL with zero * wasted work instead of the chain-walk budget the old layout needed. */ - const int64_t* of = (const int64_t*)ray_data(ix->u.hash.offs); - const int64_t* rw = (const int64_t*)ray_data(ix->u.hash.rows); - int64_t gsz = of[gid + 1] - of[gid]; + const ray_t* ofv = ix->u.hash.offs; + int64_t gsz = hx_get(ofv, gid + 1) - hx_get(ofv, gid); if (gsz > 64 && gsz > (n >> 3)) return NULL; /* dense: fall through to the scan path */ - return rowsel_from_sorted_ids(n, rw + of[gid], gsz); + return rowsel_from_sorted_rows(n, hx_rows(ix->u.hash.rows, hx_get(ofv, gid)), gsz); } /* -------------------------------------------------------------------------- @@ -2633,8 +3168,8 @@ ray_t* ray_index_in_rowsel(ray_t* col, ray_t* set_vec) { if (!gids) { ray_release(set_hdr); return NULL; } int64_t total = 0; - const int64_t* of = NULL; - const int64_t* rw = NULL; + const ray_t* ofv = NULL; + const ray_t* rwv = NULL; { ray_index_t* ix = ray_index_payload(col->index); if (!ix->u.hash.table || !ix->u.hash.gkeys || @@ -2643,8 +3178,8 @@ ray_t* ray_index_in_rowsel(ray_t* col, ray_t* set_vec) { ray_release(set_hdr); return NULL; } - of = (const int64_t*)ray_data(ix->u.hash.offs); - rw = (const int64_t*)ray_data(ix->u.hash.rows); + ofv = ix->u.hash.offs; + rwv = ix->u.hash.rows; int es = numeric_elem_size(col->type); int64_t ngid = 0; for (int64_t si = 0; si < set_len; si++) { @@ -2652,18 +3187,18 @@ ray_t* ray_index_in_rowsel(ray_t* col, ray_t* set_vec) { int64_t kw = col_is_sym ? key : (int64_t)hash_key_bits(es, key); int64_t gid = -1; - uint64_t slot = mix64((uint64_t)kw) & ix->u.hash.mask; - const int64_t* tbl = (const int64_t*)ray_data(ix->u.hash.table); + uint64_t slot = hx_home(ix, mix64((uint64_t)kw)); + const ray_t* tab = ix->u.hash.table; const int64_t* gk = (const int64_t*)ray_data(ix->u.hash.gkeys); for (;;) { - int64_t gp1 = tbl[slot]; + int64_t gp1 = hx_get(tab, slot); if (gp1 == 0) break; if (gk[gp1 - 1] == kw) { gid = gp1 - 1; break; } slot = (slot + 1) & ix->u.hash.mask; } if (gid >= 0) { gids[ngid++] = gid; - total += of[gid + 1] - of[gid]; + total += hx_get(ofv, gid + 1) - hx_get(ofv, gid); } } set_len = ngid; @@ -2690,8 +3225,8 @@ ray_t* ray_index_in_rowsel(ray_t* col, ray_t* set_vec) { int64_t mcnt = 0; for (int64_t si = 0; si < set_len; si++) { int64_t gid = gids[si]; - int64_t gsz = of[gid + 1] - of[gid]; - memcpy(matches + mcnt, rw + of[gid], (size_t)gsz * sizeof(int64_t)); + int64_t gsz = hx_get(ofv, gid + 1) - hx_get(ofv, gid); + hx_copy_rows(matches + mcnt, rwv, hx_get(ofv, gid), gsz); mcnt += gsz; } scratch_free(gid_hdr); @@ -3609,8 +4144,9 @@ static void index_set_order_sym(ray_t* v, int64_t order_sym) { } static ray_t* attach_backing_index_carry_markers(ray_t* v, ray_t* (*fn)(ray_t**)) { + /* The rebuilt table keeps its own home rule. */ uint8_t carry = (v && !RAY_IS_ERR(v) && ray_index_has(v)) - ? ray_index_payload(v->index)->markers : 0; + ? (uint8_t)(ray_index_payload(v->index)->markers & ~RAY_MARK_HASH_HIGH) : 0; int64_t order_sym = index_order_sym(v); ray_t* w = attach_via(v, fn); if (w && !RAY_IS_ERR(w) && carry && (w->attrs & RAY_ATTR_HAS_INDEX)) @@ -3725,9 +4261,7 @@ int64_t ray_index_find_row(ray_t* col, int64_t key) { /* CSR: rows are ascending within the group — first slice entry IS the * minimum matching row id. O(1). */ - const int64_t* of = (const int64_t*)ray_data(ix->u.hash.offs); - const int64_t* rw = (const int64_t*)ray_data(ix->u.hash.rows); - return rw[of[gid]]; + return hx_get(ix->u.hash.rows, hx_get(ix->u.hash.offs, gid)); } /* Public wrapper over the internal sorted-ids rowsel builder — consult @@ -3776,7 +4310,7 @@ int64_t ray_index_sym_slices(ray_t* col, ray_t* keys, int64_t k = 0; if (kind == RAY_IDX_HASH) { for (int64_t i = 0; i < nd; i++) { - const int64_t* rows = NULL; + ray_idx_rows_t rows = { NULL, false }; int64_t n = 0; int hit = ray_index_hash_group(col, doms[i], &rows, &n); if (hit < 0) { ray_free(dhdr); ray_free(shdr); return -1; } @@ -3802,7 +4336,7 @@ int64_t ray_index_sym_slices(ray_t* col, ray_t* keys, int64_t pdom = ray_read_sym(pk, p, RAY_SYM, pkeys->attrs); if (pdom != doms[i]) continue; if (pl[p] > 0) { - sl[k].dom = doms[i]; sl[k].rows = NULL; + sl[k].dom = doms[i]; sl[k].rows = (ray_idx_rows_t){ NULL, false }; sl[k].first = ps[p]; sl[k].n = pl[p]; k++; } break; @@ -3820,9 +4354,13 @@ ray_t* ray_index_rowsel_from_ids(int64_t nrows, const int64_t* ids, return rowsel_from_sorted_ids(nrows, ids, n); } +ray_t* ray_index_rowsel_from_rows(int64_t nrows, ray_idx_rows_t ids, int64_t n) { + return rowsel_from_sorted_rows(nrows, ids, n); +} + int ray_index_hash_group(ray_t* col, int64_t key, - const int64_t** rows_out, int64_t* n_out) { - *rows_out = NULL; + ray_idx_rows_t* rows_out, int64_t* n_out) { + *rows_out = (ray_idx_rows_t){ NULL, false }; *n_out = 0; if (!idx_fresh(col, RAY_IDX_HASH)) return -1; /* A STR hash is byte-keyed: an int64 key is not a probe of it, and @@ -3836,10 +4374,9 @@ int ray_index_hash_group(ray_t* col, int64_t key, return hash_key_in_range(col->type, key) ? -1 : 0; } if (gid < 0) return 0; - const int64_t* of = (const int64_t*)ray_data(ix->u.hash.offs); - const int64_t* rw = (const int64_t*)ray_data(ix->u.hash.rows); - *rows_out = rw + of[gid]; - *n_out = of[gid + 1] - of[gid]; + const ray_t* ofv = ix->u.hash.offs; + *rows_out = hx_rows(ix->u.hash.rows, hx_get(ofv, gid)); + *n_out = hx_get(ofv, gid + 1) - hx_get(ofv, gid); return 1; } @@ -3895,9 +4432,7 @@ int64_t ray_index_find_atom(ray_t* col, ray_t* a) { ray_index_t* ix = hash_probe_setup_str(col, ray_str_ptr(a), ray_str_len(a), &gid); if (!ix) return -2; if (gid < 0) return -1; - const int64_t* of = (const int64_t*)ray_data(ix->u.hash.offs); - const int64_t* rw = (const int64_t*)ray_data(ix->u.hash.rows); - return rw[of[gid]]; + return hx_get(ix->u.hash.rows, hx_get(ix->u.hash.offs, gid)); } default: { int64_t k = 0; @@ -3943,9 +4478,7 @@ int ray_index_find_vec(ray_t* col, ray_t* nd, int64_t* out, bool* any_miss) { ray_index_t* ix = hash_probe_setup_str(col, p, l, &gid); if (!ix) return 0; if (gid < 0) { out[i] = NULL_I64; miss = true; continue; } - const int64_t* of = (const int64_t*)ray_data(ix->u.hash.offs); - const int64_t* rw = (const int64_t*)ray_data(ix->u.hash.rows); - out[i] = rw[of[gid]]; + out[i] = hx_get(ix->u.hash.rows, hx_get(ix->u.hash.offs, gid)); } } else { /* Integer-family column and needles only: float equality (NaN, -0) @@ -3986,12 +4519,15 @@ void ray_index_carry_append(ray_t* src, ray_t* dst) { if (add > INT64_MAX - og || add > INT64_MAX - ok) return; /* no signed overflow below */ bool is_str = (t == RAY_STR); + /* Built in the width they end in: narrow while every value (at most + * n1) fits 32 bits, as hx_narrow would leave them. */ + int8_t aw = n1 <= (int64_t)UINT32_MAX ? RAY_I32 : RAY_I64; ray_t* gkeys = ray_vec_new(RAY_I64, og + add > 0 ? og + add : 1); - ray_t* offs = ray_vec_new(RAY_I64, og + add + 1); - ray_t* rows = ray_vec_new(RAY_I64, ok + add > 0 ? ok + add : 1); + ray_t* offs = ray_vec_new(aw, og + add + 1); + ray_t* rows = ray_vec_new(aw, ok + add > 0 ? ok + add : 1); uint64_t cap = next_pow2((uint64_t)(og + add < 4 ? 8 : 2 * (og + add))); if (cap < 8) cap = 8; - ray_t* table = ray_vec_new(RAY_I64, (int64_t)cap); + ray_t* table = ray_vec_new(aw, (int64_t)cap); if (!gkeys || RAY_IS_ERR(gkeys) || !offs || RAY_IS_ERR(offs) || !rows || RAY_IS_ERR(rows) || !table || RAY_IS_ERR(table)) { if (gkeys && !RAY_IS_ERR(gkeys)) ray_release(gkeys); @@ -4001,22 +4537,20 @@ void ray_index_carry_append(ray_t* src, ray_t* dst) { return; } int64_t* gk = (int64_t*)ray_data(gkeys); - int64_t* of = (int64_t*)ray_data(offs); - int64_t* rw = (int64_t*)ray_data(rows); - int64_t* tbl = (int64_t*)ray_data(table); uint64_t mask = cap - 1; memcpy(gk, ray_data(sx->u.hash.gkeys), (size_t)og * sizeof(int64_t)); - memcpy(of, ray_data(sx->u.hash.offs), (size_t)(og + 1) * sizeof(int64_t)); - memcpy(rw, ray_data(sx->u.hash.rows), (size_t)ok * sizeof(int64_t)); + hx_copy_into(offs, sx->u.hash.offs, og + 1); + hx_copy_into(rows, sx->u.hash.rows, ok); if (cap == sx->u.hash.mask + 1) { /* Same capacity: the old slots are valid as they are. */ - memcpy(tbl, ray_data(sx->u.hash.table), (size_t)cap * sizeof(int64_t)); + hx_copy_into(table, sx->u.hash.table, (int64_t)cap); } else { - memset(tbl, 0, (size_t)cap * sizeof(int64_t)); + /* Re-placed under src's home rule: its markers carry over. */ + memset(ray_data(table), 0, (size_t)cap * (size_t)ray_elem_size(aw)); for (int64_t g = 0; g < og; g++) { - uint64_t slot = mix64((uint64_t)gk[g]) & mask; - while (tbl[slot] != 0) slot = (slot + 1) & mask; - tbl[slot] = g + 1; + uint64_t slot = hx_home_m(sx->markers, mask, mix64((uint64_t)gk[g])); + while (hx_get(table, (int64_t)slot) != 0) slot = (slot + 1) & mask; + hx_set(table, (int64_t)slot, g + 1); } } @@ -4025,22 +4559,22 @@ void ray_index_carry_append(ray_t* src, ray_t* dst) { int64_t ng = og, nk = ok; for (int64_t r = n0; r < n1; r++) { int64_t kw = (int64_t)hash_row_key_word(dst, base, r); - uint64_t slot = mix64((uint64_t)kw) & mask; + uint64_t slot = hx_home_m(sx->markers, mask, mix64((uint64_t)kw)); for (;;) { - int64_t gp1 = tbl[slot]; + int64_t gp1 = hx_get(table, (int64_t)slot); if (gp1 == 0) break; if (gk[gp1 - 1] == kw && - (!is_str || str_rows_eq(dst, rw[of[gp1 - 1]], r))) { + (!is_str || str_rows_eq(dst, hx_get(rows, hx_get(offs, gp1 - 1)), r))) { ray_release(gkeys); ray_release(offs); ray_release(rows); ray_release(table); return; /* repeated key: not carried */ } slot = (slot + 1) & mask; } - tbl[slot] = ng + 1; + hx_set(table, (int64_t)slot, ng + 1); gk[ng] = kw; - rw[nk] = r; - of[ng + 1] = nk + 1; + hx_set(rows, nk, r); + hx_set(offs, ng + 1, nk + 1); ng++; nk++; } gkeys->len = ng; offs->len = ng + 1; rows->len = nk; table->len = (int64_t)cap; diff --git a/src/ops/idxop.h b/src/ops/idxop.h index 87d16c374..2244bf893 100644 --- a/src/ops/idxop.h +++ b/src/ops/idxop.h @@ -97,6 +97,11 @@ typedef enum { * passenger index by pointer. Clear = heap-resident index (freed normally), * including a runtime-built index attached to an mmap'd column. */ #define RAY_MARK_MMAP 0x02 +/* Hash index whose slot table takes a key's home slot from the TOP bits of + * its mixed hash (the partitioned builder); clear = the low bits, as every + * table built before it. Fixed for the life of the table: a rebuild picks + * its own. */ +#define RAY_MARK_HASH_HIGH 0x04 /* The payload stored inside data[] of a RAY_INDEX ray_t. */ typedef struct { @@ -118,7 +123,10 @@ typedef struct { struct { /* RAY_IDX_HASH — CSR grouped layout */ /* Open-addressing bucket table over DISTINCT keys plus a CSR * (offsets + contiguous row lists) grouping of the rows: - * table[mask+1] slot -> group id + 1 (0 = empty bucket) + * table[mask+1] slot -> group id + 1 (0 = empty bucket); a + * key's home slot is the top bits of its mixed + * hash under RAY_MARK_HASH_HIGH (groups then in + * hash order), else the low bits * gkeys[n_groups] key value per group (i64-canonical; * SYM stores the column-domain id) * offs[n_groups+1] rows[] slice bounds per group @@ -391,6 +399,44 @@ 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); ray_t* ray_index_inline_map(uint8_t* region, int64_t region_size); +/* ── Hash-index build trace (RAY_CSV_TRACE) ── + * Per phase of one build: wall time, major faults, the bytes the process + * read and wrote (/proc/self/io; zero off Linux), and `moved`, the bytes the + * phase's own passes read and write by design (each array a pass reads or + * writes in full, once per pass) — the I/O it costs when nothing fits in + * memory. count: the column read for the partition histogram; bucket: the + * column read again into key words and row ids; distinct: the groups of + * each partition counted; groups: deduped and stored, and the slot table + * filled alongside when its size is known; table: the slot table after the + * groups, and the arrays cut to size; append: the region into the file. */ +enum { RAY_HXT_COUNT, RAY_HXT_BUCKET, RAY_HXT_DISTINCT, + RAY_HXT_GROUPS, RAY_HXT_TABLE, RAY_HXT_APPEND, RAY_HXT_N }; +typedef struct { + int64_t ns[RAY_HXT_N], majflt[RAY_HXT_N], rd[RAY_HXT_N], wr[RAY_HXT_N], moved[RAY_HXT_N]; + int64_t cwr[RAY_HXT_N]; /* dirty bytes dropped before their writeback */ + int64_t n_keys, n_groups; /* the index built */ +} ray_hash_trace_t; +typedef struct { int64_t ns, majflt, rd, wr, cwr; } ray_hash_mark_t; +ray_hash_mark_t ray_hash_trace_mark(void); +/* Phase `ph` ran since `since` and moved `moved` bytes. */ +void ray_hash_trace_add(ray_hash_trace_t* t, int ph, ray_hash_mark_t since, int64_t moved); +/* One line: each phase that ran, `moved` also as a multiple of `col_bytes`. */ +void ray_hash_trace_print(FILE* f, const char* what, const ray_hash_trace_t* t, int64_t col_bytes); + +/* Build the hash index of numeric or SYM vector `v` straight into its + * persisted inline region, without attaching it and without staging the + * arrays in memory: once the region's size is known, `map(ctx, bytes)` + * returns `bytes` of zero-filled writable memory (NULL when it cannot), + * and the build writes there exactly the bytes ray_index_inline_write would + * write for the index ray_index_attach_hash builds on `v`. RAY_ERR_NYI for + * a type the partitioned builder does not take (STR) — nothing was mapped; + * RAY_ERR_IO when map failed, RAY_ERR_OOM / RAY_ERR_CANCEL when the build + * did: the mapped memory, if any, holds no complete region. `tr` (may be + * NULL) collects the phases. */ +typedef uint8_t* (*ray_index_region_fn)(void* ctx, int64_t bytes); +ray_err_t ray_index_hash_build_region(ray_t* v, ray_index_region_fn map, void* ctx, + ray_hash_trace_t* tr); + /* Drop any attached index from *vp. No-op if none. Restores the * pre-attach aux state byte-for-byte. Returns *vp. */ ray_t* ray_index_drop(ray_t** vp); @@ -572,6 +618,24 @@ int ray_index_find_vec(ray_t* col, ray_t* needles, int64_t* out, bool* any_miss) * fails the append. */ void ray_index_carry_append(ray_t* src, ray_t* dst); +/* Row ids borrowed from a hash index: 64-bit, or unsigned 32-bit when the + * index was built narrow (any column below 2^32 rows). Read with + * ray_idx_rows_at. */ +typedef struct { + const void* p; + bool narrow; +} ray_idx_rows_t; + +static inline int64_t ray_idx_rows_at(ray_idx_rows_t r, int64_t i) { + return r.narrow ? (int64_t)((const uint32_t*)r.p)[i] + : ((const int64_t*)r.p)[i]; +} +/* The ids from position `off` on. */ +static inline ray_idx_rows_t ray_idx_rows_from(ray_idx_rows_t r, int64_t off) { + r.p = (const uint8_t*)r.p + off * (r.narrow ? 4 : 8); + return r; +} + /* ===== Hash-index group slice (CSR accessor) ===== * * Resolve `key` to its group's contiguous ascending row-id slice. @@ -579,15 +643,17 @@ void ray_index_carry_append(ray_t* src, ray_t* dst); * value (canonicalized through the storage width like the eq probe). * * Returns: - * 1 → hit: *rows_out points at the ascending row ids, *n_out the size. + * 1 → hit: *rows_out holds the ascending row ids, *n_out the size. * The slice borrows the index payload — valid while the index is. - * 0 → key provably absent (*rows_out NULL, *n_out 0). + * 0 → key provably absent (rows_out->p NULL, *n_out 0). * -1 → not eligible (no fresh hash index / bad key) — caller falls back. */ int ray_index_hash_group(ray_t* col, int64_t key, - const int64_t** rows_out, int64_t* n_out); + ray_idx_rows_t* rows_out, int64_t* n_out); /* Build a rowsel from ASCENDING row ids (empty n=0 is valid). NULL on OOM. */ ray_t* ray_index_rowsel_from_ids(int64_t nrows, const int64_t* ids, int64_t n); +/* Same, from row ids borrowed from an index. */ +ray_t* ray_index_rowsel_from_rows(int64_t nrows, ray_idx_rows_t ids, int64_t n); /* ===== Slice-group resolution (FILTER + GROUP-by-key fusion) ===== * @@ -596,8 +662,8 @@ ray_t* ray_index_rowsel_from_ids(int64_t nrows, const int64_t* ids, int64_t n); * valid while the index is). */ typedef struct { int64_t dom; /* column-domain key id */ - const int64_t* rows; /* ascending row ids (borrowed); NULL if contiguous */ - int64_t first; /* first physical row when rows == NULL */ + ray_idx_rows_t rows; /* ascending row ids (borrowed); .p NULL if contiguous */ + int64_t first; /* first physical row when rows.p == NULL */ int64_t n; /* slice length (> 0) */ } ray_idx_slice_t; diff --git a/src/ops/internal.h b/src/ops/internal.h index a43d05632..3e8e74350 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -47,6 +47,10 @@ #include #include +/* True if every leaf is constant or reduced to a scalar. */ +bool op_tree_is_scalar(ray_graph_t* g, uint32_t id); +bool op_tree_is_atom(ray_graph_t* g, uint32_t id); + /* Borrow only while the symbol table stays read-only through the dispatch * barrier. Workers compare or copy source-domain codes without interning. * File-domain lookup keeps its own publication/lifetime contract. */ @@ -192,6 +196,18 @@ static inline int64_t read_col_i64(const void* data, int64_t row, return (int64_t)((const int32_t*)data)[row]; case RAY_I16: return (int64_t)((const int16_t*)data)[row]; + case RAY_F32: { + /* The 4-byte lane's bits, zero-extended, with -0.0 canonicalised + * to +0.0 the way the F64 group-key readers do (group_key_f64_bits, + * #407): a group hash table stores and compares these bits, so the + * two zeros must read alike. Bit-level, as there, because release + * builds use -fno-signed-zeros. Before this arm F32 fell to the + * one-byte default below, and a multi-core group by an F32 key + * hashed a byte of each value as the key (#760). */ + uint32_t u; memcpy(&u, (const float*)data + row, 4); + if (u == 0x80000000u) u = 0; + return (int64_t)u; + } default: /* RAY_BOOL, RAY_U8 */ return (int64_t)((const uint8_t*)data)[row]; } @@ -208,6 +224,9 @@ static inline void write_col_i64(void* data, int64_t row, int64_t val, ((int32_t*)data)[row] = (int32_t)val; return; case RAY_I16: ((int16_t*)data)[row] = (int16_t)val; return; + case RAY_F32: { + uint32_t u = (uint32_t)val; memcpy((float*)data + row, &u, 4); return; + } default: /* RAY_BOOL, RAY_U8 */ ((uint8_t*)data)[row] = (uint8_t)val; return; } @@ -643,6 +662,15 @@ ray_op_t* graph_alloc_node(ray_graph_t* g); * predicate without going through the full select planner. */ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr); +/* The rows a `where:` keeps, sampled for the distinct-count route gate + * (query.c; exposed for the contract tests): the table rows surviving the + * predicate among CD_GATE_WHERE_SAMPLE sampled ones in *rows, *nrows of + * them, *population the rows the whole predicate would keep. NULL (the + * outputs then describe the whole table) when the predicate names no + * column the gather covers or keeps every sampled row. */ +ray_t* query_cd_gate_where_rows(ray_t* tbl, ray_t* where_expr, int64_t n_table, + const int64_t** rows, int64_t* nrows, int64_t* population); + /* Pointer to trailing bytes after an ext node. */ #define EXT_TRAIL(ext) ((char*)((ext) + 1)) @@ -990,6 +1018,17 @@ void partitioned_gather(ray_pool_t* pool, const int64_t* idx, int64_t n, const uint8_t* esz, int64_t ncols); /* ── filter.c ── */ +/* Scan read-ahead registration (ray_pool_scan_set). exec_scan_add_col adds + * `col` when it is a mapped fixed-width vector of the registration's length + * (the first such column sets it, resident or not) whose pages are not + * already resident, so a warm query registers nothing to read. */ +void exec_scan_init(ray_pool_scan_t* s); +void exec_scan_add_col(ray_pool_scan_t* s, ray_t* col); +/* The running select's filter produced selection `sel` (NULL: every row + * kept, or a compacted table of `kept` rows): request the columns its + * registration held back for it (query.c). */ +void ray_select_scan_filtered(ray_t* sel, int64_t kept); + 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 @@ -1046,6 +1085,8 @@ ray_t* exec_in_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, bool* all_pass); ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input); ray_t* exec_elementwise_binary(ray_graph_t* g, ray_op_t* op, ray_t* lhs, ray_t* rhs); +ray_t* exec_sym_order(uint16_t opcode, ray_t* lhs, ray_t* rhs, + bool l_scalar, bool r_scalar); /* ── sort_exec.c ── */ int sort_cmp(const sort_cmp_ctx_t* ctx, int64_t a, int64_t b); @@ -1809,6 +1850,9 @@ 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); +/* Keep a grouped key column's "may have nulls" flag only when a key value is + * null (vectorised, pool-split scan); see agg_engine.c. */ +void ray_group_key_settle_nulls(ray_t* kc); /* A scalar `where:` predicate holds for every row or none. It needs a truth @@ -1824,4 +1868,7 @@ static inline bool ray_pred_atom_type_ok(int8_t t) { } } +/* Owned merged query dict, or NULL when nested select composition is unsafe. */ +ray_t* ray_select_merge_plan(ray_t* dict); + #endif /* RAY_EXEC_INTERNAL_H */ diff --git a/src/ops/join.c b/src/ops/join.c index 7a53f57f3..4906de103 100644 --- a/src/ops/join.c +++ b/src/ops/join.c @@ -652,15 +652,16 @@ static inline bool join_keys_eq(ray_t* const* l_vecs, ray_t* const* r_vecs, uint ray_t* lc = l_vecs[k]; ray_t* rc = r_vecs[k]; if (!lc || !rc) return false; - /* null == null, null != non-null. This is the rule the rest of the - * runtime already applies to key columns: collection.c's hashset - * folds every null into one bucket (so `distinct` keeps exactly one - * null and `in` matches null against null), group.c folds them into - * one group, and atom_eq answers 1 for two nulls. Joins used to - * reject a null outright, which made `anti-join [c] X X` non-empty - * whenever c held a null and made left-join miss a null-keyed match. - * As-of join keeps its own documented NULLs-never-match rule; it - * does not route through here. */ + /* null == null, null != non-null. Joins used to reject a null + * outright, which made `anti-join [c] X X` non-empty whenever c held + * a null and made left-join miss a null-keyed match. Two nulls pair + * where two values of their key types would be compared: the value + * arms below pair STR only with STR and GUID only with GUID and read + * every other key type as a raw integer, so the nulls follow that + * rule rather than `in`'s (which keeps, say, a date null apart from + * an integer null) — a join must not match 5 to 5 across two key + * types yet refuse their nulls. As-of join keeps its own documented + * NULLs-never-match rule; it does not route through here. */ bool l_null = !nullfree && ray_vec_is_null(lc, l); bool r_null = !nullfree && ray_vec_is_null(rc, r); if (l_null || r_null) { @@ -2432,18 +2433,18 @@ static int asof_lslot_cmp(const void* a, const void* b) { } typedef struct { - const int64_t* rows; + ray_idx_rows_t rows; int64_t start; int64_t n; uint8_t contig; } asof_idx_slice_t; static inline int64_t asof_slice_row(const asof_idx_slice_t* s, int64_t p) { - return s->contig ? s->start + p : s->rows[p]; + return s->contig ? s->start + p : ray_idx_rows_at(s->rows, p); } static int asof_part_group(ray_t* col, int64_t key, asof_idx_slice_t* out) { - out->rows = NULL; + out->rows = (ray_idx_rows_t){ NULL, false }; out->start = 0; out->n = 0; out->contig = 1; @@ -2497,7 +2498,7 @@ static int asof_part_group(ray_t* col, int64_t key, asof_idx_slice_t* out) { } static int asof_index_group(ray_t* col, int64_t key, asof_idx_slice_t* out) { - out->rows = NULL; + out->rows = (ray_idx_rows_t){ NULL, false }; out->start = 0; out->n = 0; out->contig = 0; @@ -2537,14 +2538,14 @@ static bool asof_verify_idx_slices(const asof_idx_slice_t* sl, int32_t n_groups, } /* Per-slice ascending-time verify over a collected probe set (see the - * single-eq index variant below). gsl holds n_groups (grows, gn) pairs. + * single-eq index variant below). gsl holds the n_groups hash slices. * Contiguous slices verify with a sequential scan over rt_time; scattered * ones fall back to the gathered walk. Above the parallel threshold the * pairs are chunked across the pool; each chunk covers the adjacent * pairs (i-1, i) for i in [max(start,1), end) within its slice, so * chunk boundaries re-check the crossing pair and no pair is skipped. * Returns false at the first violation (shared bail flag). */ -typedef struct { const int64_t* grows; int64_t lo, hi; } asof_vchunk_t; +typedef struct { ray_idx_rows_t grows; int64_t lo, hi; } asof_vchunk_t; typedef struct { const asof_vchunk_t* chunks; const int64_t* rt_time; @@ -2559,16 +2560,17 @@ static void asof_verify_fn(void* raw, uint32_t wid, int64_t cstart, for (int64_t ci = cstart; ci < cend; ci++) { if (!*c->ok) return; const asof_vchunk_t* ch = &c->chunks[ci]; - const int64_t* restrict rows = ch->grows; + ray_idx_rows_t rows = ch->grows; int64_t lo = ch->lo, hi = ch->hi; if (lo < 1) lo = 1; bool contig = (hi > lo) && - (rows[hi - 1] - rows[lo - 1] == hi - lo); + (ray_idx_rows_at(rows, hi - 1) - + ray_idx_rows_at(rows, lo - 1) == hi - lo); if (contig) { /* Branchless block accumulation: `bad += (next < cur)` maps to * packed i64 compares (the early-exit form stays scalar), with * a per-block bail so a violation still stops the scan early. */ - const int64_t* restrict tv = t + rows[lo - 1]; + const int64_t* restrict tv = t + ray_idx_rows_at(rows, lo - 1); int64_t n = hi - lo; int64_t bad = 0; for (int64_t b = 0; b < n; b += 4096) { @@ -2577,38 +2579,35 @@ static void asof_verify_fn(void* raw, uint32_t wid, int64_t cstart, bad += (int64_t)(tv[i + 1] < tv[i]); if (bad) { *c->ok = 0; return; } } + } else if (rows.narrow) { + const uint32_t* restrict r = (const uint32_t*)rows.p; + for (int64_t i = lo; i < hi; i++) + if (t[r[i]] < t[r[i - 1]]) { *c->ok = 0; return; } } else { + const int64_t* restrict r = (const int64_t*)rows.p; for (int64_t i = lo; i < hi; i++) - if (t[rows[i]] < t[rows[i - 1]]) { *c->ok = 0; return; } + if (t[r[i]] < t[r[i - 1]]) { *c->ok = 0; return; } } } } #define ASOF_VERIFY_CHUNK 65536 -static bool asof_verify_slices(const int64_t* gsl, int32_t n_groups, +static bool asof_verify_slices(const asof_idx_slice_t* gsl, int32_t n_groups, const int64_t* rt_time, int64_t total_rows) { int64_t n_chunks = 0; for (int32_t g = 0; g < n_groups; g++) - n_chunks += (gsl[2 * g + 1] + ASOF_VERIFY_CHUNK - 1) + n_chunks += (gsl[g].n + ASOF_VERIFY_CHUNK - 1) / ASOF_VERIFY_CHUNK; if (n_chunks <= 0) return true; ray_t* ch_hdr = NULL; asof_vchunk_t* chunks = (asof_vchunk_t*)scratch_alloc(&ch_hdr, (size_t)n_chunks * sizeof(asof_vchunk_t)); - if (!chunks) { - /* OOM — serial gathered walk, no allocation. */ - for (int32_t g = 0; g < n_groups; g++) { - const int64_t* rows = (const int64_t*)(intptr_t)gsl[2 * g]; - int64_t gn = gsl[2 * g + 1]; - for (int64_t p = 1; p < gn; p++) - if (rt_time[rows[p]] < rt_time[rows[p - 1]]) return false; - } - return true; - } + if (!chunks) /* OOM — serial gathered walk, no allocation. */ + return asof_verify_idx_slices(gsl, n_groups, rt_time); int64_t w = 0; for (int32_t g = 0; g < n_groups; g++) { - const int64_t* rows = (const int64_t*)(intptr_t)gsl[2 * g]; - int64_t gn = gsl[2 * g + 1]; + ray_idx_rows_t rows = gsl[g].rows; + int64_t gn = gsl[g].n; for (int64_t lo = 0; lo < gn; lo += ASOF_VERIFY_CHUNK) { int64_t hi = lo + ASOF_VERIFY_CHUNK; if (hi > gn) hi = gn; @@ -2829,21 +2828,8 @@ static bool asof_hash_group_match(uint32_t n_eq, } if (served && !rt_time_sorted && !idx_ordered && verify_rows > 0) { if (ray_index_kind(rt_eq[0]) == RAY_IDX_HASH) { - ray_t* hv_hdr = NULL; - int64_t* hv = (int64_t*)scratch_alloc(&hv_hdr, - (size_t)(n_groups > 0 ? n_groups : 1) * 2 * - sizeof(int64_t)); - if (hv) { - for (int32_t g = 0; g < n_groups; g++) { - hv[2 * g] = (int64_t)(intptr_t)gsl[g].rows; - hv[2 * g + 1] = gsl[g].n; - } - served = asof_verify_slices(hv, n_groups, rt_time, - verify_rows); - scratch_free(hv_hdr); - } else { - served = asof_verify_idx_slices(gsl, n_groups, rt_time); - } + served = asof_verify_slices(gsl, n_groups, rt_time, + verify_rows); } else { served = asof_verify_idx_slices(gsl, n_groups, rt_time); } diff --git a/src/ops/ops.h b/src/ops/ops.h index b86822ec1..1c1955dcd 100644 --- a/src/ops/ops.h +++ b/src/ops/ops.h @@ -547,6 +547,15 @@ typedef struct ray_graph { uint32_t node_id; } cexpr_env[32]; int cexpr_env_top; + /* Lookups stop above this slot while a named helper's body compiles: + * its free names are lexical (globals or columns), never the formals + * of the helper that called it. */ + int cexpr_env_base; + /* Depth of named-helper bodies being inlined. Their text was written + * outside the query, so a literal symbol in them is the symbol, as in + * bytecode; a lambda written inline in the query keeps the query's + * column rule for literals. */ + int cexpr_helper_depth; /* Output aliases of the select being compiled (src/ops/query.c): * the projections compiled so far, in order. A name reference or a @@ -967,7 +976,17 @@ ray_t* ray_lazy_append(ray_t* lazy, uint16_t opcode); * so a literal never captures a lambda/let local and resolution fires only * inside a query. Returns NULL when no query is active. */ ray_t* ray_active_query_table(void); +/* The table a helper called from a query may read columns from: the + * source schema while a projection binds aliases, else the active table. */ +ray_t* ray_query_helper_table(void); +/* Owned: the source column `sym` names, or its cell during a per-row + * evaluation; NULL when it names none. */ +ray_t* ray_query_helper_value(int64_t sym); +/* A builtin the planner lowers row by row: its result over a column-derived + * operand is itself column-derived. */ +bool ray_query_rowwise_builtin(int64_t sym_id); ray_t* ray_active_query_literal(int64_t sym); +bool ray_query_expr_reads_rows(ray_t* expr); #ifdef __cplusplus } diff --git a/src/ops/opt.c b/src/ops/opt.c index dbf2152a9..cfacce669 100644 --- a/src/ops/opt.c +++ b/src/ops/opt.c @@ -457,6 +457,12 @@ static bool fold_binary_const(ray_graph_t* g, ray_op_t* node) { if (!le || !re || !le->literal || !re->literal) return false; if (!ray_is_atom(le->literal) || !ray_is_atom(re->literal)) return false; + /* Symbol ids cannot be constant-folded as ordered integers (#738). */ + if ((node->opcode == OP_LT || node->opcode == OP_LE || + node->opcode == OP_GT || node->opcode == OP_GE) && + (le->literal->type == -RAY_SYM || re->literal->type == -RAY_SYM)) + return false; + double lf = 0.0, rf = 0.0; int64_t li = 0, ri = 0; bool l_is_f64 = false, r_is_f64 = false; @@ -2006,6 +2012,11 @@ static void pass_partition_pruning(ray_graph_t* g, ray_op_t* root) { if (pkey_is_sym != lit_is_sym) { continue; } + /* Raw partition ids have no lexical ordering (#738). Let the + * domain-aware predicate executor select these rows instead. */ + if (pkey_is_sym && (cmp_op == OP_LT || cmp_op == OP_LE || + cmp_op == OP_GT || cmp_op == OP_GE)) + continue; /* Allocate seg_mask bitmap */ uint32_t n_words = (uint32_t)((n_parts + 63) / 64); diff --git a/src/ops/query.c b/src/ops/query.c index 3da90cc8c..390eba172 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -37,6 +37,8 @@ #include "ops/agg_engine.h" /* agg_select_distinct — dict-linked pure-distinct path */ #include "core/runtime.h" /* __VM — per-thread query/eval context */ #include "ops/rowsel.h" +#include "store/col.h" /* ray_col_want_rows — group-gather read-ahead */ +#include "core/pool.h" /* ray_pool_dispatch — the route gate's sampled gather */ #include "ops/fused_group.h" #include "ops/fused_topk.h" #include "ops/hll.h" @@ -709,6 +711,73 @@ static bool table_is_parted(ray_t* tbl) { * name), an atom take with K << nrows, and the result is a flat table * with no LIST columns, dispatch to ray_topk_table — bounded-heap * selection in O(n log K) instead of full sort + gather. */ +/* The sort keys a select names in asc:/desc: — a symbol atom or a symbol + * vector each. Calls fn(name, ctx) per key; stops early on nonzero. */ +static int select_for_each_sort_key(ray_t** dict_elems, int64_t dict_n, + int64_t asc_id, int64_t desc_id, + int (*fn)(int64_t, void*), void* ctx) { + for (int64_t i = 0; i + 1 < dict_n; i += 2) { + int64_t kid = dict_elems[i]->i64; + if (kid != asc_id && kid != desc_id) continue; + ray_t* v = dict_elems[i + 1]; + if (v->type == -RAY_SYM) { + if (fn(v->i64, ctx)) return 1; + } else if (v->type == RAY_SYM) { + for (int64_t k = 0; k < v->len; k++) + if (fn(((int64_t*)ray_data(v))[k], ctx)) return 1; + } + } + return 0; +} + +typedef struct { ray_t* result; ray_t* src; int64_t rows; int64_t added; } carry_ctx_t; + +static int carry_one_sort_key(int64_t name, void* p) { + carry_ctx_t* c = (carry_ctx_t*)p; + if (ray_table_get_col(c->result, name)) return 0; /* output already */ + ray_t* col = ray_table_get_col(c->src, name); + if (!col || col->type < 0 || RAY_IS_PARTED(col->type) || + col->type == RAY_MAPCOMMON || ray_len(col) != c->rows) + return 0; /* not a row column */ + ray_retain(col); + ray_t* r = ray_table_add_col(c->result, name, col); + ray_release(col); + c->result = r; + if (!r || RAY_IS_ERR(r)) return 1; + c->added++; + return 0; +} + +/* Append each asc:/desc: key that names a full-length source column but no + * output column to `result`; *added counts them (they are the tail). */ +static ray_t* select_fallback_carry_sort_keys(ray_t* result, ray_t* src, + ray_t** dict_elems, int64_t dict_n, + int64_t asc_id, int64_t desc_id, + int64_t* added) { + *added = 0; + if (!src || RAY_IS_ERR(src) || src->type != RAY_TABLE || + result->type != RAY_TABLE) + return result; + carry_ctx_t c = { result, src, ray_table_nrows(result), 0 }; + select_for_each_sort_key(dict_elems, dict_n, asc_id, desc_id, + carry_one_sort_key, &c); + *added = c.added; + return c.result; +} + +/* Drop the last `n` columns of a table (the carried sort keys). */ +static ray_t* select_fallback_drop_tail_cols(ray_t* tbl, int64_t n) { + if (!tbl || RAY_IS_ERR(tbl) || tbl->type != RAY_TABLE) return tbl; + int64_t keep = ray_table_ncols(tbl) - n; + if (keep < 0) keep = 0; + ray_t* out = ray_table_new(keep); + for (int64_t c = 0; c < keep && out && !RAY_IS_ERR(out); c++) + out = ray_table_add_col(out, ray_table_col_name(tbl, c), + ray_table_get_col_idx(tbl, c)); + ray_release(tbl); + return out ? out : ray_error("oom", NULL); +} + /* Decoded take: value the CALLER already evaluated (grouped DAG path: it * evaluates take: once to decide the HEAD pushdown). Passing the DECODED form * rather than the ray_t keeps it a stack value with no ownership to leak on the @@ -904,7 +973,7 @@ static ray_t* apply_sort_take(ray_t* result, ray_t** dict_elems, int64_t dict_n, * intermediates one call later. */ return topk; } - if (topk && RAY_IS_ERR(topk)) ray_release(topk); + if (topk && RAY_IS_ERR(topk)) ray_error_free(topk); /* topk == NULL: unsupported config, fall through. */ } } @@ -1096,7 +1165,7 @@ static bool unsorted_positive_take_limit(ray_t** dict_elems, int64_t dict_n, * uniformly by ray_graph_free. * -------------------------------------------------------------------------- */ static ray_op_t* cexpr_env_lookup(ray_graph_t* g, int64_t sym) { - for (int i = g->cexpr_env_top - 1; i >= 0; i--) + for (int i = g->cexpr_env_top - 1; i >= g->cexpr_env_base; i--) if (g->cexpr_env[i].sym == sym) return &g->nodes[g->cexpr_env[i].node_id]; return NULL; @@ -1222,7 +1291,101 @@ static ray_op_t* compile_const_str_expr(ray_graph_t* g, ray_t* expr) { * all previously-returned pointers). The ID is stable; only the * backing address may change. */ +static int expr_contains_call_named(ray_t* expr, const char* name, size_t name_len); + +bool ray_query_rowwise_builtin(int64_t id) { + if (resolve_unary_dag(id) || resolve_binary_dag(id) || resolve_agg_opcode(id)) return true; + /* Forms compile_expr_dag lowers by name rather than through a table. */ + /* reverse/asc/desc reorder a column but keep every row of it. */ + static const char* const names[] = { + "as", "if", "and", "or", "cond", "pow", "substr", "replace", "xbar", "within", + "day", "dayofweek", "dayofyear", "hour", "minute", "month", "second", "year", + "reverse", "asc", "desc", "at", + }; + enum { N = sizeof names / sizeof *names }; + /* Sym ids are only stable within one symbol-table epoch (sym.h). */ + static _Thread_local int64_t ids[N]; + static _Thread_local uint64_t epoch; + if (epoch != ray_sym_epoch() || !epoch) { + for (size_t i = 0; i < N; i++) ids[i] = ray_sym_intern(names[i], strlen(names[i])); + epoch = ray_sym_epoch(); + } + for (size_t i = 0; i < N; i++) if (ids[i] == id) return true; + return false; +} + /* Compile a Rayfall AST expression into a DAG node */ +static bool builtin_named(const ray_t* b, const char* const* names, size_t n); + +/* The set of `(in col set)` over a string column, when it is a list of + * strings — a literal (list "a" "b"), or a name bound to such a list — as + * the string vector it spells, so the membership compiles and probes one + * hash set instead of declining to the per-row evaluator. Elements that are + * not strings are dropped: no string row equals them. NULL when `set` is + * not such a list: a call, an element computed at run time, `list` rebound, + * or a name that is a column, a formal or something other than a list. */ +static ray_t* in_str_set_const(ray_graph_t* g, ray_t* set) { + if (!set) return NULL; + ray_t** e; + int64_t from, n; + if (set->type == -RAY_SYM && !(set->attrs & ATTR_QUOTED)) { + int64_t id = set->i64; + if (cexpr_env_lookup(g, id) || sel_alias_lookup(g, id)) return NULL; + ray_t* v = g->cexpr_helper_depth > 0 ? ray_env_get_lexical_local_callee(id) + : ray_env_get_lexical_local(id); + if (!v) { + if (g->table && g->table->type == RAY_TABLE && ray_table_get_col(g->table, id)) + return NULL; + v = g->cexpr_helper_depth > 0 ? ray_env_get_compiled(id) : ray_env_get(id); + } + if (!v || v->type != RAY_LIST) return NULL; + e = (ray_t**)ray_data(v); + from = 0; + n = ray_len(v); + for (int64_t i = 0; i < n; i++) + if (!e[i] || !ray_is_atom(e[i])) return NULL; + } else { + if (set->type != RAY_LIST || ray_len(set) < 2) return NULL; + e = (ray_t**)ray_data(set); + ray_t* head = e[0]; + if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return NULL; + if (cexpr_env_lookup(g, head->i64)) return NULL; + ray_t* b = g->cexpr_helper_depth > 0 ? ray_env_get_lexical_local_callee(head->i64) + : ray_env_get_lexical_local(head->i64); + if (!b) b = ray_env_get(head->i64); + static const char* const list_fn[] = { "list" }; + if (!builtin_named(b, list_fn, 1)) return NULL; + from = 1; + n = ray_len(set); + for (int64_t i = 1; i < n; i++) { + ray_t* a = e[i]; + if (!a || !ray_is_atom(a)) return NULL; + if (a->type == -RAY_SYM && !(a->attrs & ATTR_QUOTED)) return NULL; /* a name */ + } + } + ray_t* v = ray_vec_new(RAY_STR, n - from); + for (int64_t i = from; i < n && v && !RAY_IS_ERR(v); i++) + if (e[i]->type == -RAY_STR) + v = ray_str_vec_append(v, ray_str_ptr(e[i]), ray_str_len(e[i])); + return v ? v : ray_error("oom", NULL); +} + +/* Is `set` a name that reaches a global value no const node can hold (a + * list, a dict) — not a formal, an alias, a local or a column? */ +static bool in_set_names_global_value(ray_graph_t* g, ray_t* set) { + if (!set || set->type != -RAY_SYM || (set->attrs & ATTR_QUOTED)) return false; + int64_t id = set->i64; + if (ray_sym_is_dotted(id)) return false; + if (cexpr_env_lookup(g, id) || sel_alias_lookup(g, id)) return false; + if (g->cexpr_helper_depth > 0 ? ray_env_get_lexical_local_callee(id) + : ray_env_get_lexical_local(id)) + return false; + if (g->table && g->table->type == RAY_TABLE && ray_table_get_col(g->table, id)) + return false; + ray_t* v = g->cexpr_helper_depth > 0 ? ray_env_get_compiled(id) : ray_env_get(id); + return v && !ray_is_atom(v) && !ray_is_vec(v); +} + ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { if (!expr) return NULL; @@ -1254,7 +1417,8 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { if (bound) return bound; ray_op_t* alias = sel_alias_lookup(g, expr->i64); if (alias) return alias; - ray_t* local = ray_env_get_lexical_local(expr->i64); + ray_t* local = g->cexpr_helper_depth > 0 ? ray_env_get_lexical_local_callee(expr->i64) + : ray_env_get_lexical_local(expr->i64); if (local) { if (ray_is_atom(local)) return ray_const_atom(g, local); if (ray_is_vec(local)) return ray_const_vec(g, local); @@ -1310,7 +1474,10 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { /* Global env: atom literals / typed vectors compile as * const nodes. Lambdas only make sense as call heads * and are handled in the list branch below. */ - ray_t* gv = ray_env_get(expr->i64); + /* Inside a helper's body a free name is the helper's: an `eval` + * window of whoever evaluated the query is not its scope. */ + ray_t* gv = g->cexpr_helper_depth > 0 ? ray_env_get_compiled(expr->i64) + : ray_env_get(expr->i64); if (gv) { if (ray_is_atom(gv)) return ray_const_atom(g, gv); if (ray_is_vec(gv)) return ray_const_vec(g, gv); @@ -1349,6 +1516,11 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { * the rule fires only when a query table is bound. A literal naming no * column stays a const atom node. */ if (expr->type == -RAY_SYM) { + /* Inside a named helper's body a literal symbol is the symbol + * itself, as it is when the helper runs as bytecode: the column + * rule belongs to text written in the query, inline lambdas + * included. */ + if (g->cexpr_helper_depth) return ray_const_atom(g, expr); /* A literal naming an EARLIER PROJECTION of the same select resolves * to it, exactly as the bare name does — and ahead of a source * column of the same name, as the bare name does. The alias store @@ -1386,6 +1558,16 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { ray_t** elems = (ray_t**)ray_data(expr); ray_t* head = elems[0]; + /* A head bound as a value where the text is (a formal of a lambda + * inlined here, a local of the frame the query runs in) is a call + * through that value, however it is spelled (quote, if, count): + * the planner cannot lower it, and the evaluator calls it. */ + if (head && head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && + (cexpr_env_lookup(g, head->i64) || + (g->cexpr_helper_depth > 0 ? ray_env_get_lexical_local_callee(head->i64) + : ray_env_get_lexical_local(head->i64)))) + return NULL; + /* Lambda invocation: `((fn [formals] body) a1 a2 …)`. * β-reduce at the DAG-node level — compile each actual * arg into its own op (in the current env), push the @@ -1450,8 +1632,11 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { cexpr_env_lookup(g, head->i64) == NULL && !(g->table && g->table->type == RAY_TABLE && ray_table_get_col(g->table, head->i64))) { - ray_t* gv = ray_env_get(head->i64); - if (gv && gv->type == RAY_LAMBDA) { + ray_t* gv = g->cexpr_helper_depth > 0 ? ray_env_get_compiled(head->i64) + : ray_env_get(head->i64); + /* Not a closure: its captures are not in the planner's scope, + * and a captured name would resolve to a column or a global. */ + if (gv && gv->type == RAY_LAMBDA && !LAMBDA_CLOSURE(gv)) { ray_t* formals = LAMBDA_PARAMS(gv); ray_t* body_lst = LAMBDA_BODY(gv); if (formals && body_lst && body_lst->type == RAY_LIST && @@ -1468,6 +1653,15 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { actual_ids[i] = a->id; } int64_t* fids = (int64_t*)ray_data(formals); + /* The body was written outside this select and + * outside any helper that calls it: a free name in + * it is a global (or a column), never an output + * alias of the select nor a formal of the calling + * helper. Hide both while the body compiles; the + * actuals above were compiled in the caller's scope + * and keep seeing aliases and formals. */ + int saved_base = g->cexpr_env_base; + g->cexpr_env_base = g->cexpr_env_top; int pushed = 0; for (int64_t i = 0; i < nf; i++) { g->cexpr_env[g->cexpr_env_top].sym = fids[i]; @@ -1475,17 +1669,14 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { g->cexpr_env_top++; pushed++; } - /* The body was written outside this select: a free - * name in it is a global (or a column), never an - * output alias of the select that happens to call - * the lambda. Hide the alias store while the body - * compiles; the actuals above were compiled in the - * projection's own scope and keep seeing aliases. */ int saved_aliases = g->sel_alias_n; g->sel_alias_n = 0; + g->cexpr_helper_depth++; ray_op_t* result = compile_expr_dag(g, body); + g->cexpr_helper_depth--; g->sel_alias_n = saved_aliases; cexpr_env_pop(g, pushed); + g->cexpr_env_base = saved_base; return result; } } @@ -1627,16 +1818,54 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { if (fname_len == 6 && memcmp(fname, "concat", 6) == 0) { ray_op_t* folded = compile_const_str_expr(g, expr); if (folded) return folded; - if (n < 2 || n - 1 > 16) return NULL; - uint32_t arg_ids[16]; + /* One node for up to 255 operands, the executor's limit. */ + if (n < 2 || n - 1 > 255) return NULL; + uint32_t arg_ids[255]; for (int64_t i = 1; i < n; i++) { ray_op_t* a = compile_expr_dag(g, elems[i]); if (!a) return NULL; arg_ids[i - 1] = a->id; } - ray_op_t* args[16]; + ray_op_t* args[255]; for (int64_t i = 0; i < n - 1; i++) args[i] = &g->nodes[arg_ids[i]]; + /* Constant collections keep ordinary concat semantics in a query. + * Scalar text expressions retain the existing string operation. */ + if (n == 3 && args[0]->opcode == OP_CONST && args[1]->opcode == OP_CONST) { + ray_op_ext_t* a = find_ext(g, arg_ids[0]); + ray_op_ext_t* b = find_ext(g, arg_ids[1]); + if (a && b && a->literal && b->literal && + (ray_is_vec(a->literal) || ray_is_vec(b->literal) || + (args[0]->out_type != RAY_SYM && args[0]->out_type != RAY_STR) || + (args[1]->out_type != RAY_SYM && args[1]->out_type != RAY_STR))) { + ray_t* value = ray_concat_fn(a->literal, b->literal); + if (!value) return NULL; + if (RAY_IS_ERR(value)) { + if (!g->compile_err) g->compile_err = value; + else ray_error_free(value); + return NULL; + } + /* The typed membership executor cannot consume a boxed + * mixed-type probe. Leave it to evaluator membership. */ + if (value->type == RAY_LIST) { ray_release(value); return NULL; } + ray_op_t* out = ray_is_atom(value) ? ray_const_atom(g, value) + : ray_const_vec(g, value); + ray_release(value); + return out; + } + } + /* OP_CONCAT is a string kernel. Numeric collection concatenation + * belongs to the whole-column evaluation fallback. */ + for (int64_t i = 0; i < n - 1; i++) { + int8_t t = args[i]->out_type; + if (RAY_IS_PARTED(t)) t = (int8_t)RAY_PARTED_BASETYPE(t); + if (t != RAY_SYM && t != RAY_STR) return NULL; + } + /* Every vector operand must carry source rows. A bound/literal + * vector beside a column is a collection append, not row text. */ + for (int64_t i = 0; i < n - 1; i++) + if (op_tree_is_scalar(g, arg_ids[i]) && + !op_tree_is_atom(g, arg_ids[i])) return NULL; return ray_concat(g, args, (int)(n - 1)); } @@ -1926,7 +2155,21 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { ray_op_t* left = compile_expr_dag(g, elems[1]); if (!left) return NULL; uint32_t left_id = left->id; - ray_op_t* right = compile_expr_dag(g, elems[2]); + ray_op_t* right = NULL; + if ((ctor == ray_in || ctor == ray_not_in) && + left->opcode != OP_CONST && left->out_type == RAY_STR) { + ray_t* sv = in_str_set_const(g, elems[2]); + if (sv && RAY_IS_ERR(sv)) { ray_error_free(sv); return NULL; } + if (sv) { right = ray_const_vec(g, sv); ray_release(sv); if (!right) return NULL; } + } + /* A set held in a global list (or another value no const + * node holds) is the evaluator's to read: compiled, the + * name became a scan of a column that is not there, and + * `(in y S)` failed with "column 'S' not found". */ + if (!right && (ctor == ray_in || ctor == ray_not_in) && + in_set_names_global_value(g, elems[2])) + return NULL; + if (!right) right = compile_expr_dag(g, elems[2]); if (!right) return NULL; left = &g->nodes[left_id]; if ((ctor == ray_and || ctor == ray_or) && @@ -2028,17 +2271,841 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { * Column-membership scoped and query-only by construction — see * ray_active_query_table. */ static _Thread_local ray_t* g_active_query_table = NULL; +/* The source schema while a projection fallback binds output aliases into + * its evaluation table; a helper's free names read columns from here. */ +static _Thread_local ray_t* g_query_source_table = NULL; +/* Dependency classification is stable across group slices. Cache it for + * one grouped evaluation so computed text does not compile per group. */ +typedef struct { + ray_t* table; + ray_t* exprs[64]; + bool reads_rows[64]; + int n; +} query_dependency_cache_t; +static _Thread_local query_dependency_cache_t* g_query_dependencies; + +typedef struct { int64_t name; ray_t* expr; } query_inline_binding_t; + +/* A builtin whose call can move from a helper body into the query + * expression without changing what the program does: deterministic, no + * effects, no input but its arguments, and never calling back into user + * code. Everything the planner lowers qualifies, plus the collection + * verbs the fallback evaluates whole; anything else keeps the call. */ +static bool query_inline_pure_builtin(int64_t id) { + static const char* const pure[] = { + "quote", "concat", "distinct", "reverse", "asc", "desc", "iasc", "idesc", "rank", + "til", "take", "drop", "enlist", "list", "count", "first", "last", "at", "in", + "not-in", "except", "union", "sect", "where", "raze", "flip", "key", "value", + "type", "sublist", "differ", "fills", "group", "upper", "lower", "trim", "strlen", + "like", "ilike", "str-find", "nil?", + }; + enum { NPURE = sizeof pure / sizeof *pure }; + /* Interned once per symbol-table epoch (sym.h): this runs for every + * call node of every helper, and ids do not survive a re-init. */ + static _Thread_local int64_t pure_ids[NPURE]; + static _Thread_local uint64_t epoch; + if (epoch != ray_sym_epoch() || !epoch) { + for (size_t i = 0; i < NPURE; i++) pure_ids[i] = ray_sym_intern(pure[i], strlen(pure[i])); + epoch = ray_sym_epoch(); + } + bool known = ray_query_rowwise_builtin(id); + for (size_t i = 0; i < NPURE && !known; i++) known = pure_ids[i] == id; + if (!known) return false; + ray_t* fn = ray_env_get(id); + if (!fn) return id == pure_ids[0]; /* quote is a form */ + if (fn->type == RAY_LAMBDA) return false; /* shadowed by a user helper */ + /* The builtin of that name, not another one bound to it. */ + if (ray_env_builtin_sym(fn) != id) return false; + return !(fn->attrs & RAY_FN_RESTRICTED); +} + +/* Fallback can inline pure expressions even when the DAG cannot lower + * their types or shapes. Never move effects or opaque user calls. */ +static bool query_inline_pure(ray_t* expr, int depth) { + if (!expr || depth > 24) return false; + if (expr->type == -RAY_SYM && !(expr->attrs & ATTR_QUOTED)) { + /* A name standing for a user function may be called by whatever + * receives it; its effects cannot be moved or duplicated. Globals + * only: a scoped lookup here would bind a column into a helper's + * call frame as a side effect. */ + ray_t* v = ray_env_get_global(expr->i64); + return !(v && v->type == RAY_LAMBDA); + } + if (expr->type != RAY_LIST || (expr->attrs & ATTR_QUOTED)) return true; + if (!expr->len) return true; + ray_t** es = ray_data(expr); + if (!es[0] || es[0]->type != -RAY_SYM) return false; + int64_t id = es[0]->i64; + if (id == ray_sym_intern("quote", 5)) return expr->len == 2; + if (!query_inline_pure_builtin(id)) return false; + for (int64_t i = 1; i < expr->len; i++) + if (!query_inline_pure(es[i], depth + 1)) return false; + return true; +} + +/* Whether evaluating `expr` can have an effect the program observes. A + * `by:` key the planner cannot lower is evaluated over the whole column + * first and again row by row when that run turns out to have meant one + * row at a time; a body with an effect would then run it twice, so such a + * body is evaluated row by row from the start. The decision follows the + * callee wherever it is bound: a global helper, a parameter or `let` of an + * enclosing frame, a capture of the closure being read, or a lambda literal + * bound by a `let` earlier in the same body. A callee that is computed + * (`((at H 'a) v)`) or unknown counts as an effect, as does `set`, `eval`, + * a system or I/O builtin and the few builtins that read outside their + * arguments; every other builtin is pure. */ +/* What the walk knows a name means, innermost last. A parameter is bound + * to the call's argument text (NULL when unknown), resolved where the call + * was written; a `let` binds a lambda literal, another name (an alias) or a + * computed value, resolved with the bindings in scope at the `let`; and a + * literal a builtin calls with elements of arguments the walk has seen are + * pure callables binds its parameters to those. */ +enum { KB_ARG, KB_LIT, KB_ALIAS, KB_UNKNOWN, KB_PURE, KB_LOOP }; +struct key_pure_ctx; +typedef struct { + int64_t name; + uint8_t kind; + ray_t* val; /* KB_ARG text, KB_LIT literal, KB_ALIAS name */ + const struct key_pure_ctx* at; /* where `val` is resolved (NULL: globals) */ + int at_n; /* ... with that context's first at_n bindings */ + bool cond; /* a `let` in a branch: it may not have run */ +} key_bind_t; +typedef struct key_pure_ctx { + ray_t* closure; /* captures of the lambda being walked, or NULL */ + key_bind_t* binds; + int n; + int cond; /* walking a branch that may not run */ +} key_pure_ctx_t; + +enum { KEY_PURE_MAX_BIND = 32 }; + +static bool key_expr_pure(ray_t* expr, int depth, key_pure_ctx_t* ctx); + +static bool key_pure_form(int64_t id) { + static const char* const forms[] = { + "let", "if", "do", "cond", "and", "or", "while", "times", "fn", "try", + "raise", "return", "quote", "self", + }; + enum { NFORMS = sizeof forms / sizeof *forms }; + static _Thread_local int64_t ids[NFORMS]; + static _Thread_local uint64_t epoch; + if (epoch != ray_sym_epoch() || !epoch) { + for (size_t i = 0; i < NFORMS; i++) ids[i] = ray_sym_intern(forms[i], strlen(forms[i])); + epoch = ray_sym_epoch(); + } + for (size_t i = 0; i < NFORMS; i++) if (ids[i] == id) return true; + return false; +} + +/* A builtin that reads or writes outside its arguments. */ +static bool key_impure_builtin(ray_t* fn, int64_t id) { + static const char* const impure[] = { + "println", "show", "print", "rand", "guid", "eval", "parse", "resolve", "env", "get", + "remove", "timeit", "exit", "ser", "de", "datoms", "assert-fact", "retract-fact", + "scan-eav", "pull", "dl-program", "dl-query", "dl-provenance", "hnsw-save", "rc", "meta", + }; + enum { NIMPURE = sizeof impure / sizeof *impure }; + static _Thread_local int64_t ids[NIMPURE]; + static _Thread_local uint64_t epoch; + if (epoch != ray_sym_epoch() || !epoch) { + for (size_t i = 0; i < NIMPURE; i++) ids[i] = ray_sym_intern(impure[i], strlen(impure[i])); + epoch = ray_sym_epoch(); + } + if (fn->attrs & (RAY_FN_RESTRICTED | RAY_FN_SPECIAL_FORM)) return true; + /* The builtin's own name, not the one it was reached by: println bound + * to another name is still println. */ + int64_t own = ray_env_builtin_sym(fn); + if (own >= 0) id = own; + if (ray_sym_is_dotted(id)) return true; /* .sys.*, .io.*, ... */ + for (size_t i = 0; i < NIMPURE; i++) if (ids[i] == id) return true; + return false; +} + +static bool key_literal_is_fn(ray_t* v) { + if (!v || v->type != RAY_LIST || v->len < 3) return false; + ray_t* h = ((ray_t**)ray_data(v))[0]; + return h && h->type == -RAY_SYM && !(h->attrs & ATTR_QUOTED) && h->i64 == ray_sym_intern("fn", 2); +} + +/* The context `b` resolves in: the bindings that were in scope there. */ +static key_pure_ctx_t key_bind_view(const key_bind_t* b) { + key_pure_ctx_t v = { NULL, NULL, 0, 0 }; + if (b->at) { v.closure = b->at->closure; v.binds = b->at->binds; v.n = b->at_n; } + return v; +} + +/* Whether `id` is bound by the walk, a capture or a scope frame: then a + * call spelled like a special form (if, do, let, fn, quote, try, ...) or + * a builtin is a call through that binding, as it is on the tree walker + * and in compiled code. */ +static bool key_name_bound(int64_t id, const key_pure_ctx_t* ctx) { + for (int i = 0; i < ctx->n; i++) if (ctx->binds[i].name == id) return true; + if (ctx->closure) { + ray_t* keys = ray_dict_keys(ctx->closure); + for (int64_t i = 0; keys && i < keys->len; i++) + if (ray_read_sym(ray_data(keys), i, RAY_SYM, keys->attrs) == id) return true; + } + return ray_env_get_local(id) != NULL; +} + +/* Whether a head spelled like a special form is the form where it is + * written: not bound by the walk, a capture or a frame. The compiler + * takes do, fn, if, let, return, times, try, while and self as the forms + * whatever their global binding; any other form name (quote, cond, and, + * or, raise) it resolves, so one set globally to anything but a builtin + * makes the call a call: (set quote f) then (quote x). */ +static bool key_is_form_here(int64_t id, const key_pure_ctx_t* ctx) { + if (key_name_bound(id, ctx)) return false; + static const char* const wired[] = { "do", "fn", "if", "let", "return", "times", "try", "while", "self" }; + enum { NWIRED = sizeof wired / sizeof *wired }; + static _Thread_local int64_t ids[NWIRED]; + static _Thread_local uint64_t epoch; + if (epoch != ray_sym_epoch() || !epoch) { + for (size_t i = 0; i < NWIRED; i++) ids[i] = ray_sym_intern(wired[i], strlen(wired[i])); + epoch = ray_sym_epoch(); + } + for (size_t i = 0; i < NWIRED; i++) if (ids[i] == id) return true; + ray_t* g = ray_env_get_global(id); + return !g || g->type == RAY_UNARY || g->type == RAY_BINARY || g->type == RAY_VARY; +} + +/* A lambda literal, `fn` being the special form where it is written. */ +static bool key_lit_fn(ray_t* v, const key_pure_ctx_t* ctx) { + return key_literal_is_fn(v) && key_is_form_here(ray_sym_intern("fn", 2), ctx); +} + +/* Bind a callee's parameter names (a SYM vector, or `[]` parsed as an + * empty vector) after the bindings already in `ctx`: to the call's + * argument text written in `at`, or, with no arguments, to `kind` (an + * unknown value, or a pure callable). False when the shapes do not fit, + * which the walk reads as an effect. */ +static bool key_bind_params(ray_t* params, ray_t** args, int64_t nargs, uint8_t kind, + const key_pure_ctx_t* at, key_pure_ctx_t* ctx) { + int64_t np = params ? params->len : 0; + if ((args && np != nargs) || ctx->n + np > KEY_PURE_MAX_BIND) return false; + if (np > 0 && params->type != RAY_SYM) return false; + for (int64_t i = 0; i < np; i++) + ctx->binds[ctx->n++] = (key_bind_t){ ray_read_sym(ray_data(params), i, RAY_SYM, params->attrs), + args ? KB_ARG : kind, args ? args[i] : NULL, + at, at ? at->n : 0, false }; + return true; +} + +/* A call of a lambda value: its body with its own captures and parameters. + * Called: the parameters mean the arguments, written in `caller`; passed as + * a value: its parameters are unknown values (a call through one is an + * effect). */ +static bool key_lambda_call_pure(ray_t* lam, ray_t** args, int64_t nargs, int depth, const key_pure_ctx_t* caller) { + ray_t* body = LAMBDA_BODY(lam); + if (!body || body->type != RAY_LIST) return false; + key_bind_t binds[KEY_PURE_MAX_BIND]; + key_pure_ctx_t ctx = { LAMBDA_CLOSURE(lam), binds, 0, 0 }; + if (!key_bind_params(LAMBDA_PARAMS(lam), args, nargs, KB_UNKNOWN, caller, &ctx)) return false; + ray_t** es = ray_data(body); + for (int64_t i = 0; i < body->len; i++) + if (!key_expr_pure(es[i], depth + 1, &ctx)) return false; + return true; +} + +/* A call of a lambda literal written in `outer`: its body, with the + * bindings in scope there and the call's arguments (also written there) + * bound to its parameters, or each parameter bound to `kind`. */ +static bool key_literal_call_kind(ray_t* lit, ray_t** args, int64_t nargs, uint8_t kind, int depth, + const key_pure_ctx_t* outer) { + ray_t** le = ray_data(lit); + if (outer->n > KEY_PURE_MAX_BIND) return false; + key_bind_t binds[KEY_PURE_MAX_BIND]; + key_pure_ctx_t ctx = { outer->closure, binds, outer->n, 0 }; + for (int i = 0; i < outer->n; i++) binds[i] = outer->binds[i]; + if (!key_bind_params(le[1], args, nargs, kind, outer, &ctx)) return false; + for (int64_t i = 2; i < lit->len; i++) + if (!key_expr_pure(le[i], depth + 1, &ctx)) return false; + return true; +} + +static bool key_literal_call_pure(ray_t* lit, ray_t** args, int64_t nargs, int depth, const key_pure_ctx_t* outer) { + return key_literal_call_kind(lit, args, nargs, KB_UNKNOWN, depth, outer); +} + +/* What a name stands for when it is called (args != NULL) or passed as a + * value: a binding the walk made (parameter or `let`), a capture, a binding + * of a frame in scope, a global. True when pure: a pure lambda, a pure + * builtin, or plain data. */ +static bool key_name_pure(int64_t id, ray_t** args, int64_t nargs, int depth, const key_pure_ctx_t* ctx) { + bool called = args != NULL; + if (depth > 16) return false; + for (int i = ctx->n - 1; i >= 0; i--) { + const key_bind_t* b = &ctx->binds[i]; + if (b->name != id) continue; + key_pure_ctx_t at = key_bind_view(b); + if (b->kind == KB_PURE) return true; + /* Rebound by a `let` in a loop: a later iteration, or the code + * after the loop, may see any of its values. */ + if (b->kind == KB_LOOP) { if (called) return false; continue; } + if (b->kind != KB_ARG) { + bool pure = b->kind == KB_UNKNOWN ? !called + : b->kind == KB_ALIAS ? key_name_pure(b->val->i64, args, nargs, depth + 1, &at) + : key_literal_call_pure(b->val, args, nargs, depth, &at); + /* A `let` in a branch may not have run: what the name meant + * before it counts as well. */ + if (!pure || !b->cond) return pure; + continue; + } + ray_t* a = b->val; + if (!a) return !called; /* an unknown value */ + /* The argument names something: follow it where the call was + * written, not in this body's bindings. */ + if (a->type == -RAY_SYM && !(a->attrs & ATTR_QUOTED)) return key_name_pure(a->i64, args, nargs, depth + 1, &at); + if (key_lit_fn(a, &at)) return key_literal_call_pure(a, args, nargs, depth, &at); + return !called; /* computed, or a literal datum */ + } + ray_t* v = NULL; + if (ctx->closure) { + ray_t* keys = ray_dict_keys(ctx->closure); + ray_t* vals = ray_dict_vals(ctx->closure); + for (int64_t i = 0; keys && vals && i < keys->len; i++) + if (ray_read_sym(ray_data(keys), i, RAY_SYM, keys->attrs) == id) { v = ((ray_t**)ray_data(vals))[i]; break; } + } + if (!v) v = ray_env_get_local(id); /* a parameter or let of a frame in scope */ + if (!v) v = ray_env_get_global(id); + if (!v && ray_sym_is_dotted(id)) v = ray_env_get(id); /* D.f: through the dict */ + if (!v) return !called; /* an unknown callee is an effect */ + if (v->type == RAY_LAMBDA) return key_lambda_call_pure(v, args, nargs, depth, ctx); + if (v->type == RAY_UNARY || v->type == RAY_BINARY || v->type == RAY_VARY) + return !key_impure_builtin(v, id); + /* Data: calling it is an error, not an effect. Reading it is pure, + * whatever it holds; a function taken out of it is caught where it is + * called, as a computed callee or a computed function argument of a + * builtin that calls it (key_higher_order_pure). */ + return !called; +} + +/* The builtins that call a function argument, by the C function behind + * them, so every name bound to one is covered: the argument positions + * each calls (bit i: argument i), and whether the literal shortcut below + * applies (map, pmap: elements; fold, scan: accumulator first). */ +enum { HOF_ELEMS = 1, HOF_ACC = 2 }; +static const struct { void* fn; uint8_t calls; uint8_t shortcut; } key_hof_table[] = { + { (void*)ray_map_fn, 1, HOF_ELEMS }, { (void*)ray_pmap_fn, 1, HOF_ELEMS }, + { (void*)ray_fold_fn, 1, HOF_ACC }, { (void*)ray_scan_fn, 1, HOF_ACC }, + { (void*)ray_fold_left_fn, 1, 0 }, { (void*)ray_fold_right_fn, 1, 0 }, + { (void*)ray_fold_while_fn, 3, 0 }, { (void*)ray_scan_left_fn, 1, 0 }, + { (void*)ray_scan_right_fn, 1, 0 }, { (void*)ray_prior_fn, 1, 0 }, + { (void*)ray_apply_fn, 1, 0 }, { (void*)ray_map_left_fn, 1, 0 }, + { (void*)ray_map_right_fn, 1, 0 }, +}; +enum { KEY_HOF_N = sizeof key_hof_table / sizeof *key_hof_table }; + +static bool key_hof_builtin(const ray_t* fn) { + for (int k = 0; k < KEY_HOF_N; k++) + if (key_hof_table[k].fn == (void*)(uintptr_t)fn->i64) return true; + return false; +} + +/* A value whose every callable is pure: a pure lambda or builtin, data + * that holds no function (an atom or a typed vector other than symbols, + * which name globals), or a list of such values. */ +static bool key_value_callables_pure(ray_t* v, int depth, const key_pure_ctx_t* ctx) { + if (!v || depth > 16) return false; + if (v->type == RAY_LAMBDA) return key_lambda_call_pure(v, NULL, 0, depth, ctx); + if (v->type == RAY_UNARY || v->type == RAY_BINARY || v->type == RAY_VARY) { + /* A builtin that calls its arguments is pure only for arguments + * the walk sees: as a value whose calls it cannot see, it is not + * known pure (map passed to map, then called with a computed + * function). */ + if (key_hof_builtin(v)) return false; + int64_t id = ray_env_builtin_sym(v); + return id >= 0 && !key_impure_builtin(v, id); + } + if (v->type == RAY_LIST) { + if (v->len > 64) return false; + ray_t** es = ray_data(v); + for (int64_t i = 0; i < v->len; i++) + if (!key_value_callables_pure(es[i], depth + 1, ctx)) return false; + return true; + } + if (v->type == RAY_SYM || v->type == -RAY_SYM) return false; + return ray_is_atom(v) || ray_is_vec(v); +} + +/* The one builtin a head means, as key_name_pure resolves it, or NULL + * when it can mean anything else: a lambda, data, an unknown value, two + * builtins (a `let` in a branch), nothing. */ +static ray_t* key_head_unique_builtin(int64_t id, const key_pure_ctx_t* ctx, int depth) { + if (depth > 16) return NULL; + ray_t* found = NULL; + for (int i = ctx->n - 1; i >= 0; i--) { + const key_bind_t* b = &ctx->binds[i]; + if (b->name != id) continue; + if (!((b->kind == KB_ALIAS || b->kind == KB_ARG) && b->val && b->val->type == -RAY_SYM && + !(b->val->attrs & ATTR_QUOTED))) return NULL; + key_pure_ctx_t at = key_bind_view(b); + ray_t* r = key_head_unique_builtin(b->val->i64, &at, depth + 1); + if (!r || (found && r != found)) return NULL; + found = r; + if (!b->cond) return found; + } + ray_t* v = NULL; + if (ctx->closure) { + ray_t* keys = ray_dict_keys(ctx->closure); + ray_t* vals = ray_dict_vals(ctx->closure); + for (int64_t i = 0; keys && vals && i < keys->len; i++) + if (ray_read_sym(ray_data(keys), i, RAY_SYM, keys->attrs) == id) { v = ((ray_t**)ray_data(vals))[i]; break; } + } + if (!v) v = ray_env_get_local(id); + if (!v) v = ray_env_get_global(id); + if (!v && ray_sym_is_dotted(id)) v = ray_env_get(id); + if (!v || !(v->type == RAY_UNARY || v->type == RAY_BINARY || v->type == RAY_VARY)) return NULL; + if (found && v != found) return NULL; + return v; +} + +/* Argument text whose value's every callable is known to be pure (see + * key_value_callables_pure): such data, a name bound to it, a pure lambda + * literal, or a `list`/`enlist` of such arguments. Anything computed is + * not known. */ +static bool key_arg_callables_pure(ray_t* e, int depth, const key_pure_ctx_t* ctx) { + if (!e || depth > 16) return false; + if (e->type == -RAY_SYM) { + if (e->attrs & ATTR_QUOTED) return false; + int64_t id = e->i64; + for (int i = ctx->n - 1; i >= 0; i--) { + const key_bind_t* b = &ctx->binds[i]; + if (b->name != id) continue; + key_pure_ctx_t at = key_bind_view(b); + bool pure = b->kind == KB_PURE ? true + : b->kind == KB_LIT ? key_literal_call_pure(b->val, NULL, 0, depth, &at) + : (b->kind == KB_ALIAS || (b->kind == KB_ARG && b->val)) + ? key_arg_callables_pure(b->val, depth + 1, &at) + : false; /* unknown, or rebound in a loop */ + /* A `let` in a branch may not have run: what the name meant + * before it must be pure as well, as key_name_pure requires. */ + if (!pure || !b->cond) return pure; + } + ray_t* v = NULL; + if (ctx->closure) { + ray_t* keys = ray_dict_keys(ctx->closure); + ray_t* vals = ray_dict_vals(ctx->closure); + for (int64_t i = 0; keys && vals && i < keys->len; i++) + if (ray_read_sym(ray_data(keys), i, RAY_SYM, keys->attrs) == id) { v = ((ray_t**)ray_data(vals))[i]; break; } + } + if (!v) v = ray_env_get_local(id); + if (!v) v = ray_env_get_global(id); + if (!v && ray_sym_is_dotted(id)) v = ray_env_get(id); + return key_value_callables_pure(v, depth + 1, ctx); + } + if (e->type != RAY_LIST) return e->type != RAY_SYM && (ray_is_atom(e) || ray_is_vec(e)); + if (e->attrs & ATTR_QUOTED || !e->len) return false; + if (key_lit_fn(e, ctx)) return key_literal_call_pure(e, NULL, 0, depth, ctx); + ray_t** es = ray_data(e); + if (!es[0] || es[0]->type != -RAY_SYM || (es[0]->attrs & ATTR_QUOTED)) return false; + /* The list constructors, by what the head means, not how it is spelled: + * a local list or enlist is a call through it. */ + ray_t* h = key_head_unique_builtin(es[0]->i64, ctx, 0); + if (!h || (h->i64 != (int64_t)(uintptr_t)ray_list_fn && h->i64 != (int64_t)(uintptr_t)ray_enlist_fn)) + return false; + for (int64_t i = 1; i < e->len; i++) + if (!key_arg_callables_pure(es[i], depth + 1, ctx)) return false; + return true; +} + +/* The builtins a call head can mean, as key_name_pure resolves it (a + * `let` alias, a parameter bound to a name, a capture, a frame, a global, + * a dict through a dotted name), up to `max`; a `let` in a branch adds + * what the name meant before it. Anything else it can mean adds nothing: + * a lambda is walked as a call, an unknown value is already an effect. */ +static int key_head_builtins(int64_t id, const key_pure_ctx_t* ctx, ray_t** out, int n, int max, int depth) { + if (depth > 16 || n >= max) return n; + for (int i = ctx->n - 1; i >= 0; i--) { + const key_bind_t* b = &ctx->binds[i]; + if (b->name != id) continue; + key_pure_ctx_t at = key_bind_view(b); + if ((b->kind == KB_ALIAS || b->kind == KB_ARG) && b->val && b->val->type == -RAY_SYM && + !(b->val->attrs & ATTR_QUOTED)) + n = key_head_builtins(b->val->i64, &at, out, n, max, depth + 1); + if (!b->cond) return n; + } + ray_t* v = NULL; + if (ctx->closure) { + ray_t* keys = ray_dict_keys(ctx->closure); + ray_t* vals = ray_dict_vals(ctx->closure); + for (int64_t i = 0; keys && vals && i < keys->len; i++) + if (ray_read_sym(ray_data(keys), i, RAY_SYM, keys->attrs) == id) { v = ((ray_t**)ray_data(vals))[i]; break; } + } + if (!v) v = ray_env_get_local(id); + if (!v) v = ray_env_get_global(id); + if (!v && ray_sym_is_dotted(id)) v = ray_env_get(id); + if (v && (v->type == RAY_UNARY || v->type == RAY_BINARY || v->type == RAY_VARY) && n < max) out[n++] = v; + return n; +} + +/* A call of a builtin that calls some of its arguments: each argument it + * calls must be a literal or known pure where it comes from (a name bound + * to a pure lambda or builtin); a function computed out of data (a list, + * a dict, a table cell) is a callee the walk cannot see. `(map f xs ...)` + * and `(fold f init xs)` with a lambda literal f whose other arguments' + * callables are all pure: f's parameters are pure too. Returns 1 pure, + * 0 effect, -1 walk it as any call. */ +static int key_higher_order_pure(int64_t id, ray_t** es, int64_t n, int depth, key_pure_ctx_t* ctx) { + ray_t* cand[4]; + int nc = key_head_builtins(id, ctx, cand, 0, 4, 0); + int shortcut = -1; /* the one candidate's shortcut kind, when there is one */ + bool any = false; + for (int c = 0; c < nc; c++) { + int k = 0; + while (k < KEY_HOF_N && key_hof_table[k].fn != (void*)(uintptr_t)cand[c]->i64) k++; + if (k == KEY_HOF_N) { shortcut = -2; continue; } + any = true; + for (int64_t a = 0; a + 1 < n && a < 8; a++) { + if (!(key_hof_table[k].calls & (1u << a))) continue; + ray_t* arg = es[a + 1]; + if (!key_lit_fn(arg, ctx) && !key_arg_callables_pure(arg, depth + 1, ctx)) return 0; + } + shortcut = shortcut == -1 ? key_hof_table[k].shortcut : -2; + } + if (!any || nc != 1 || shortcut <= 0 || n < 3 || !key_lit_fn(es[1], ctx)) return -1; + bool acc = shortcut == HOF_ACC; + for (int64_t i = 2; i < n; i++) + if (!key_arg_callables_pure(es[i], depth + 1, ctx)) return -1; + ray_t** le = ray_data(es[1]); + ray_t* params = le[1]; + int64_t np = params ? params->len : 0; + if (np > 0 && params->type != RAY_SYM) return 0; + if (ctx->n + np > KEY_PURE_MAX_BIND) return 0; + key_bind_t binds[KEY_PURE_MAX_BIND]; + key_pure_ctx_t lctx = { ctx->closure, binds, ctx->n, 0 }; + for (int i = 0; i < ctx->n; i++) binds[i] = ctx->binds[i]; + for (int64_t i = 0; i < np; i++) + binds[lctx.n++] = (key_bind_t){ ray_read_sym(ray_data(params), i, RAY_SYM, params->attrs), + acc && i == 0 ? KB_UNKNOWN : KB_PURE, NULL, NULL, 0, false }; + for (int64_t i = 2; i < es[1]->len; i++) + if (!key_expr_pure(le[i], depth + 1, &lctx)) return 0; + /* The shortcut replaces the walk of the call's arguments: evaluating + * them must be pure too. */ + for (int64_t i = 2; i < n; i++) + if (!key_expr_pure(es[i], depth + 1, ctx)) return 0; + return 1; +} + +/* The names `let` binds anywhere in `expr`, outside lambda literals and + * quoted text, added to names[*nn] once each. False when there are more + * than the walk can bind or the text is too deep. */ +static bool key_collect_lets(ray_t* expr, int64_t* names, int* nn, int depth, const key_pure_ctx_t* ctx) { + if (!expr || expr->type != RAY_LIST || (expr->attrs & ATTR_QUOTED) || !expr->len) return true; + if (depth > 32) return false; + ray_t** es = ray_data(expr); + if (es[0] && es[0]->type == -RAY_SYM && !(es[0]->attrs & ATTR_QUOTED)) { + int64_t id = es[0]->i64; + if ((id == ray_sym_intern("fn", 2) || id == ray_sym_intern("quote", 5)) && key_is_form_here(id, ctx)) return true; + if (id == ray_sym_intern("let", 3) && expr->len == 3 && es[1] && es[1]->type == -RAY_SYM) { + bool seen = false; + for (int i = 0; i < *nn && !seen; i++) seen = names[i] == es[1]->i64; + if (!seen) { + if (*nn >= KEY_PURE_MAX_BIND) return false; + names[(*nn)++] = es[1]->i64; + } + } + } + for (int64_t i = 0; i < expr->len; i++) + if (!key_collect_lets(es[i], names, nn, depth + 1, ctx)) return false; + return true; +} + +static bool key_expr_pure(ray_t* expr, int depth, key_pure_ctx_t* ctx) { + if (!expr) return true; + if (depth > 16) return false; + if (expr->type == -RAY_SYM) { + if (expr->attrs & ATTR_QUOTED) return true; + return key_name_pure(expr->i64, NULL, 0, depth, ctx); + } + if (expr->type != RAY_LIST || (expr->attrs & ATTR_QUOTED) || !expr->len) return true; + ray_t** es = ray_data(expr); + ray_t* head = es[0]; + if (!head) return false; + int64_t first_arg = 1; + if (head->type == RAY_LIST) { + if (!key_lit_fn(head, ctx)) return false; /* a computed callee */ + if (!key_literal_call_pure(head, es + 1, expr->len - 1, depth, ctx)) return false; + } else if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED)) { + int64_t id = head->i64; + if (key_pure_form(id) && key_is_form_here(id, ctx)) { + if (id == ray_sym_intern("quote", 5)) return true; + if (id == ray_sym_intern("fn", 2)) return key_literal_call_pure(expr, NULL, 0, depth, ctx); + if (id == ray_sym_intern("let", 3) && expr->len == 3 && es[1] && es[1]->type == -RAY_SYM && + !(es[1]->attrs & ATTR_QUOTED)) { + /* Every `let` binds: a later call through the name means + * this value, never a global or capture of that name. */ + if (ctx->n >= KEY_PURE_MAX_BIND) return false; + ray_t* val = es[2]; + uint8_t kind = KB_UNKNOWN; + if (key_lit_fn(val, ctx)) kind = KB_LIT; /* checked where it is called */ + else if (val && val->type == -RAY_SYM && !(val->attrs & ATTR_QUOTED)) kind = KB_ALIAS; + if (kind != KB_LIT && !key_expr_pure(val, depth + 1, ctx)) return false; + ctx->binds[ctx->n] = (key_bind_t){ es[1]->i64, kind, kind == KB_UNKNOWN ? NULL : val, ctx, ctx->n, ctx->cond > 0 }; + ctx->n++; + return true; + } + } else { + int ho = key_higher_order_pure(id, es, expr->len, depth, ctx); + if (ho >= 0) return ho == 1; + if (!key_name_pure(id, es + 1, expr->len - 1, depth, ctx)) return false; + } + } else { + return false; + } + /* After its first operand a conditional or loop form's operands may + * not run: a `let` there is conditional. In a try body a raise can + * skip any `let`, so the whole form is. */ + bool is_form = head->type == -RAY_SYM && key_pure_form(head->i64) && key_is_form_here(head->i64, ctx); + bool is_try = is_form && head->i64 == ray_sym_intern("try", 3); + bool is_loop = is_form && (head->i64 == ray_sym_intern("while", 5) || head->i64 == ray_sym_intern("times", 5)); + bool branches = is_form && + (head->i64 == ray_sym_intern("if", 2) || head->i64 == ray_sym_intern("cond", 4) || + head->i64 == ray_sym_intern("and", 3) || head->i64 == ray_sym_intern("or", 2) || + is_loop || is_try); + int64_t cond_from = is_try ? first_arg : first_arg + 1; + /* try calls its handler when it is a function: anything but a literal + * function, a literal fallback value or a name known pure is a callee + * the walk cannot see. */ + if (is_try && expr->len >= 3) { + ray_t* h = es[2]; + if (h && h->type == RAY_LAMBDA) { + /* A lambda object spliced into the text is called as it is. */ + if (!key_lambda_call_pure(h, NULL, 0, depth + 1, ctx)) return false; + } else { + bool literal = h && (key_lit_fn(h, ctx) || + (h->type == -RAY_SYM && (h->attrs & ATTR_QUOTED)) || + (h->type != RAY_LIST && h->type != -RAY_SYM)); + if (!literal && !key_arg_callables_pure(h, depth + 1, ctx)) return false; + } + } + /* A loop runs its body again: a `let` there reaches the calls before + * it in the next iteration, and the code after the loop. Every name + * the loop rebinds is marked first, so a call through it is an effect. */ + if (is_loop) { + int64_t names[KEY_PURE_MAX_BIND]; + int nn = 0; + for (int64_t i = first_arg; i < expr->len; i++) + if (!key_collect_lets(es[i], names, &nn, 0, ctx)) return false; + if (ctx->n + nn > KEY_PURE_MAX_BIND) return false; + for (int i = 0; i < nn; i++) + ctx->binds[ctx->n++] = (key_bind_t){ names[i], KB_LOOP, NULL, NULL, 0, true }; + } + bool in_cond = false; + for (int64_t i = first_arg; i < expr->len; i++) { + if (branches && i == cond_from) { ctx->cond++; in_cond = true; } + bool ok = key_expr_pure(es[i], depth + 1, ctx); + if (!ok) { if (in_cond) ctx->cond--; return false; } + } + if (in_cond) ctx->cond--; + return true; +} + +static ray_t* query_quote_value(ray_t* value) { + ray_t* quoted = ray_list_new(2); + if (!quoted || RAY_IS_ERR(quoted)) { + if (quoted) ray_error_free(quoted); + return NULL; + } + ray_t** q = ray_data(quoted); + q[0] = ray_sym(ray_sym_intern("quote", 5)); + if (!q[0] || RAY_IS_ERR(q[0])) { + if (q[0]) ray_error_free(q[0]); + quoted->len = 0; ray_release(quoted); return NULL; + } + q[1] = value; ray_retain(value); quoted->len = 2; + return quoted; +} + +/* A projection can replace a source column with an output alias. Keep a + * private binding for a helper's free source reference in that case; its + * actual arguments continue to read the visible alias. */ +typedef struct { + ray_t* table; /* borrowed until a private column is added */ + bool owned; + /* Grouped derived outputs: the source rows are gone, so a free name + * that named a source column means its global binding, as it does + * when the helper runs as bytecode. */ + bool globals_for_source; + int next; +} query_inline_scope_t; + +/* The private name must be free in the evaluation table and the globals; + * a lexical binding of the same spelling wins over a query column anyway. */ +static ray_t* query_inline_source_col(query_inline_scope_t* scope, ray_t* col) { + char name[48]; + int64_t id; + do { + int len = snprintf(name, sizeof name, "__query_source_%d", scope->next++); + id = ray_sym_intern(name, len); + } while (ray_table_get_col(scope->table, id) || ray_env_get(id)); + if (!scope->owned) { ray_retain(scope->table); scope->owned = true; } + scope->table = ray_table_add_col(scope->table, id, col); + if (!scope->table || RAY_IS_ERR(scope->table)) return NULL; + return ray_sym(id); +} + +/* Source schema and evaluation schema differ after aliases/group outputs. + * Free names use the former; actual arguments keep their calling scope. */ +static ray_t* query_inline_walk(ray_t* expr, ray_t* tbl, + query_inline_binding_t* bindings, int nb, + int depth, int* budget, bool named_body, query_inline_scope_t* scope) { + if (!expr || depth > 24 || --*budget < 0) return NULL; + /* A literal symbol in a named helper's body is the symbol, as in + * bytecode; text written in the query, inline lambdas included, keeps + * the query's column rule. */ + if (named_body && expr->type == -RAY_SYM && (expr->attrs & ATTR_QUOTED)) + return query_quote_value(expr); + if (expr->type == -RAY_SYM && !(expr->attrs & ATTR_QUOTED)) { + for (int i = nb - 1; i >= 0; i--) if (bindings[i].name == expr->i64) { + ray_retain(bindings[i].expr); + return bindings[i].expr; + } + ray_t* source_col = named_body ? ray_table_get_col(tbl, expr->i64) : NULL; + if (source_col && scope && scope->globals_for_source) source_col = NULL; + else if (source_col && scope && scope->table && !RAY_IS_ERR(scope->table) && + source_col != ray_table_get_col(scope->table, expr->i64)) + return query_inline_source_col(scope, source_col); + if (named_body && !source_col) { + /* A named helper's free name belongs to its global scope, not + * to an earlier select alias. Quote the value so a SYM or LIST + * constant cannot be reinterpreted as a column or a call. */ + ray_t* value = ray_env_get_global(expr->i64); + if (!value || !(ray_is_atom(value) || ray_is_vec(value))) return NULL; + return query_quote_value(value); + } + } + if (expr->type != RAY_LIST || expr->len == 0 || (expr->attrs & ATTR_QUOTED)) { + ray_retain(expr); return expr; + } + ray_t** es = ray_data(expr); + int64_t fn_id = ray_sym_intern("fn", 2); + /* A call through a formal of the body being expanded (named quote, if + * or count as well): the expansion cannot hold it, the helper is + * called instead. */ + if (es[0]->type == -RAY_SYM && !(es[0]->attrs & ATTR_QUOTED)) + for (int i = nb - 1; i >= 0; i--) if (bindings[i].name == es[0]->i64) return NULL; + if (es[0]->type == -RAY_SYM && + (es[0]->i64 == fn_id || es[0]->i64 == ray_sym_intern("let", 3) || + es[0]->i64 == ray_sym_intern("quote", 5))) { + ray_retain(expr); return expr; + } + ray_t* params = NULL, *body = NULL; + bool named = false; + if (es[0]->type == -RAY_SYM && !(es[0]->attrs & ATTR_QUOTED) && + !ray_table_get_col(tbl, es[0]->i64)) { + ray_t* fn = ray_env_get(es[0]->i64); + /* A closure's body reads its captures; inlined, those names would + * resolve to columns or globals instead. Never inline one, however + * often it has been called (a closure compiles on its second call). */ + if (fn && fn->type == RAY_LAMBDA && !LAMBDA_CLOSURE(fn)) { + ray_t* bodies = LAMBDA_BODY(fn); + if (bodies && bodies->type == RAY_LIST && bodies->len == 1) { + params = LAMBDA_PARAMS(fn); + body = ((ray_t**)ray_data(bodies))[0]; + named = true; + } + } + } else if (es[0]->type == RAY_LIST && es[0]->len == 3) { + ray_t** head = ray_data(es[0]); + if (head[0]->type == -RAY_SYM && head[0]->i64 == fn_id) { + params = head[1]; body = head[2]; + } + } + ray_t* out = ray_list_new(expr->len); + if (!out || RAY_IS_ERR(out)) { + if (out) ray_error_free(out); + return NULL; + } + ray_t** dst = ray_data(out); + out->len = 0; + for (int64_t i = 0; i < expr->len; i++) { + if (i == 0) { dst[i] = es[i]; ray_retain(dst[i]); } + else dst[i] = query_inline_walk(es[i], tbl, bindings, nb, depth + 1, budget, named_body, scope); + if (!dst[i]) { ray_release(out); return NULL; } + out->len++; + } + out->attrs = expr->attrs; + if (!params || params->type != RAY_SYM || params->len != expr->len - 1 || + params->len > 64 || + expr_contains_call_named(body, "let", 3) || + expr_contains_call_named(body, "fn", 2)) return out; + query_inline_binding_t formals[64]; + for (int64_t i = 0; i < params->len; i++) + formals[i] = (query_inline_binding_t){sym_cell_runtime_id(params, i), dst[i + 1]}; + /* An inline lambda inside a named helper's body is still that body. */ + ray_t* expanded = query_inline_walk(body, tbl, formals, (int)params->len, + depth + 1, budget, named || named_body, scope); + if (!expanded) return out; + if (!query_inline_pure(expanded, 0)) { ray_release(expanded); return out; } + for (int64_t i = 1; i < out->len; i++) + if (!query_inline_pure(dst[i], 0)) { ray_release(expanded); return out; } + ray_release(out); + return expanded; +} + +static bool query_expr_has_helper(ray_t* expr) { + if (!expr || expr->type != RAY_LIST || (expr->attrs & ATTR_QUOTED) || !expr->len) + return false; + ray_t** es = ray_data(expr); + if (es[0]->type == RAY_LIST) return true; + if (es[0]->type == -RAY_SYM) { + int64_t id = es[0]->i64; + if (id == ray_sym_intern("quote", 5) || id == ray_sym_intern("fn", 2) || + id == ray_sym_intern("let", 3)) return false; + ray_t* fn = ray_env_get(id); + if (fn && fn->type == RAY_LAMBDA) return true; + } + for (int64_t i = 1; i < expr->len; i++) + if (query_expr_has_helper(es[i])) return true; + return false; +} + +/* Whether evaluating `expr` cannot change what a global reads. Inlining + * puts the value a helper's free global has now into the expansion, which + * a query may then evaluate once per group or row; an effect in the same + * expression (a helper that sets that global) would run in between and + * the expansion would not see it. Such an expression is evaluated as + * written, its helpers called each time, as the tree walker does. */ +static bool query_expr_effect_free(ray_t* expr) { + key_bind_t binds[KEY_PURE_MAX_BIND]; + key_pure_ctx_t ctx = { NULL, binds, 0, 0 }; + return key_expr_pure(expr, 0, &ctx); +} + +static ray_t* query_inline_helpers(ray_t* expr, ray_t* tbl) { + if (!query_expr_has_helper(expr) || !query_expr_effect_free(expr)) { ray_retain(expr); return expr; } + int budget = 1024; + ray_t* expanded = query_inline_walk(expr, tbl, NULL, 0, 0, &budget, false, NULL); + if (!expanded) { ray_retain(expr); expanded = expr; } + return expanded; +} + +static ray_t* eval_query_expr(ray_t* expr, ray_t* tbl) { + ray_t* expanded = query_inline_helpers(expr, tbl); + ray_t* result = ray_eval(expanded); + ray_release(expanded); + return result; +} + /* The per-row evaluation in progress, if any: the row, the table it indexes * and the scope depth just above its own query frame. A literal column * name stands for the row's cell only while the active table is that table * and no nested query has opened a scope since — a nested select, a * per-group evaluation or a where-mask over any table (the same one * included) binds whole columns and must see whole columns. */ +/* The rows of the group being evaluated by the per-group fallback, while + * its expression runs: a helper's free source column is sliced by it. */ +static _Thread_local ray_t* g_active_query_group_idx = NULL; static _Thread_local int64_t g_active_query_row = -1; static _Thread_local ray_t* g_active_query_row_tbl = NULL; static _Thread_local int32_t g_active_query_row_depth = 0; ray_t* ray_active_query_table(void) { return g_active_query_table; } +ray_t* ray_query_helper_table(void) { + return g_query_source_table ? g_query_source_table : g_active_query_table; +} + /* Mount columns AND publish `tbl` as the active query table; returns the * previously-active table so the caller can restore it after the matching @@ -2055,10 +3122,34 @@ static ray_t* bind_all_columns(ray_t* tbl) { return prev; } +static ray_t* group_key_eval(ray_t* v, ray_t* tbl); + +/* The column of an aggregate's argument expression over `tbl`: the + * full-column evaluation the eval-level grouping slices per group + * (`(sum (if (== st 'bad) 1 0))`, #756). Evaluated with the columns in + * scope and as a row-wise projection where it compiles (group_key_eval), + * since the eval-level `if` tests whole-vector truthiness. A lazy result + * is materialized, since the per-group ray_at_fn consumes lazy arguments. + * Owned ref, or an error. */ +static ray_t* select_eval_over_table(ray_t* expr, ray_t* tbl) { + if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); + ray_t* _aqt = bind_all_columns(tbl); + ray_t* v = group_key_eval(expr, tbl); + g_active_query_table = _aqt; + ray_env_pop_scope(); + if (!v) return ray_error("domain", "select by: failed to evaluate aggregation source"); + if (RAY_IS_ERR(v)) return v; + if (ray_is_lazy(v)) { + v = ray_lazy_materialize(v); + if (!v) return ray_error("domain", "select by: failed to materialize aggregation source"); + } + return v; +} + static ray_t* eval_where_mask(ray_t* where_expr, ray_t* tbl, const char* label) { if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); ray_t* _aqt = bind_all_columns(tbl); - ray_t* mask = ray_eval(where_expr); + ray_t* mask = eval_query_expr(where_expr, tbl); if (mask && !RAY_IS_ERR(mask)) mask = ray_lazy_materialize(mask); g_active_query_table = _aqt; @@ -2085,7 +3176,7 @@ static ray_op_t* compile_where_predicate(ray_graph_t* g, ray_t* tbl, * 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; } + else { ray_error_free(g->compile_err); g->compile_err = NULL; } return NULL; } @@ -2186,7 +3277,52 @@ static int expr_contains_agg(ray_t* expr) { return 0; } -static int is_group_dag_agg_expr(ray_t* expr); /* defined below */ +/* Collection concat changes row counts; text concat is still row-wise. + * Compile only the concat subtree to distinguish them without evaluating + * user functions. Without a table, conservatively decline the shortcut. */ +static bool expr_has_collection_concat(ray_t* expr, ray_t* tbl) { + if (!expr || expr->type != RAY_LIST || (expr->attrs & ATTR_QUOTED) || !expr->len) + return false; + ray_t** elems = ray_data(expr); + int64_t name = elems[0]->type == -RAY_SYM ? elems[0]->i64 : -1; + bool concat = name == ray_sym_intern("concat", 6); + ray_t* fn = name >= 0 ? ray_env_get(name) : NULL; + bool helper = fn && fn->type == RAY_LAMBDA; + if (concat || helper) { + if (!tbl) return true; + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return true; + ray_op_t* op = compile_expr_dag(g, expr); + bool collection = !op || (concat && op->opcode != OP_CONCAT); + if (op && op->opcode == OP_CONST) { + ray_op_ext_t* ext = find_ext(g, op->id); + if (ext && ext->literal) collection = !ray_is_atom(ext->literal); + } + ray_graph_free(g); + if (concat || !collection) return collection; + /* Only helpers the native compiler cannot lower need expansion. + * Walk calls once, rather than re-expanding every enclosing aggregate. */ + ray_t* expanded = query_inline_helpers(expr, tbl); + ray_t** ex = expanded->type == RAY_LIST && expanded->len ? ray_data(expanded) : NULL; + if (ex && ex[0]->type == -RAY_SYM && ex[0]->i64 == name) { + /* The call could not be expanded (an opaque helper): it is a + * collection operation only if an argument is one. */ + collection = false; + for (int64_t i = 1; i < expanded->len && !collection; i++) + collection = expr_has_collection_concat(ex[i], tbl); + } else { + collection = expr_contains_call_named(expanded, "concat", 6) && + expr_has_collection_concat(expanded, tbl); + } + ray_release(expanded); + return collection; + } + for (int64_t i = 1; i < expr->len; i++) + if (expr_has_collection_concat(elems[i], tbl)) return true; + return false; +} + +static int is_group_dag_agg_expr(ray_t* expr, ray_t* tbl); /* defined below */ static bool simplify_agg_idiom(ray_t* val_expr, ray_t* tbl, uint16_t* out_op, ray_t** out_arg); @@ -2270,7 +3406,7 @@ static ray_t* agg_arith_rewrite(ray_t* expr, ray_t* tbl, ray_t** hexprs, int64_t* hnames, int* n_hidden, int cap, int* ok) { if (!*ok || !expr) { *ok = 0; return NULL; } - if (expr->type == RAY_LIST && is_group_dag_agg_expr(expr) && + if (expr->type == RAY_LIST && is_group_dag_agg_expr(expr, tbl) && hidden_agg_shape_ok(expr)) { ray_t** el = (ray_t**)ray_data(expr); /* nested agg inside the agg argument: not a DAG shape — bail */ @@ -2338,7 +3474,7 @@ static ray_t* try_decompose_agg_arith(ray_t* val_expr, ray_t* tbl, ray_t** hexprs, int64_t* hnames, int* n_hidden, int cap) { if (!val_expr || val_expr->type != RAY_LIST) return NULL; - if (is_group_dag_agg_expr(val_expr)) return NULL; /* plain agg path */ + if (is_group_dag_agg_expr(val_expr, tbl)) return NULL; /* plain agg path */ if (!expr_contains_agg(val_expr)) return NULL; int ok = 1; int saved = *n_hidden; @@ -2415,7 +3551,7 @@ static ray_t* select_fallback_passthrough_col(ray_t* expr, ray_t* tbl, int64_t n } /* True when a projection's TOP-LEVEL call is a "whole-column verb": a - * length-changing / reordering builtin (distinct, asc, desc, reverse) that + * collection builtin (distinct, asc, desc, reverse, enlist) that * consumes an entire column vector and returns a vector. The DAG compiler * has no bucket for these — they are neither element-wise ops nor * scalar-reducing aggregations — so `compile_expr_dag` returns NULL and the @@ -2427,15 +3563,62 @@ static ray_t* select_fallback_passthrough_col(ray_t* expr, ray_t* tbl, int64_t n * (see eval_expr_whole_column). Matched on the top-level head only — * a whole-column verb nested under an element-wise op has ambiguous length * semantics and is left to the per-row path. */ -static int is_whole_column_projection(ray_t* expr) { +static int is_whole_column_projection(ray_t* expr, ray_t* tbl) { if (!expr || expr->type != RAY_LIST) return 0; if (ray_len(expr) < 2) return 0; ray_t* head = ((ray_t**)ray_data(expr))[0]; if (!head || head->type != -RAY_SYM) return 0; + ray_t* fn = ray_env_get(head->i64); + if (fn && fn->type == RAY_LAMBDA) { + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return 0; + ray_op_t* op = compile_expr_dag(g, expr); + ray_op_ext_t* ext = op && op->opcode == OP_CONST ? find_ext(g, op->id) : NULL; + int whole = ext && ext->literal && !ray_is_atom(ext->literal); + ray_graph_free(g); + return whole; + } ray_t* s = ray_sym_str(head->i64); if (!s) return 0; size_t l = ray_str_len(s); const char* p = ray_str_ptr(s); + if (l == 6 && memcmp(p, "concat", 6) == 0) { + /* Preserve row-wise text concatenation when another projection + * forces fallback, but evaluate collection concat once. Compilation + * only inspects types/literals; it does not run user expressions. */ + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return 0; + ray_op_t* op = compile_expr_dag(g, expr); + int whole = 0; + if (op && op->opcode == OP_CONST) { + ray_op_ext_t* ext = find_ext(g, op->id); + whole = ext && ext->literal && !ray_is_atom(ext->literal); + } else if (!op) { + /* A declined concat consumes complete operands: a column plus + * a bound vector is a collection append, and an operand the + * compiler has no node for (a reordered, indexed or cast + * column) means the same whole column it means in update, + * where and by. Neither may be retried for each row. */ + whole = 1; + } + ray_graph_free(g); + return whole; + } + if (l == 6 && memcmp(p, "enlist", 6) == 0) { + /* Only a single scalar value can stand for a broadcast column. + * Column arguments, vector constants and multi-argument enlist + * remain per-row constructors. Aggregate arguments are handled by + * the fallback's existing one-value rule. */ + if (ray_len(expr) != 2) return 0; + ray_t* value = ((ray_t**)ray_data(expr))[1]; + if (!ray_is_atom(value)) return 0; + if (value->type == -RAY_SYM) { + if (ray_table_get_col(tbl, value->i64) && + !ray_env_has_lexical_local(value->i64)) return 0; + if (!(value->attrs & ATTR_QUOTED)) value = ray_env_get(value->i64); + } + return value && ray_is_atom(value); + } return (l == 8 && memcmp(p, "distinct", 8) == 0) || (l == 7 && memcmp(p, "reverse", 7) == 0) || (l == 3 && memcmp(p, "asc", 3) == 0) || @@ -2446,10 +3629,57 @@ static int is_whole_column_projection(ray_t* expr) { * `(count (distinct col))` is semantically an aggregate, but `distinct` * is not a row-aligned DAG input inside GROUP. Route it through the * per-group eval fallback so `distinct` sees each group's slice. */ -static int is_group_dag_agg_expr(ray_t* expr) { +static bool expr_is_constant_collection(ray_t* expr, ray_t* tbl, bool* lowered) { + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return false; + ray_op_t* op = compile_expr_dag(g, expr); + if (lowered) *lowered = op != NULL; + bool collection = op && op_tree_is_scalar(g, op->id) && + !op_tree_is_atom(g, op->id); + ray_graph_free(g); + return collection; +} + +/* True when an aggregate's input must be evaluated per group rather than + * lowered as a row-aligned input: a constant collection (its length is + * independent of the source rows; `collections` says the caller cares), or + * a collection concat the compiler cannot lower. A source column, or a + * column expression free of concat and helper calls, needs no trial + * compile — the planner asks this for every aggregate several times. */ +static bool agg_input_needs_group_eval(ray_t* arg, ray_t* tbl, bool collections) { + if (!arg) return false; + if (tbl && tbl->type == RAY_TABLE) { + if (arg->type == -RAY_SYM) { + bool local = !(arg->attrs & ATTR_QUOTED) && ray_env_has_lexical_local(arg->i64); + if (!local && ray_table_get_col(tbl, arg->i64)) return false; + if (!collections) return false; + } else if (arg->type != RAY_LIST) { + return collections && ray_is_vec(arg); + } else if (!expr_contains_call_named(arg, "concat", 6) && !query_expr_has_helper(arg)) { + if (!collections || expr_refs_row_column(arg, tbl)) return false; + } + } + bool lowered = false; + bool constant = expr_is_constant_collection(arg, tbl, &lowered); + if (constant && collections) return true; + if (lowered) return false; + /* A helper the planner can neither lower nor expand (several + * statements, a closure, recursion) runs per group in the evaluator, + * where its argument keeps the group's rows. */ + if (tbl && tbl->type == RAY_TABLE && query_expr_has_helper(arg)) { + ray_t* expanded = query_inline_helpers(arg, tbl); + bool opaque = query_expr_has_helper(expanded); + ray_release(expanded); + if (opaque) return true; + } + return expr_has_collection_concat(arg, tbl); +} + +static int is_group_dag_agg_expr(ray_t* expr, ray_t* tbl) { if (!is_agg_expr(expr)) return 0; ray_t** elems = (ray_t**)ray_data(expr); uint16_t op = resolve_agg_opcode(elems[0]->i64); + if (expr_contains_call_named(elems[1], "distinct", 8)) return 0; if (op == OP_QUANTILE) { if (ray_len(expr) < 3) return 0; if (!quantile_literal_prob(elems[2], @@ -2457,7 +3687,7 @@ static int is_group_dag_agg_expr(ray_t* expr) { NULL)) return 0; } - return !expr_contains_call_named(elems[1], "distinct", 8); + return !agg_input_needs_group_eval(elems[1], tbl, op == OP_COUNT); } static bool expr_literal_is_temporal(ray_t* expr) { @@ -2501,7 +3731,7 @@ static bool expr_contains_temporal_arith(ray_t* expr, ray_t* tbl) { } static int is_group_dag_agg_expr_dag_safe(ray_t* expr, ray_t* tbl) { - if (!is_group_dag_agg_expr(expr)) return 0; + if (!is_group_dag_agg_expr(expr, tbl)) return 0; ray_t** elems = (ray_t**)ray_data(expr); uint16_t op = resolve_agg_opcode(elems[0]->i64); @@ -2522,6 +3752,17 @@ static int is_group_dag_agg_expr_dag_safe(ray_t* expr, ray_t* tbl) { if (expr_contains_temporal_arith(elems[2], tbl)) return 0; } + /* An argument the DAG has no node for — (in s (list ...)) — is left to + * the per-group evaluation instead of failing the whole select with + * "failed to compile aggregation argument". Compilation only inspects + * types and literals; it runs no user expression. */ + if (agg_arg && agg_arg->type == RAY_LIST) { + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return 1; + ray_op_t* op_in = compile_expr_dag(g, agg_arg); + ray_graph_free(g); + if (!op_in) return 0; + } return 1; } @@ -2768,6 +4009,10 @@ static bool match_group_count_emit_filter(ray_t* from_expr, ray_t* where_expr, return false; ray_t* by = dict_get(inner, "by"); if (!by) return false; + /* The child source is not resolved yet. Concat's text/collection + * distinction can change aggregate slot numbering, so do not arm an + * index-based filter without that type information. */ + if (expr_contains_call_named(ray_dict_vals(inner), "concat", 6)) return false; DICT_VIEW_DECL(iv); DICT_VIEW_OPEN(inner, iv); @@ -2786,7 +4031,7 @@ static bool match_group_count_emit_filter(ray_t* from_expr, ray_t* where_expr, kid == take_id || kid == asc_id || kid == desc_id) continue; ray_t* val = iv[i + 1]; - if (!is_group_dag_agg_expr(val)) + if (!is_group_dag_agg_expr(val, NULL)) continue; ray_t** ae = (ray_t**)ray_data(val); uint16_t op = resolve_agg_opcode(ae[0]->i64); @@ -2821,7 +4066,7 @@ static bool positive_take_i64(ray_t* expr, int64_t* out) { return true; } -static bool match_group_desc_count_take(ray_t** dict_elems, int64_t dict_n, +static bool match_group_desc_count_take(ray_t* tbl, ray_t** dict_elems, int64_t dict_n, int64_t from_id, int64_t where_id, int64_t by_id, int64_t take_id, int64_t asc_id, int64_t desc_id, @@ -2867,7 +4112,7 @@ static bool match_group_desc_count_take(ray_t** dict_elems, int64_t dict_n, kid == take_id || kid == asc_id || kid == desc_id) continue; ray_t* val = dict_elems[i + 1]; - if (!is_group_dag_agg_expr(val)) + if (!is_group_dag_agg_expr(val, tbl)) continue; ray_t** ae = (ray_t**)ray_data(val); uint16_t op = resolve_agg_opcode(ae[0]->i64); @@ -2905,20 +4150,24 @@ static int is_aggr_unary_call(ray_t* expr) { return (fn_obj->attrs & RAY_FN_AGGR) != 0; } -static int is_streaming_aggr_unary_call(ray_t* expr) { +static int is_streaming_aggr_unary_call(ray_t* expr, ray_t* tbl) { + /* Collection concat changes the source length. Evaluate it within + * each group rather than slicing a concatenated full-table result. */ if (!is_aggr_unary_call(expr)) return 0; ray_t** elems = (ray_t**)ray_data(expr); - return !expr_contains_call_named(elems[1], "distinct", 8); + if (expr_contains_call_named(elems[1], "distinct", 8)) return 0; + return !agg_input_needs_group_eval(elems[1], tbl, true); } -static int is_plain_count_expr(ray_t* expr) { +static int is_plain_count_expr(ray_t* expr, ray_t* tbl) { if (!expr || expr->type != RAY_LIST) return 0; int64_t n = ray_len(expr); if (n < 2) return 0; ray_t** elems = (ray_t**)ray_data(expr); if (!elems[0] || elems[0]->type != -RAY_SYM) return 0; if (resolve_agg_opcode(elems[0]->i64) != OP_COUNT) return 0; - return !expr_contains_call_named(elems[1], "distinct", 8); + if (expr_contains_call_named(elems[1], "distinct", 8)) return 0; + return !agg_input_needs_group_eval(elems[1], tbl, true); } /* NOTE: binary-aggregator gates (is_aggr_binary_call / @@ -3057,14 +4306,14 @@ static int64_t select_output_count(ray_t** dict_elems, int64_t dict_n) { /* Upper bound on the aggregate subcalls a compound output decomposes * into (try_decompose_agg_arith extracts each is_group_dag_agg_expr - * node as one hidden slot). Pure structural walk — cheap, compile-time. */ -static int64_t count_agg_subexprs(ray_t* expr) { + * node as one hidden slot). Use the same source types as the rewrite. */ +static int64_t count_agg_subexprs(ray_t* expr, ray_t* tbl) { if (!expr) return 0; - if (is_group_dag_agg_expr(expr)) return 1; + if (is_group_dag_agg_expr(expr, tbl)) return 1; if (expr->type != RAY_LIST) return 0; ray_t** e = (ray_t**)ray_data(expr); int64_t n = ray_len(expr), c = 0; - for (int64_t i = 0; i < n; i++) c += count_agg_subexprs(e[i]); + for (int64_t i = 0; i < n; i++) c += count_agg_subexprs(e[i], tbl); return c; } @@ -4994,13 +6243,13 @@ static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl, ray_t* sel * Helper used inside the per-group hot loop (slices the table's column * via ray_at_fn, hands the slice to env_bind_local which retains, then * drops our ref). Returns 0 on success, error ray_t* on failure. */ -static ray_t* bind_col_slice(int64_t sym, ray_t* col, ray_t* idx_list) { - /* For typed-vec col + RAY_I64 idx vec, gather directly so the bound - * slice is the same typed vector as the source — `(at v idx)` would - * box every element into a RAY_LIST of atoms, which breaks any - * per-group expression that expects a numeric vec (`desc`, `take`, - * `asc`, etc.). Fall back to ray_at_fn for LIST inputs and other - * shapes the gather kernel doesn't cover. */ +/* The rows `idx_list` of `col`, owned. For typed-vec col + RAY_I64 idx + * vec, gather directly so the slice is the same typed vector as the + * source — `(at v idx)` would box every element into a RAY_LIST of atoms, + * which breaks any per-group expression that expects a numeric vec + * (`desc`, `take`, `asc`, etc.). Fall back to ray_at_fn for LIST inputs + * and other shapes the gather kernel doesn't cover. */ +static ray_t* slice_col_by_idx(ray_t* col, ray_t* idx_list) { ray_t* slice = NULL; if (col && ray_is_vec(col) && idx_list && idx_list->type == RAY_I64 && ray_is_vec(idx_list)) { @@ -5008,9 +6257,12 @@ static ray_t* bind_col_slice(int64_t sym, ray_t* col, ray_t* idx_list) { slice = gather_by_idx(col, (int64_t*)idx_data, ray_len(idx_list)); } if (!slice) slice = ray_at_fn(col, idx_list); - if (!slice || RAY_IS_ERR(slice)) { - return slice ? slice : ray_error("oom", NULL); - } + return slice ? slice : ray_error("oom", NULL); +} + +static ray_t* bind_col_slice(int64_t sym, ray_t* col, ray_t* idx_list) { + ray_t* slice = slice_col_by_idx(col, idx_list); + if (!slice || RAY_IS_ERR(slice)) return slice ? slice : ray_error("oom", NULL); ray_env_set_query_local(sym, slice); ray_release(slice); return NULL; @@ -5050,7 +6302,7 @@ static ray_t* typed_vec_to_list(ray_t* tv, int64_t fill, int64_t n_groups) { * Returns either a typed vec (homogeneous scalars) or a LIST col. */ typedef ray_t* (*idx_feeder_fn)(int64_t gi, void* state); -static ray_t* nonagg_eval_per_group_core(ray_t* expr, ray_t* tbl, +static ray_t* nonagg_eval_per_group_impl(ray_t* expr, ray_t* tbl, idx_feeder_fn feeder, void* fstate, int64_t n_groups) { /* Exact-size carve: collect_col_refs dedups against real table columns, @@ -5096,7 +6348,10 @@ static ray_t* nonagg_eval_per_group_core(ray_t* expr, ray_t* tbl, if (err) { ray_error_free(err); bound = 0; } } if (bound) { + ray_t* prev_group_idx = g_active_query_group_idx; + g_active_query_group_idx = empty_idx; ray_t* cell = ray_eval(expr); + g_active_query_group_idx = prev_group_idx; 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; @@ -5133,7 +6388,10 @@ static ray_t* nonagg_eval_per_group_core(ray_t* expr, ray_t* tbl, return err; } } + ray_t* prev_group_idx = g_active_query_group_idx; + g_active_query_group_idx = idx_list; ray_t* cell = ray_eval(expr); + g_active_query_group_idx = prev_group_idx; if (!cell || RAY_IS_ERR(cell)) { g_active_query_table = _aqt; ray_env_pop_scope(); @@ -5263,6 +6521,20 @@ static ray_t* nonagg_eval_per_group_core(ray_t* expr, ray_t* tbl, return result; } +static ray_t* nonagg_eval_per_group_core(ray_t* expr, ray_t* tbl, + idx_feeder_fn feeder, void* fstate, + int64_t n_groups) { + query_dependency_cache_t cache = { .table = tbl }; + query_dependency_cache_t* prev = g_query_dependencies; + g_query_dependencies = &cache; + ray_t* expanded = query_inline_helpers(expr, tbl); + ray_t* result = nonagg_eval_per_group_impl(expanded, tbl, feeder, fstate, n_groups); + ray_release(expanded); + for (int i = 0; i < cache.n; i++) ray_release(cache.exprs[i]); + g_query_dependencies = prev; + return result; +} + /* idx_feeder for the eval-fallback's LIST `groups` layout. */ typedef struct { ray_t** items; } groups_state_t; static ray_t* groups_idx_feed(int64_t gi, void* st) { @@ -5315,12 +6587,120 @@ static ray_t* nonagg_eval_per_group_buf(ray_t* expr, ray_t* tbl, return res; } +/* The evaluator has argument syntax here, unlike a builtin called from a + * lambda or apply. Only column-derived vectors use query text concat. + * Bare columns need no graph allocation on the per-group hot path. */ +static bool query_expr_reads_rows_on(ray_t* expr, ray_t* tbl) { + if (!tbl || tbl->type != RAY_TABLE || !expr) return false; + if (expr->type == -RAY_SYM) { + if (!(expr->attrs & ATTR_QUOTED)) { + /* A bound name carries its provenance; an unknown one (a + * closure's capture) falls back to the table. */ + int rows = ray_env_binding_rows(expr->i64); + if (rows == 1) return true; + if (rows == 0) return false; + } + if (ray_table_get_col(tbl, expr->i64)) return true; + if (!ray_sym_is_dotted(expr->i64)) return false; + } else if (expr->type != RAY_LIST) return false; + if (expr->type == RAY_LIST && expr->len == 3) { + ray_t** es = ray_data(expr); + if (es[0]->type == -RAY_SYM && es[0]->i64 == ray_sym_intern("as", 2)) + return query_expr_reads_rows_on(es[2], tbl); + } + if (expr->type == RAY_LIST && expr->len >= 2) { + ray_t** es = ray_data(expr); + if (es[0]->type == -RAY_SYM) { + int64_t id = es[0]->i64; + if (id == ray_sym_intern("reverse", 7) || id == ray_sym_intern("asc", 3) || + id == ray_sym_intern("desc", 4) || id == ray_sym_intern("at", 2)) + return query_expr_reads_rows_on(es[1], tbl); + } + } + if (ray_eval_query_helper_active()) { + if (expr->type != RAY_LIST || !expr->len || (expr->attrs & ATTR_QUOTED)) return false; + ray_t** es = ray_data(expr); + if (es[0]->type != -RAY_SYM) return false; + int64_t id = es[0]->i64; + ray_t* fn = ray_env_get(id); + if (!fn) return false; + /* An opaque helper's result over row data is row data: the VM + * tracks that inside the call; here only its arguments are known. */ + if (fn->type != RAY_LAMBDA && !ray_query_rowwise_builtin(id)) return false; + for (int64_t i = 1; i < expr->len; i++) + if (query_expr_reads_rows_on(es[i], tbl)) return true; + return false; + } + if (expr->type == RAY_LIST && expr->len >= 2) { + ray_t** es = ray_data(expr); + ray_t* fn = es[0]->type == -RAY_SYM && !(es[0]->attrs & ATTR_QUOTED) && + !ray_table_get_col(tbl, es[0]->i64) ? ray_env_get(es[0]->i64) : NULL; + if (fn && fn->type == RAY_LAMBDA) { + /* The planner inlines what it can; a helper it cannot lower + * yields row data when it was given row data. */ + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return false; + ray_op_t* op = compile_expr_dag(g, expr); + bool reads_rows = op && !op_tree_is_scalar(g, op->id); + bool lowered = op != NULL; + ray_graph_free(g); + if (lowered) return reads_rows; + for (int64_t i = 1; i < expr->len; i++) + if (query_expr_reads_rows_on(es[i], tbl)) return true; + return false; + } + } + query_dependency_cache_t* cache = g_query_dependencies; + if (cache && cache->table == tbl) + for (int i = 0; i < cache->n; i++) + if (cache->exprs[i] == expr) return cache->reads_rows[i]; + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return false; + ray_op_t* op = compile_expr_dag(g, expr); + bool reads_rows = op && !op_tree_is_scalar(g, op->id); + ray_graph_free(g); + if (cache && cache->table == tbl && cache->n < 64) { + cache->exprs[cache->n] = expr; + ray_retain(expr); + cache->reads_rows[cache->n++] = reads_rows; + } + return reads_rows; +} + +bool ray_query_expr_reads_rows(ray_t* expr) { + return query_expr_reads_rows_on(expr, g_active_query_table); +} + /* The value a literal column-name symbol stands for while a query is * active (see the literal rule in eval.c): the whole column, or — while a * per-row evaluation is running — that column's cell in the current row, * so `'price` reads what `price` reads wherever the expression is * evaluated. Owned ref; NULL when no query is active or the name is not a * column of it. */ +/* What a helper's free name that is a source column stands for: the whole + * column, or during a per-row evaluation the current row's cell, as the + * query's own expressions see it. Owned; NULL when `sym` is no column. */ +ray_t* ray_query_helper_value(int64_t sym) { + ray_t* src = ray_query_helper_table(); + if (!src || src->type != RAY_TABLE) return NULL; + ray_t* col = ray_table_get_col(src, sym); + if (!col) return NULL; + /* Per-group evaluation: the group's rows of the column, as the + * expression's own column references are bound. */ + if (g_active_query_group_idx && src == g_active_query_table) + return slice_col_by_idx(col, g_active_query_group_idx); + if (g_active_query_row < 0 || g_active_query_table != g_active_query_row_tbl || + g_active_query_row >= ray_len(col) || + ray_env_query_scope_above(g_active_query_row_depth)) { + ray_retain(col); return col; + } + int allocated = 0; + ray_t* cell = collection_elem(col, g_active_query_row, &allocated); + if (!cell || RAY_IS_ERR(cell)) return cell; + if (!allocated) ray_retain(cell); + return cell; +} + ray_t* ray_active_query_literal(int64_t sym) { ray_t* qt = g_active_query_table; if (!qt || qt->type != RAY_TABLE) return NULL; @@ -5338,7 +6718,7 @@ ray_t* ray_active_query_literal(int64_t sym) { return cell; } -static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { +static ray_t* eval_expr_per_row_impl(ray_t* expr, ray_t* tbl, int64_t nrows) { /* Exact-size carve, mirrors nonagg_eval_per_group_core: ncols(tbl) is * a hard upper bound for collect_col_refs's deduplicated table-column * output — no silent truncation past the former [16] cap. */ @@ -5346,10 +6726,15 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { if (ncols_max < 1) ncols_max = 1; ray_t* refs_hdr = NULL; int64_t* col_syms = (int64_t*)scratch_alloc(&refs_hdr, - (size_t)ncols_max * (sizeof(int64_t) + sizeof(ray_t*))); + (size_t)ncols_max * (sizeof(int64_t) + 2 * sizeof(ray_t*))); if (!col_syms) return ray_error("oom", NULL); int n_cols = collect_col_refs(expr, tbl, col_syms, (int)ncols_max, 0); ray_t** cols = (ray_t**)(col_syms + ncols_max); + /* The string cells marked for this row (RAY_ATTR_STR_CELL): the mark is + * cleared once the row is evaluated, so a cell the expression hands + * back inside a list or a dict leaves as a plain string. */ + ray_t** marked = cols + ncols_max; + int n_marked = 0; for (int i = 0; i < n_cols; i++) cols[i] = ray_table_get_col(tbl, col_syms[i]); @@ -5383,12 +6768,36 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { scratch_free(refs_hdr); return arg ? arg : ray_error("domain", "select: failed to read column cell for per-row eval"); } + /* A string cell is one value of its column, not a lone string + * literal: mark it so `in` answers it with one verdict + * (RAY_ATTR_STR_CELL). A cell read out of a LIST column is + * shared with it, so the mark goes on a copy. */ + if (arg->type == -RAY_STR) { + if (!allocated) { + ray_t* own = ray_str(ray_str_ptr(arg), ray_str_len(arg)); + if (!own || RAY_IS_ERR(own)) { + 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(); + if (result) ray_release(result); + scratch_free(refs_hdr); + return own ? own : ray_error("oom", NULL); + } + arg = own; + allocated = 1; + } + arg->attrs |= RAY_ATTR_STR_CELL; + marked[n_marked++] = arg; + } ray_env_set_query_local(col_syms[i], arg); if (allocated) ray_release(arg); } g_active_query_row = row; ray_t* cell = ray_eval(expr); + /* The query scope still holds each marked cell, so the pointers + * are live here. */ + for (int k = 0; k < n_marked; k++) marked[k]->attrs &= (uint8_t)~RAY_ATTR_STR_CELL; + n_marked = 0; if (!cell || RAY_IS_ERR(cell)) { 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(); @@ -5511,6 +6920,13 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { return result; } +static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { + ray_t* expanded = query_inline_helpers(expr, tbl); + ray_t* result = eval_expr_per_row_impl(expanded, tbl, nrows); + ray_release(expanded); + return result; +} + /* Evaluate a whole-column projection (is_whole_column_projection) ONCE against * the full table: every column is bound as a complete vector (via * bind_all_columns, exactly as the DAG path does) and the expression is @@ -5519,7 +6935,7 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { * defines its output column's length, which may differ from the table's row * count — the caller enforces cross-column length agreement. Mirrors * eval_expr_per_row's scope save/restore, including on every error exit. */ -static ray_t* eval_expr_whole_column(ray_t* expr, ray_t* tbl) { +static ray_t* eval_expr_whole_column_impl(ray_t* expr, ray_t* tbl) { if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); ray_t* _aqt = bind_all_columns(tbl); /* Whole columns here, even when a per-row evaluation of an outer select @@ -5540,6 +6956,13 @@ static ray_t* eval_expr_whole_column(ray_t* expr, ray_t* tbl) { return result; } +static ray_t* eval_expr_whole_column(ray_t* expr, ray_t* tbl) { + ray_t* expanded = query_inline_helpers(expr, tbl); + ray_t* result = eval_expr_whole_column_impl(expanded, tbl); + ray_release(expanded); + return result; +} + /* Zero groups still need the aggregate's column. Run the aggregate once over * an empty vector of the source's type so the empty column keeps the type a * non-empty result would have had; if that probe cannot run, an empty LIST @@ -6089,6 +7512,10 @@ static ray_t* query_materialize_parted_col(ray_t* col) { return flat; } +static int collect_col_refs_set(ray_t* expr, ray_t* tbl, + int64_t* out_syms, int max_out, int n); + + /* Planner rewrite for `(select {K: K c: (count (distinct X)) from: T * [where: W] by: K [desc: c take: N]})`. * @@ -6128,16 +7555,23 @@ static ray_t* try_count_distinct_v2_rewrite( * to the general per-group path, seven times slower than the dict form * of the same query. */ int64_t K_syms[15]; /* leave room for X in the composite */ + int64_t K_alias[15]; /* the output name of each key: the dict's name, + * else the source column's (the other paths emit + * the alias, so the rewrite must too — a planner + * choice may not change the result's names) */ int n_K = 0; if (by_expr && by_expr->type == -RAY_SYM && !(by_expr->attrs & ATTR_QUOTED)) { - K_syms[n_K++] = by_expr->i64; + K_alias[n_K] = K_syms[n_K] = by_expr->i64; n_K++; } else if (by_expr && by_expr->type == RAY_SYM && ray_is_vec(by_expr) && !(by_expr->attrs & ATTR_QUOTED)) { int64_t n = ray_len(by_expr); if (n == 0 || n > 15) return NULL; - for (int64_t i = 0; i < n; i++) - K_syms[n_K++] = ray_read_sym(ray_data(by_expr), i, by_expr->type, by_expr->attrs); + for (int64_t i = 0; i < n; i++) { + K_alias[n_K] = K_syms[n_K] = + ray_read_sym(ray_data(by_expr), i, by_expr->type, by_expr->attrs); + n_K++; + } } else if (by_expr && by_expr->type == RAY_DICT) { DICT_VIEW_DECL(byv); DICT_VIEW_OPEN(by_expr, byv); @@ -6145,17 +7579,31 @@ static ray_t* try_count_distinct_v2_rewrite( int64_t pairs = byv_n / 2; if (pairs == 0 || pairs > 15) { DICT_VIEW_CLOSE(byv); return NULL; } for (int64_t i = 0; i < pairs; i++) { + ray_t* a = byv[i * 2]; ray_t* v = byv[i * 2 + 1]; - if (!v || v->type != -RAY_SYM || (v->attrs & ATTR_QUOTED)) { + if (!a || a->type != -RAY_SYM || + !v || v->type != -RAY_SYM || (v->attrs & ATTR_QUOTED)) { DICT_VIEW_CLOSE(byv); return NULL; /* non-column-ref value — out of scope */ } - K_syms[n_K++] = v->i64; + /* an alias naming another input column is rejected by the + * by-dict materialization; let it report that */ + if (a->i64 != v->i64 && ray_table_get_col(tbl, a->i64)) { + DICT_VIEW_CLOSE(byv); + return NULL; + } + K_syms[n_K] = v->i64; K_alias[n_K] = a->i64; n_K++; } DICT_VIEW_CLOSE(byv); } else { return NULL; } + /* An alias that repeats a name is the by-dict's error; the other paths + * raise it. (An alias equal to the count's name is kept: every route + * emits the key under it first and the count under it second.) */ + for (int j = 0; j < n_K; j++) + for (int i = 0; i < j; i++) + if (K_alias[i] == K_alias[j] || K_syms[i] == K_syms[j]) return NULL; /* Walk the dict — accept exactly one `(count (distinct col_ref))` * agg and an optional identity key projection. Any other agg / @@ -6300,7 +7748,7 @@ static ray_t* try_count_distinct_v2_rewrite( } ray_t* out = ray_table_new(2); if (out && !RAY_IS_ERR(out)) - out = ray_table_add_col(out, K_syms[0], kv); + out = ray_table_add_col(out, K_alias[0], kv); if (out && !RAY_IS_ERR(out)) out = ray_table_add_col(out, cd_c_sym, fu); ray_release(kv); @@ -6313,6 +7761,27 @@ static ray_t* try_count_distinct_v2_rewrite( } } + /* The two-pass rewrite only where it wins (ray_cd_two_pass_preferred, + * cdfuse.c); the select otherwise groups by K and counts distinct X over + * the group slices (a by-dict of column refs is rewritten to a key + * vector on the way there). The estimates the gate takes describe the + * rows a `where:` keeps (query_cd_gate_where_rows): a filter that drops a + * dominant key value hides the groups and the shares of what remains. */ + { + const int64_t n_table = ray_table_nrows(tbl); + const int64_t* sel_rows = NULL; + int64_t sel_nrows = n_table, sel_pop = 0; + ray_t* sel_hdr = where_expr + ? query_cd_gate_where_rows(tbl, where_expr, n_table, &sel_rows, &sel_nrows, &sel_pop) + : NULL; + ray_pool_t* pool = ray_pool_get(); + int64_t workers = pool ? ray_pool_total_workers(pool) : 1; + bool two_pass = ray_cd_two_pass_preferred(K_cols, n_K, X_col, sel_rows, sel_nrows, + sel_pop, workers); + if (sel_hdr) scratch_free(sel_hdr); + if (!two_pass) return NULL; + } + /* === Inner pass: group by (K1, ..., Kn, X) on the source table === */ ray_graph_t* g_in = ray_graph_new(tbl); if (!g_in) return NULL; @@ -6356,6 +7825,12 @@ static ray_t* try_count_distinct_v2_rewrite( ray_graph_free(g_in); return (fres && RAY_IS_ERR(fres)) ? fres : NULL; } + /* The filter hands back an owned reference to the input table and + * leaves the matching rows on g_in->selection, which the group below + * reads. The constant node keeps the graph's own reference until + * ray_graph_free, so this one is dropped now; kept, it pinned `tbl` + * for good and the next insert into it copied every column (#757). */ + ray_release(fres); } ray_op_t* inner = ray_group(g_in, keys_in, n_K + 1, agg_ops_in, agg_ins_in, 1); @@ -6418,7 +7893,9 @@ static ray_t* try_count_distinct_v2_rewrite( * alias. The outer pass counts a key column, so ray_group names * the agg output "_count" — the result has the n_K key columns * plus this one count column. The count column is the one whose - * name matches none of the K syms. */ + * name matches none of the K syms. A by-dict's key columns then + * take their aliases (`{a: k1 b: k2}` → a, b), as every other grouping + * path names them. */ { int64_t nc = ray_table_ncols(result); for (int64_t ci = 0; ci < nc; ci++) { @@ -6430,6 +7907,16 @@ static ray_t* try_count_distinct_v2_rewrite( break; } } + int64_t key_ci[15]; /* positions first, then the renames: an + * alias may repeat another key's source name */ + for (int j = 0; j < n_K; j++) { + key_ci[j] = -1; + for (int64_t ci = 0; ci < nc; ci++) + if (ray_table_col_name(result, ci) == K_syms[j]) { key_ci[j] = ci; break; } + } + for (int j = 0; j < n_K; j++) + if (key_ci[j] >= 0 && K_alias[j] != K_syms[j]) + ray_table_set_col_name(result, key_ci[j], K_alias[j]); } /* Apply the user's desc:/asc:/take: clauses on the dedup'd, counted * output. The emit_filter trims to top-N during the outer pass but @@ -6450,6 +7937,18 @@ static ray_t* try_count_distinct_v2_rewrite( * match_count_distinct (typically a column ref, possibly a dotted-name * or computed sub-expression). Returns an I64 vector of length * n_groups with the per-group distinct count. */ +/* The per-group gathers of count_distinct_per_group_buf read `src` at the + * rows its groups list. On a mapped column that is not cached they would + * wait on one page fault at a time: request the pages those rows fall on + * first, runs of them as one range — clustered rows ask for their stretch + * of the column only. Scan read-ahead, so RAY_SCAN_PREFETCH=0 turns it off. */ +static void cd_want_group_rows(ray_t* src, const int64_t* idx_buf, + const int64_t* offsets, const int64_t* grp_cnt, + int64_t n_groups) { + if (!src || RAY_IS_ERR(src) || n_groups <= 0 || !ray_pool_scan_on()) return; + ray_col_want_rows(src, idx_buf, offsets[n_groups - 1] + grp_cnt[n_groups - 1]); +} + static ray_t* count_distinct_per_group_buf(ray_t* inner_expr, ray_t* tbl, const int64_t* idx_buf, const int64_t* offsets, @@ -6483,6 +7982,7 @@ static ray_t* count_distinct_per_group_buf(ray_t* inner_expr, ray_t* tbl, ray_release(src); return wide; } + cd_want_group_rows(src, idx_buf, offsets, grp_cnt, n_groups); ray_t* out = ray_vec_new(RAY_I64, n_groups); if (!out || RAY_IS_ERR(out)) { @@ -6730,11 +8230,19 @@ static inline int64_t key_read_i64(const void* d, int64_t idx, case RAY_TIME: return ((const int32_t*)d)[idx]; case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)d)[idx]; + /* F32/F64: the bits, with -0.0 canonicalised to +0.0 the way the + * grouping reads its keys (group_key_f64_bits, #407). The group result + * holds +0.0 for the merged zero group; a row carrying -0.0 read raw + * would miss it and be dropped from every per-group kernel (#760). + * Bit-level, as there: release builds use -fno-signed-zeros, under + * which a value compare against 0.0 folds to a no-op. */ case RAY_F32: { uint32_t u; memcpy(&u, &((const float*)d)[idx], 4); + if (u == 0x80000000u) u = 0; return (int64_t)u; } case RAY_F64: { int64_t u; memcpy(&u, &((const double*)d)[idx], 8); + if (u == INT64_MIN) u = 0; return u; } /* SYM: raw index — callers compare cells of the source column * against cells of a group-key column DERIVED from it (same @@ -6924,6 +8432,239 @@ static void rgid_probe_str_fn(void* ctx_, uint32_t worker_id, } } +/* Composite (multi-key) row→gid probe: the sibling of rgid_probe_fn for a + * `by: [k1 k2 ...]` of fixed-width / SYM keys (#756). The hash table maps + * each result group's key tuple (gk[gid * nk ..]) to gid + 1; a row hashes + * its nk key cells, read as int64 the way the single-key probe reads them, + * and walks the slots comparing tuples. Rows a selection drops get -1, as + * in rgid_probe_fn. The table is read-only and row_gid writes are + * disjoint, so workers need no synchronisation. */ +typedef struct { + int nk; + const void* const* key_data; /* [nk] flat source key column data */ + const int8_t* key_type; /* [nk] */ + const uint8_t* key_attrs; /* [nk] */ + const int64_t* gk; /* [n_groups * nk] group key tuples */ + const int64_t* hk_gid_p1; /* [mask + 1]: gid + 1, 0 = empty */ + uint64_t mask; + int64_t* row_gid; + const uint8_t* sel_flg; /* NULL: every row */ + const uint32_t* sel_offs; + const uint16_t* sel_idx; + uint32_t sel_n_segs; +} rgid_probe_mk_ctx_t; + +static inline uint64_t rgid_mk_hash_step(uint64_t h, int64_t v) { + h ^= (uint64_t)v; + h *= 0x9E3779B97F4A7C15ULL; + h ^= h >> 33; + return h; +} + +static inline int64_t rgid_mk_probe_row(const rgid_probe_mk_ctx_t* x, int64_t r) { + uint64_t h = 0x9E3779B97F4A7C15ULL; + for (int k = 0; k < x->nk; k++) + h = rgid_mk_hash_step(h, key_read_i64(x->key_data[k], r, + x->key_type[k], x->key_attrs[k])); + uint64_t s = h & x->mask; + for (;;) { + int64_t g_p1 = x->hk_gid_p1[s]; + if (g_p1 == 0) return -1; + const int64_t* t = x->gk + (g_p1 - 1) * x->nk; + int k = 0; + for (; k < x->nk; k++) + if (t[k] != key_read_i64(x->key_data[k], r, x->key_type[k], x->key_attrs[k])) + break; + if (k == x->nk) return g_p1 - 1; + s = (s + 1) & x->mask; + } +} + +static void rgid_probe_mk_fn(void* ctx_, uint32_t worker_id, + int64_t start, int64_t end) { + (void)worker_id; + const rgid_probe_mk_ctx_t* x = (const rgid_probe_mk_ctx_t*)ctx_; + if (!x->sel_flg) { + for (int64_t r = start; r < end; r++) x->row_gid[r] = rgid_mk_probe_row(x, r); + return; + } + uint32_t seg_lo = (uint32_t)(start / RAY_MORSEL_ELEMS); + uint32_t seg_hi = (uint32_t)((end + RAY_MORSEL_ELEMS - 1) / RAY_MORSEL_ELEMS); + if (seg_hi > x->sel_n_segs) seg_hi = x->sel_n_segs; + int64_t covered = start; + for (uint32_t seg = seg_lo; seg < seg_hi; seg++) { + int64_t base = (int64_t)seg * RAY_MORSEL_ELEMS; + int64_t s_lo = base, s_hi = base + RAY_MORSEL_ELEMS; + if (s_lo < start) s_lo = start; + if (s_hi > end) s_hi = end; + covered = s_hi; + uint8_t f = x->sel_flg[seg]; + if (f == RAY_SEL_NONE) { + for (int64_t r = s_lo; r < s_hi; r++) x->row_gid[r] = -1; + } else if (f == RAY_SEL_ALL) { + for (int64_t r = s_lo; r < s_hi; r++) x->row_gid[r] = rgid_mk_probe_row(x, r); + } else { + uint8_t in_seg[RAY_MORSEL_ELEMS / 8] = {0}; + uint32_t off = x->sel_offs[seg]; + uint32_t cnt = x->sel_offs[seg + 1] - off; + for (uint32_t i = 0; i < cnt; i++) { + uint16_t loc = x->sel_idx[off + i]; + in_seg[loc >> 3] |= (uint8_t)(1u << (loc & 7)); + } + for (int64_t r = s_lo; r < s_hi; r++) { + uint16_t loc = (uint16_t)(r - base); + x->row_gid[r] = (in_seg[loc >> 3] & (1u << (loc & 7))) + ? rgid_mk_probe_row(x, r) : -1; + } + } + } + /* rows past the selection's last segment are not selected */ + for (int64_t r = covered; r < end; r++) x->row_gid[r] = -1; +} + +/* The base types the composite probe reads: KEY_READ's coverage less STR, + * which the single-key scatter resolves through its own descriptor probe. */ +static int rgid_mk_key_type_ok(int8_t bt) { + switch (bt) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_F32: case RAY_F64: case RAY_DATE: case RAY_TIME: + case RAY_TIMESTAMP: case RAY_SYM: + return 1; + default: + return 0; + } +} + +/* True when `by_expr` is a `by: [k1 k2 ...]` whose keys are all columns of + * `tbl` the composite probe can read. Such a select stays on the DAG path + * when its only non-DAG outputs are count(distinct) aggregates and literal + * broadcasts; the post-group scatter then maps rows to groups through + * rgid_build_multikey. STR, GUID, LIST and mapcommon keys keep their + * existing routes. */ +static int multikey_scatter_keys_ok(ray_t* by_expr, ray_t* tbl) { + if (!by_expr || by_expr->type != RAY_SYM || ray_len(by_expr) < 2) return 0; + const int64_t* ids = (const int64_t*)ray_data(by_expr); + for (int64_t k = 0; k < ray_len(by_expr); k++) { + ray_t* col = ray_table_get_col(tbl, ids[k]); + if (!col || col->type == RAY_MAPCOMMON) return 0; + int8_t bt = col->type; + if (RAY_IS_PARTED(bt)) bt = (int8_t)RAY_PARTED_BASETYPE(bt); + if (!rgid_mk_key_type_ok(bt)) return 0; + } + return 1; +} + +/* Build row_gid[nrows] for a composite key: one tuple per result group from + * `result`'s key columns, hashed; then every row of `tbl`'s key columns is + * probed (in parallel when the input is large). Parted source keys are + * flattened for the probe. Rows `selection` drops get -1. Returns NULL on + * success, else an owned error. */ +static ray_t* rgid_build_multikey(ray_t* tbl, ray_t* result, ray_t* by_expr, + int64_t nrows, int64_t n_groups, + ray_t* selection, int64_t* row_gid) { + int nk = (int)ray_len(by_expr); + const int64_t* ids = (const int64_t*)ray_data(by_expr); + ray_t* err = NULL; + ray_t* cols_hdr = NULL; + ray_t* gk_hdr = NULL; + ray_t* slot_hdr = NULL; + /* [nk] scan columns, [nk] owned flags, [nk] data, [nk] types, [nk] attrs */ + size_t cols_sz = (size_t)nk * (2 * sizeof(ray_t*) + sizeof(void*) + 2); + uint8_t* cols_mem = (uint8_t*)scratch_calloc(&cols_hdr, cols_sz); + if (!cols_mem) return ray_error("oom", NULL); + ray_t** scan = (ray_t**)cols_mem; + ray_t** grp = scan + nk; + const void** kdata = (const void**)(grp + nk); + int8_t* ktype = (int8_t*)(kdata + nk); + uint8_t* kattr = (uint8_t*)(ktype + nk); + uint8_t* owned = NULL; + ray_t* owned_hdr = NULL; + owned = (uint8_t*)scratch_calloc(&owned_hdr, (size_t)nk); + if (!owned) { scratch_free(cols_hdr); return ray_error("oom", NULL); } + + for (int k = 0; k < nk && !err; k++) { + ray_t* orig = ray_table_get_col(tbl, ids[k]); + ray_t* g = ray_table_get_col(result, ids[k]); + if (!orig || !g) { err = ray_error("domain", "select by: group key column not found"); break; } + ray_t* sc = orig; + if (RAY_IS_PARTED(sc->type) || sc->type == RAY_MAPCOMMON) { + sc = query_materialize_parted_col(sc); + if (!sc || RAY_IS_ERR(sc)) { err = sc ? sc : ray_error("oom", NULL); break; } + owned[k] = 1; + } + if (!rgid_mk_key_type_ok(sc->type) || g->type != sc->type || + ray_len(sc) != nrows || ray_len(g) != n_groups) { + if (owned[k]) ray_release(sc); + owned[k] = 0; + err = ray_error("type", "group key type mismatch"); + break; + } + scan[k] = sc; grp[k] = g; + kdata[k] = ray_data(sc); ktype[k] = sc->type; kattr[k] = sc->attrs; + } + + uint64_t cap = 0, mask = 0; + int64_t* gk = NULL; + int64_t* slot = NULL; + if (!err) { + cap = (uint64_t)n_groups * 2; + if (cap < 32) cap = 32; + uint64_t c = 1; + while (c && c < cap) c <<= 1; + if (!c) err = ray_error("oom", NULL); + else { + cap = c; mask = cap - 1; + gk = (int64_t*)scratch_alloc(&gk_hdr, (size_t)n_groups * (size_t)nk * sizeof(int64_t)); + slot = (int64_t*)scratch_calloc(&slot_hdr, (size_t)cap * sizeof(int64_t)); + if (!gk || !slot) err = ray_error("oom", NULL); + } + } + if (!err) { + for (int64_t gi = 0; gi < n_groups; gi++) + for (int k = 0; k < nk; k++) + gk[gi * nk + k] = key_read_i64(ray_data(grp[k]), gi, grp[k]->type, grp[k]->attrs); + for (int64_t gi = 0; gi < n_groups; gi++) { + const int64_t* t = gk + gi * nk; + uint64_t h = 0x9E3779B97F4A7C15ULL; + for (int k = 0; k < nk; k++) h = rgid_mk_hash_step(h, t[k]); + uint64_t s = h & mask; + for (;;) { + int64_t cur = slot[s]; + if (cur == 0) { slot[s] = gi + 1; break; } + const int64_t* u = gk + (cur - 1) * nk; + int k = 0; + for (; k < nk; k++) if (u[k] != t[k]) break; + if (k == nk) break; /* duplicate tuple — keep the first */ + s = (s + 1) & mask; + } + } + rgid_probe_mk_ctx_t ctx = { + .nk = nk, .key_data = kdata, .key_type = ktype, .key_attrs = kattr, + .gk = gk, .hk_gid_p1 = slot, .mask = mask, .row_gid = row_gid, + .sel_flg = NULL, .sel_offs = NULL, .sel_idx = NULL, .sel_n_segs = 0, + }; + if (selection) { + ray_rowsel_t* sm = ray_rowsel_meta(selection); + ctx.sel_flg = ray_rowsel_flags(selection); + ctx.sel_offs = ray_rowsel_offsets(selection); + ctx.sel_idx = ray_rowsel_idx(selection); + ctx.sel_n_segs = sm->n_segs; + } + ray_pool_t* pool = ray_pool_get(); + if (pool && nrows >= 200000 && ray_pool_total_workers(pool) >= 2) + ray_pool_dispatch(pool, rgid_probe_mk_fn, &ctx, nrows); + else + rgid_probe_mk_fn(&ctx, 0, 0, nrows); + } + + for (int k = 0; k < nk; k++) if (owned[k] && scan[k]) ray_release(scan[k]); + if (gk_hdr) scratch_free(gk_hdr); + if (slot_hdr) scratch_free(slot_hdr); + scratch_free(owned_hdr); + scratch_free(cols_hdr); + return err; +} + /* Forward declarations for eval-level groupby fallback */ /* R8: cheap predicate for whether atom_broadcast_vec can handle this @@ -7142,9 +8883,14 @@ static ray_t* eval_scalar_agg_outputs(ray_t** dict_elems, int64_t dict_n, * would feed it one scalar cell at a time, making `count` report the * row count instead of the distinct count (issue #405). Mirror the * projection fallback's routing and evaluate it once. */ - ray_t* src = is_whole_column_projection(agg_elems[1]) - ? eval_expr_whole_column(agg_elems[1], tbl) - : eval_expr_per_row(agg_elems[1], tbl, nrows); + /* Expand helpers first: a pure helper around such a verb is the + * verb, and must not be fed one cell at a time either. */ + ray_t* agg_src_expr = query_inline_helpers(agg_elems[1], tbl); + ray_t* src = (is_whole_column_projection(agg_src_expr, tbl) || + expr_is_constant_collection(agg_src_expr, tbl, NULL)) + ? eval_expr_whole_column_impl(agg_src_expr, tbl) + : eval_expr_per_row_impl(agg_src_expr, tbl, nrows); + ray_release(agg_src_expr); if (!src || RAY_IS_ERR(src)) { ray_release(result); return src ? src : ray_error("domain", "select: failed to evaluate aggregation source"); @@ -8226,7 +9972,7 @@ static ray_t* try_temporal_group_materialize(ray_t* dict, ray_t* tbl) { #define MAT_CHECK(value) do { if (!(value) || RAY_IS_ERR(value)) { failure = (value); (value) = NULL; goto oom; } } while (0) for (int64_t i = 0; i < ray_dict_len(dict); i++) { ray_t* expr = ray_list_get(vals, i); - if (!expr || !is_group_dag_agg_expr(expr)) continue; + if (!expr || !is_group_dag_agg_expr(expr, tbl)) continue; ray_t** es = ray_data(expr); uint16_t kind = resolve_agg_opcode(es[0]->i64); int argc = agg_is_binary_agg(kind) ? 2 : 1; @@ -8359,6 +10105,25 @@ static ray_t* select_fallback_broadcast(ray_t* v, int64_t n) { return wide; } +/* Scalar columns stay one cell until every collection length is known. + * This also handles an empty source and scalar outputs before a collection. */ +static ray_t* select_fallback_finish_columns(ray_t* result, uint32_t* scalar_cols, + int64_t nrows) { + for (int64_t c = 0; c < ray_table_ncols(result); c++) { + if (!scalar_cols[c]) continue; + ray_t* col = ray_table_get_col_idx(result, c); + ray_retain(col); + ray_t* wide = select_fallback_broadcast(col, nrows); + if (!wide || RAY_IS_ERR(wide)) { + ray_release(result); + return wide ? wide : ray_error("oom", NULL); + } + ray_table_set_col_idx(result, c, wide); + ray_release(wide); + } + return result; +} + 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); @@ -8582,6 +10347,53 @@ static ray_t* select_alias_map_list(ray_t* expr, int64_t from, select_alias_map_ return out; } +/* ── where: is alias-blind to a by-dict's keys ─────────────────────────── + * The eager by-dict path adds each alias as a column of the table the rest + * of the select is compiled over. A literal symbol naming a from-table + * column resolves to that column (B3 Part 2), so `{a: k1} where: (!= k1 'a)` + * read `'a` as the new alias column and compared k1 with itself — no rows — + * while the two-pass distinct-count rewrite and the deferred parted route, + * which add no column, kept the symbol. where: names source columns only + * (like by: and the sort keys), so before the aliases are added every + * literal in it that names an alias the table does not already hold is + * wrapped in `(quote …)`, which the compiler folds to the symbol (the + * literal_col_ref contract: Part 2 unwraps the tick atom, not a quote call). + * The wrapped atom keeps the shape ray_quote_fn gives it. `sub` returns an + * owned expression; `changed` says whether any literal was wrapped. */ +typedef struct { + ray_t** d_elems; /* the by-dict's [key value] pairs */ + int64_t nk; + ray_t* tbl; + bool changed; +} where_shield_ctx_t; + +static ray_t* select_where_shield_alias_literals(ray_t* e, void* vctx) { + where_shield_ctx_t* c = (where_shield_ctx_t*)vctx; + if (!e) return NULL; + if (e->type == -RAY_SYM) { + if (!(e->attrs & ATTR_QUOTED)) { ray_retain(e); return e; } + bool names_alias = false; + for (int64_t i = 0; i < c->nk && !names_alias; i++) { + ray_t* k = c->d_elems[i * 2]; + names_alias = k && k->type == -RAY_SYM && k->i64 == e->i64 && + !ray_table_get_col(c->tbl, k->i64); + } + if (!names_alias) { ray_retain(e); return e; } + 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, e); + if (head && !RAY_IS_ERR(head)) ray_release(head); + if (!wrap || RAY_IS_ERR(wrap)) return wrap ? wrap : ray_error("oom", NULL); + c->changed = true; + return wrap; + } + if (e->type != RAY_LIST || e->len < 1) { ray_retain(e); return e; } + ray_t** el = (ray_t**)ray_data(e); + if (select_sym_is(el[0], "quote", 5)) { ray_retain(e); return e; } + return select_alias_map_list(e, 0, select_where_shield_alias_literals, c); +} + /* ── 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 @@ -8950,7 +10762,7 @@ static bool select_derived_needs_rows(ray_t* expr) { * one visible to the next), drops the hidden aggregate columns, restores * the dict's output order and applies the sort keys and take: that were * held back. Consumes `result`. */ -static ray_t* select_apply_derived(ray_t* result, ray_t* dict, select_alias_plan_t* plan) { +static ray_t* select_apply_derived(ray_t* result, ray_t* dict, select_alias_plan_t* plan, ray_t* source) { if (!result || RAY_IS_ERR(result)) return result; if (ray_is_lazy(result)) result = ray_lazy_materialize(result); if (!result || RAY_IS_ERR(result)) return result; @@ -8958,9 +10770,20 @@ static ray_t* select_apply_derived(ray_t* result, ray_t* dict, select_alias_plan int64_t n_groups = ray_table_nrows(result); for (int64_t d = 0; d < plan->n_derived; d++) { ray_t* expr = plan->derived_exprs[d]; + /* The group result carries no source rows: a helper's free name + * that named a source column means its global binding here, and an + * output alias never captures it. */ + ray_t* expanded = NULL; + if (query_expr_has_helper(expr) && query_expr_effect_free(expr)) { + int budget = 1024; + query_inline_scope_t scope = { .globals_for_source = true }; + expanded = query_inline_walk(expr, source, NULL, 0, 0, &budget, false, &scope); + } + if (!expanded) { ray_retain(expr); expanded = expr; } ray_t* col = select_derived_needs_rows(expr) - ? eval_expr_per_row(expr, result, n_groups) - : eval_expr_whole_column(expr, result); + ? eval_expr_per_row_impl(expanded, result, n_groups) + : eval_expr_whole_column_impl(expanded, result); + ray_release(expanded); if (!col || RAY_IS_ERR(col)) { ray_release(result); return col ? col : ray_error("oom", NULL); } if (ray_is_lazy(col)) col = ray_lazy_materialize(col); if (!col || RAY_IS_ERR(col)) { ray_release(result); return col ? col : ray_error("oom", NULL); } @@ -8983,39 +10806,724 @@ static ray_t* select_apply_derived(ray_t* result, ray_t* dict, select_alias_plan int64_t take_id = ray_sym_intern("take", 4), asc_id = ray_sym_intern("asc", 3), desc_id = ray_sym_intern("desc", 4); int64_t nearest_id = ray_sym_intern("nearest", 7); int64_t ncols = ray_table_ncols(result); + /* Already laid out — keys, then the outputs in the dict's order, no + * hidden slots and no repeated name — leaves nothing to do. This is + * the common case for a grouped fallback with one output. */ + if (plan->n_hidden == 0) { + int64_t c = 0, want = 0; + bool laid_out = true; + for (int64_t i = 0; i + 1 < dv_n && laid_out; i += 2) { + int64_t cn = dv[i]->i64; + if (cn == from_id || cn == where_id || cn == by_id || cn == take_id || cn == asc_id || cn == desc_id || cn == nearest_id) continue; + if (!ray_table_get_col(result, cn)) continue; /* folded away */ + want++; + while (c < ncols && ray_table_col_name(result, c) != cn) { + /* a key: must not be named like any output */ + int64_t kn = ray_table_col_name(result, c); + for (int64_t j = 0; j + 1 < dv_n && laid_out; j += 2) if (dv[j]->i64 == kn) laid_out = false; + c++; + } + if (c >= ncols) laid_out = false; + else c++; + } + if (c != ncols) laid_out = false; /* trailing columns: misplaced */ + if (laid_out && want > 0) { + if (plan->sort_after) + result = apply_sort_take(result, dv, dv_n, asc_id, desc_id, take_id, NULL); + DICT_VIEW_CLOSE(dv); + return result; + } + } ray_t* out = ray_table_new(ncols); if (!out || RAY_IS_ERR(out)) { DICT_VIEW_CLOSE(dv); ray_release(result); return out ? out : ray_error("oom", NULL); } + /* An output may carry a key's name (`{k: (first x) … by: k}`): the + * engine then emits both, the key first. The last column of a name is + * the output; any earlier one is a key. */ for (int64_t c = 0; c < ncols && out && !RAY_IS_ERR(out); c++) { int64_t cn = ray_table_col_name(result, c); - bool is_output = false, is_hidden = false; + bool is_output = false, is_hidden = false, last = true; for (int64_t i = 0; i + 1 < dv_n; i += 2) if (dv[i]->i64 == cn && cn != from_id && cn != where_id && cn != by_id && cn != take_id && cn != asc_id && cn != desc_id && cn != nearest_id) { is_output = true; break; } for (int64_t h = 0; h < plan->n_hidden; h++) if (plan->hidden_names[h] == cn) { is_hidden = true; break; } - if (is_output || is_hidden) continue; + for (int64_t c2 = c + 1; c2 < ncols && last; c2++) + if (ray_table_col_name(result, c2) == cn) last = false; + if ((is_output && last) || is_hidden) continue; out = ray_table_add_col(out, cn, ray_table_get_col_idx(result, c)); } for (int64_t i = 0; i + 1 < dv_n && out && !RAY_IS_ERR(out); i += 2) { int64_t cn = dv[i]->i64; if (cn == from_id || cn == where_id || cn == by_id || cn == take_id || cn == asc_id || cn == desc_id || cn == nearest_id) continue; - ray_t* col = ray_table_get_col(result, cn); + ray_t* col = NULL; + for (int64_t c = ncols - 1; c >= 0 && !col; c--) + if (ray_table_col_name(result, c) == cn) col = ray_table_get_col_idx(result, c); if (!col) continue; /* an output the engine folded away (e.g. a key projection) */ out = ray_table_add_col(out, cn, col); } - if (!out || RAY_IS_ERR(out)) { DICT_VIEW_CLOSE(dv); ray_release(result); return out ? out : ray_error("oom", NULL); } - ray_release(result); - result = out; - if (plan->sort_after) - result = apply_sort_take(result, dv, dv_n, asc_id, desc_id, take_id, NULL); - DICT_VIEW_CLOSE(dv); - return result; + if (!out || RAY_IS_ERR(out)) { DICT_VIEW_CLOSE(dv); ray_release(result); return out ? out : ray_error("oom", NULL); } + ray_release(result); + result = out; + if (plan->sort_after) + result = apply_sort_take(result, dv, dv_n, asc_id, desc_id, take_id, NULL); + DICT_VIEW_CLOSE(dv); + return result; +} + +/* -------------------------------------------------------------------------- + * Scan read-ahead for a select (see ray_pool_scan_set in core/pool.c) + * + * ray_select opens a registration; once the source table is known the + * select registers the mapped columns its clauses name, and the zone-index + * verdict of its filter, so every dispatch it runs, fast paths included, + * keeps the rows just ahead of its workers requested from storage. + * + * A filter the zones say nothing about may keep a handful of rows; the + * columns only read after it are then held back (`defer`) until its + * selection is known (ray_select_scan_filtered): read whole when the + * selected rows land on most of their pages, else only those pages. + * -------------------------------------------------------------------------- */ +typedef struct { + ray_pool_scan_t scan; + ray_pool_scan_t defer; /* read after the filter, requested once it ran */ + ray_t** args; /* the select this registration belongs to */ + ray_t* gate_hdr; /* scratch block behind scan.gate */ + bool filled; +} select_scan_t; +static RAY_TLS select_scan_t* t_select_scan; + +static bool scan_gate_int_type(int8_t t) { + return t == RAY_BOOL || t == RAY_U8 || t == RAY_I16 || t == RAY_I32 || t == RAY_I64; +} + +static bool scan_gate_temporal(int8_t t) { + return t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP; +} + +/* A non-null integer or temporal constant that compares with a `ct` column + * on its stored value. */ +static bool scan_gate_atom(ray_t* a, int8_t ct, int64_t* out) { + if (!a || !ray_is_atom(a) || RAY_ATOM_IS_NULL(a)) return false; + int8_t t = (int8_t)-a->type; + if (scan_gate_temporal(ct) ? t != ct : !scan_gate_int_type(t)) return false; + switch (t) { + case RAY_I32: *out = a->i32; return true; + case RAY_I16: *out = a->i16; return true; + case RAY_U8: *out = a->u8; return true; + case RAY_BOOL: *out = a->b8; return true; + default: *out = a->i64; return true; /* I64, DATE, TIME, TIMESTAMP */ + } +} + +/* The [lo hi] literal of a `within`. */ +static bool scan_gate_range(ray_t* v, int8_t ct, int64_t* lo, int64_t* hi) { + if (!v || !ray_is_vec(v) || v->len != 2 || ray_vec_has_nulls(v)) return false; + if (scan_gate_temporal(ct) ? v->type != ct : !scan_gate_int_type(v->type)) return false; + *lo = read_col_i64(ray_data(v), 0, v->type, v->attrs); + *hi = read_col_i64(ray_data(v), 1, v->type, v->attrs); + return true; +} + +/* Clear the gate chunks where conjunct `e` holds for no row. Shapes: + * (op col c) for op in == < <= > >=, and (within col [lo hi]), over an + * integer or temporal column with a chunk-zone index; anything else rules + * nothing out. A null ranks below every value (null < c holds), so a + * chunk holding nulls always passes < and <=. */ +static void scan_gate_conjunct(select_scan_t* ss, ray_t* e, ray_t* tbl) { + enum { G_EQ, G_LT, G_LE, G_GT, G_GE, G_WITHIN }; + if (!e || e->type != RAY_LIST || ray_len(e) != 3) return; + ray_t** el = (ray_t**)ray_data(e); + if (!el[0] || el[0]->type != -RAY_SYM) return; + ray_t* fs = ray_sym_str(el[0]->i64); + if (!fs) return; + const char* f = ray_str_ptr(fs); + size_t fl = ray_str_len(fs); + int op; + if (fl == 2 && memcmp(f, "==", 2) == 0) op = G_EQ; + else if (fl == 1 && f[0] == '<') op = G_LT; + else if (fl == 2 && memcmp(f, "<=", 2) == 0) op = G_LE; + else if (fl == 1 && f[0] == '>') op = G_GT; + else if (fl == 2 && memcmp(f, ">=", 2) == 0) op = G_GE; + else if (fl == 6 && memcmp(f, "within", 6) == 0) op = G_WITHIN; + else return; + if (!el[1] || el[1]->type != -RAY_SYM || (el[1]->attrs & ATTR_QUOTED)) return; + ray_t* col = ray_table_get_col(tbl, el[1]->i64); + if (!col || !ray_is_vec(col) || col->len != ss->scan.rows) return; + int8_t ct = col->type; + if (!scan_gate_int_type(ct) && !scan_gate_temporal(ct)) return; + if (ray_index_kind(col) != RAY_IDX_CHUNK_ZONE) return; + const ray_index_t* ix = ray_index_payload(col->index); + if (ix->built_for_len != col->len || ix->u.chunk_zone.is_f64 || + !ix->u.chunk_zone.mins || !ix->u.chunk_zone.maxs || !ix->u.chunk_zone.null_bits) return; + uint32_t nch = ix->u.chunk_zone.n_chunks; + uint8_t lg = ix->u.chunk_zone.chunk_log2; + if (lg >= 40 || ((int64_t)nch << lg) < col->len) return; + int64_t lo = 0, hi = 0; + if (op == G_WITHIN ? !scan_gate_range(el[2], ct, &lo, &hi) + : !scan_gate_atom(el[2], ct, &lo)) return; + if (!ss->scan.gate) { + size_t words = ((size_t)nch + 63) / 64; + uint64_t* g = (uint64_t*)scratch_alloc(&ss->gate_hdr, words * sizeof(uint64_t)); + if (!g) return; + memset(g, 0xff, words * sizeof(uint64_t)); + ss->scan.gate = g; + ss->scan.gate_log2 = lg; + } else if (ss->scan.gate_log2 != lg) { + return; + } + uint64_t* g = (uint64_t*)ss->scan.gate; + const int64_t* mins = (const int64_t*)ray_data(ix->u.chunk_zone.mins); + const int64_t* maxs = (const int64_t*)ray_data(ix->u.chunk_zone.maxs); + const uint8_t* nb = (const uint8_t*)ray_data(ix->u.chunk_zone.null_bits); + for (uint32_t c = 0; c < nch; c++) { + int64_t mn = mins[c], mx = maxs[c]; + bool nulls = (nb[c >> 3] >> (c & 7)) & 1; + bool pass; + if (mn > mx) pass = (op == G_LT || op == G_LE) && nulls; /* no non-null value */ + else switch (op) { + case G_EQ: pass = lo >= mn && lo <= mx; break; + case G_LT: pass = nulls || mn < lo; break; + case G_LE: pass = nulls || mn <= lo; break; + case G_GT: pass = mx > lo; break; + case G_GE: pass = mx >= lo; break; + default: pass = mx >= lo && mn <= hi; break; + } + if (!pass) g[c >> 6] &= ~(UINT64_C(1) << (c & 63)); + } +} + +/* Walk the top-level `and` of a filter. */ +static void scan_gate_where(select_scan_t* ss, ray_t* e, ray_t* tbl, int depth) { + if (!e || e->type != RAY_LIST || depth > 8) return; + int64_t n = ray_len(e); + ray_t** el = (ray_t**)ray_data(e); + if (n >= 2 && el[0] && el[0]->type == -RAY_SYM) { + ray_t* fs = ray_sym_str(el[0]->i64); + if (fs && ray_str_len(fs) == 3 && memcmp(ray_str_ptr(fs), "and", 3) == 0) { + for (int64_t i = 1; i < n; i++) scan_gate_where(ss, el[i], tbl, depth + 1); + return; + } + } + scan_gate_conjunct(ss, e, tbl); +} + +/* The rows a `where:` keeps, for the route gate below — sampled, not + * evaluated in full: CD_GATE_WHERE_SAMPLE rows of the table are read at the + * estimator's hashed stride (agg_est_sample_row), the columns the predicate + * names gathered from them into a table of that many rows, and the + * predicate run over it as the select would run it. The survivors' table + * rows come back in *rows (nrows of them), with *population the rows the + * whole predicate would keep, scaled from the sample; the estimates over + * them describe the filtered table. Running the predicate over the whole + * table instead cost 18 ms of a 90 ms select at 100 M rows when the gate + * then chose the slices, whose path evaluates it again; this costs a few, + * the gather over the pool's threads. The pages the sampled rows fall on + * are asked for ahead of the reads (ray_col_want_rows — at this stride + * about every page of a mapped column, requested through the pool as the + * select's own scan would): read as they were met, a column not in memory + * waited on a page fault per sampled row, on this thread, 0.8 s and more + * of a half-second select at 100 M rows. + * The sample is drawn from the chunks the select's own zone gate lets + * through (scan_gate_where: a conjunct over an integer or temporal column + * with a chunk-zone index): a filter on a slice of a time-ordered column + * reads the pages of its chunks, not every page of the column, and the + * key and value columns are then asked for over that slice too. + * NULL — the gate then estimates over the whole table — when the predicate + * names no column, names one the gather does not cover (text, nested, + * parted), keeps every sampled row, or memory runs out. The returned + * block owns the row list; scratch_free it after the gate. */ +enum { CD_GATE_WHERE_SAMPLE = AGG_EST_SAMPLE_ROWS * 8 }; + +/* The sampled rows of the predicate's columns gathered over a range of the + * sample: a task of the pool, the columns in turn. */ +typedef struct { + const void* const* src; + void* const* dst; + const uint8_t* esz; + const int64_t* idx; + int n; +} cd_gate_gather_ctx_t; + +static void cd_gate_gather_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + const cd_gate_gather_ctx_t* c = raw; + const int64_t* idx = c->idx; + enum { AHEAD = 16 }; + for (int j = 0; j < c->n; j++) { + /* the sampled rows miss the cache: typed loads with reads kept in + * flight (a byte-wise copy serialised them, 25 ms for the 262,144) */ + switch (c->esz[j]) { +#define CD_GATE_GATHER(T) do { \ + const T* sp = (const T*)c->src[j]; T* dp = (T*)c->dst[j]; \ + for (int64_t r = start; r < end; r++) { \ + if (r + AHEAD < end) __builtin_prefetch(sp + idx[r + AHEAD]); \ + dp[r] = sp[idx[r]]; \ + } \ + } while (0) + case 1: CD_GATE_GATHER(uint8_t); break; + case 2: CD_GATE_GATHER(uint16_t); break; + case 4: CD_GATE_GATHER(uint32_t); break; + default: CD_GATE_GATHER(uint64_t); break; +#undef CD_GATE_GATHER + } + } +} + +ray_t* query_cd_gate_where_rows(ray_t* tbl, ray_t* where_expr, int64_t n_table, + const int64_t** rows, int64_t* nrows, int64_t* population) { + *rows = NULL; *nrows = n_table; *population = 0; + if (n_table <= 0) return NULL; + int64_t ncols_max = ray_table_ncols(tbl); + if (ncols_max < 1) return NULL; + ray_t* syms_hdr = NULL; + int64_t* syms = (int64_t*)scratch_alloc(&syms_hdr, (size_t)ncols_max * sizeof(int64_t)); + if (!syms) return NULL; + int n_ref = collect_col_refs_set(where_expr, tbl, syms, (int)ncols_max, 0); + for (int i = 0; i < n_ref; i++) { + ray_t* c = ray_table_get_col(tbl, syms[i]); + if (!c || RAY_IS_ERR(c) || RAY_IS_PARTED(c->type) || c->type == RAY_MAPCOMMON || + c->len < n_table) { n_ref = 0; break; } + switch (c->type) { + case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: case RAY_F64: case RAY_F32: + case RAY_SYM: break; + default: n_ref = 0; break; + } + if (n_ref == 0) break; + } + if (n_ref <= 0) { scratch_free(syms_hdr); return NULL; } + + /* The chunks the zone gate lets through, and the rows they hold (P): + * the sample is drawn from those rows. */ + select_scan_t ss; + memset(&ss, 0, sizeof ss); + ss.scan.rows = n_table; + scan_gate_where(&ss, where_expr, tbl, 0); + int64_t P = n_table, n_pass = 0; + uint32_t* pass = NULL; + ray_t* pass_hdr = NULL; + const uint8_t lg = ss.scan.gate_log2; + if (ss.scan.gate) { + const int64_t nch = (n_table + ((int64_t)1 << lg) - 1) >> lg; + pass = (uint32_t*)scratch_alloc(&pass_hdr, (size_t)nch * sizeof(uint32_t)); + if (!pass) { scratch_free(ss.gate_hdr); scratch_free(syms_hdr); return NULL; } + for (int64_t ch = 0; ch < nch; ch++) + if ((ss.scan.gate[ch >> 6] >> (ch & 63)) & 1) pass[n_pass++] = (uint32_t)ch; + if (n_pass == nch) { + scratch_free(pass_hdr); pass = NULL; /* nothing ruled out */ + } else { + P = n_pass << lg; + if (n_pass > 0 && pass[n_pass - 1] == (uint32_t)(nch - 1)) + P -= (nch << lg) - n_table; /* the last chunk is short */ + } + } + if (ss.gate_hdr) scratch_free(ss.gate_hdr); + if (P <= 0) { + /* no chunk can hold a survivor: the predicate keeps nothing */ + if (pass_hdr) scratch_free(pass_hdr); + scratch_free(syms_hdr); + ray_t* out_hdr = NULL; + int64_t* out = (int64_t*)scratch_alloc(&out_hdr, sizeof(int64_t)); + if (!out) return NULL; + *rows = out; *nrows = 0; *population = 0; + return out_hdr; + } + const int64_t n_s = P < CD_GATE_WHERE_SAMPLE ? P : CD_GATE_WHERE_SAMPLE; + ray_t* idx_hdr = NULL; + int64_t* idx = (int64_t*)scratch_alloc(&idx_hdr, (size_t)n_s * sizeof(int64_t)); + if (!idx) { if (pass_hdr) scratch_free(pass_hdr); scratch_free(syms_hdr); return NULL; } + const int64_t cmask = ((int64_t)1 << lg) - 1; + for (int64_t i = 0; i < n_s; i++) { + const int64_t j = agg_est_sample_row(i, n_s, P); /* among the rows let through */ + idx[i] = pass ? (((int64_t)pass[j >> lg] << lg) | (j & cmask)) : j; + } + if (pass_hdr) scratch_free(pass_hdr); + + /* The gathered columns, made first; then the rows gathered into them + * over the pool's threads. */ + ray_t* gv_hdr = NULL; + uint8_t* gv_mem = (uint8_t*)scratch_alloc(&gv_hdr, (size_t)n_ref * (sizeof(ray_t*) + sizeof(void*) * 2 + 1)); + if (!gv_mem) { scratch_free(idx_hdr); scratch_free(syms_hdr); return NULL; } + ray_t** gv = (ray_t**)gv_mem; + const void** src = (const void**)(gv_mem + (size_t)n_ref * sizeof(ray_t*)); + void** dst = (void**)(gv_mem + (size_t)n_ref * (sizeof(ray_t*) + sizeof(void*))); + uint8_t* esz = gv_mem + (size_t)n_ref * (sizeof(ray_t*) + sizeof(void*) * 2); + int n_g = 0; + for (int i = 0; i < n_ref; i++) { + ray_t* c = ray_table_get_col(tbl, syms[i]); + /* the pages the sampled rows fall on, asked for ahead of the reads */ + ray_col_want_rows(c, idx, n_s); + /* a SYM column at its own code width: ray_vec_new would make a + * 64-bit one, and the copy below is by the source's width */ + ray_t* g = c->type == RAY_SYM ? ray_sym_vec_new(c->attrs & RAY_SYM_W_MASK, n_s) + : ray_vec_new(c->type, n_s); + if (!g || RAY_IS_ERR(g)) { if (g) ray_release(g); break; } + g->len = n_s; + g->attrs |= c->attrs & RAY_ATTR_HAS_NULLS; + if (c->type == RAY_SYM) ray_sym_vec_adopt_domain(g, c); + gv[n_g] = g; src[n_g] = ray_data(c); dst[n_g] = ray_data(g); esz[n_g] = col_esz(c); + n_g++; + } + ray_t* st = n_g == n_ref ? ray_table_new(0) : NULL; + if (st && RAY_IS_ERR(st)) { ray_error_free(st); st = NULL; } + if (st) { + cd_gate_gather_ctx_t ctx = { src, dst, esz, idx, n_g }; + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, n_s, AGG_EST_SAMPLE_ROWS)) + ray_pool_dispatch(pool, cd_gate_gather_fn, &ctx, n_s); + else + cd_gate_gather_fn(&ctx, 0, 0, n_s); + for (int i = 0; i < n_g && st; i++) { + /* add_col releases the table on an error and returns the error */ + st = ray_table_add_col(st, syms[i], gv[i]); + if (st && RAY_IS_ERR(st)) { ray_error_free(st); st = NULL; } + } + } + for (int i = 0; i < n_g; i++) ray_release(gv[i]); + scratch_free(gv_hdr); + scratch_free(syms_hdr); + if (!st) { scratch_free(idx_hdr); return NULL; } + + ray_t* out_hdr = NULL; + ray_graph_t* gs = ray_graph_new(st); + if (gs) { + ray_op_t* pred = compile_expr_dag(gs, where_expr); + ray_op_t* froot = pred ? ray_filter(gs, ray_const_table(gs, st), pred) : NULL; + if (froot) froot = ray_optimize(gs, froot); + /* the filter returns its input (the sampled table) retained, with + * the selection installed on the graph */ + ray_t* fres = froot ? exec_node(gs, froot) : NULL; + if (fres && !RAY_IS_ERR(fres) && gs->selection) { + const int64_t kept = ray_rowsel_meta(gs->selection)->total_pass; + ray_t* ind = kept > 0 ? ray_rowsel_to_indices(gs->selection) : NULL; + int64_t* out = (int64_t*)scratch_alloc(&out_hdr, (size_t)(kept > 0 ? kept : 1) * sizeof(int64_t)); + if (out && (ind || kept == 0)) { + const int64_t* ii = ind ? (const int64_t*)ray_data(ind) : NULL; + for (int64_t j = 0; j < kept; j++) out[j] = idx[ii[j]]; + *rows = out; *nrows = kept; + *population = (int64_t)((double)P * (double)kept / (double)n_s); + if (kept > 0 && *population < kept) *population = kept; + } else if (out_hdr) { scratch_free(out_hdr); out_hdr = NULL; } + if (ind) ray_release(ind); + } + if (fres) { if (RAY_IS_ERR(fres)) ray_error_free(fres); else ray_release(fres); } + ray_graph_free(gs); + } + ray_release(st); + scratch_free(idx_hdr); + return out_hdr; +} + +/* A column is registered unless it is cached (exec_scan_add_col samples the + * whole column). Under a zone gate only the chunks it lets through are + * read: drop the columns whose sampled gated-in pages are cached already, + * so a repeated query over cached rows does no read-ahead work at all. */ +static void scan_gate_drop_cached(ray_pool_scan_t* s) { + int64_t nch = (s->rows + ((int64_t)1 << s->gate_log2) - 1) >> s->gate_log2; + int64_t first = -1, last = -1, n_in = 0; + for (int64_t ch = 0; ch < nch; ch++) { + if (!((s->gate[ch >> 6] >> (ch & 63)) & 1)) continue; + if (first < 0) first = ch; + last = ch; + n_in++; + } + if (first < 0) return; + /* Four gated-in chunks: the first, the last and two between them. */ + int64_t in[4]; + int nin = 0; + for (int64_t ch = first, k = 0; ch <= last && nin < 4; ch++) { + if (!((s->gate[ch >> 6] >> (ch & 63)) & 1)) continue; + if (k == 0 || k == n_in - 1 || k == n_in / 3 || k == 2 * n_in / 3) in[nin++] = ch; + k++; + } + for (uint32_t k = 0; k < s->n; ) { + bool cached = true; + for (int i = 0; i < nin && cached; i++) { + int64_t r0 = in[i] << s->gate_log2; + int64_t r1 = r0 + ((int64_t)1 << s->gate_log2) < s->rows ? r0 + ((int64_t)1 << s->gate_log2) : s->rows; + cached = ray_vm_resident(s->base[k] + (size_t)r0 * s->esz[k], + (size_t)(r1 - r0) * s->esz[k]); + } + if (!cached) { k++; continue; } + s->base[k] = s->base[s->n - 1]; + s->esz[k] = s->esz[s->n - 1]; + s->warm[k] = s->warm[s->n - 1]; + s->n--; + } +} + +/* Fill the open registration of the select `args` from its source table. */ +static void select_scan_register(ray_t** args, ray_t* dict, ray_t* tbl, ray_t* where) { + select_scan_t* ss = t_select_scan; + if (!ss || ss->filled || ss->args != args) return; + ss->filled = true; + int64_t syms[64], wsyms[64]; + int n = 0, nw = 0; + int64_t from_id = dict_key_id(dict, "from"); + int64_t where_id = dict_key_id(dict, "where"); + DICT_VIEW_DECL(pv); + DICT_VIEW_OPEN(dict, pv); + if (DICT_VIEW_OVERFLOW(pv)) { DICT_VIEW_CLOSE(pv); return; } + for (int64_t i = 0; i + 1 < pv_n; i += 2) { + if (pv[i]->i64 == from_id) continue; + if (pv[i]->i64 == where_id) nw = collect_syms(pv[i + 1], wsyms, 64, nw); + else n = collect_syms(pv[i + 1], syms, 64, n); + } + DICT_VIEW_CLOSE(pv); + for (int i = 0; i < nw; i++) + exec_scan_add_col(&ss->scan, ray_table_get_col(tbl, wsyms[i])); + int64_t nrows = ray_table_nrows(tbl); + bool rows_set = ss->scan.rows >= 0; + if (!rows_set) ss->scan.rows = nrows; /* the gate is sized by it */ + if (where) scan_gate_where(ss, where, tbl, 0); + bool defer = where && !ss->scan.gate; + for (int i = 0; i < n; i++) + exec_scan_add_col(defer ? &ss->defer : &ss->scan, ray_table_get_col(tbl, syms[i])); + /* Once every column is in: the gate's cached ones are not requested. */ + if (ss->scan.gate) scan_gate_drop_cached(&ss->scan); + /* A column the filter also reads is requested with it. */ + for (uint32_t k = 0; k < ss->defer.n; ) { + bool dup = false; + for (uint32_t j = 0; j < ss->scan.n; j++) dup |= ss->scan.base[j] == ss->defer.base[k]; + if (!dup) { k++; continue; } + ss->defer.base[k] = ss->defer.base[ss->defer.n - 1]; + ss->defer.esz[k] = ss->defer.esz[ss->defer.n - 1]; + ss->defer.warm[k] = ss->defer.warm[ss->defer.n - 1]; + ss->defer.n--; + } + /* No mapped column at all: leave ray_execute its own registration. */ + if (!ss->scan.n && !ss->defer.n && !rows_set) ss->scan.rows = -1; + ray_pool_scan_set(&ss->scan); +} + +/* Rows of selection `sel` that select_scan_want_selected requests page by + * page at most; a larger selection is read whole. */ +#define SELECT_SCAN_SPARSE_MAX 65536 + +/* Add the pages of bytes [a, b) to the pending range [*lo, *hi), sending the + * pending range first when the new pages do not touch it. */ +static void select_scan_want_range(uintptr_t a, uintptr_t b, uintptr_t* lo, uintptr_t* hi) { + const uintptr_t pg = 4096; + uintptr_t plo = a & ~(pg - 1), phi = (b + pg - 1) & ~(pg - 1); + if (*hi && plo <= *hi) { + if (phi > *hi) *hi = phi; + return; + } + if (*hi) ray_vm_advise_willneed((void*)*lo, *hi - *lo); + *lo = plo; + *hi = phi; +} + +/* Request the pages of the column at `base` (elements of `esz` bytes) that + * the rows selected by `sel` fall on, adjacent pages as one range. */ +static void select_scan_want_selected(const uint8_t* base, size_t esz, int64_t rows, + ray_t* sel) { + if (!ray_pool_scan_on()) return; + ray_rowsel_t* m = ray_rowsel_meta(sel); + const uint8_t* fl = ray_rowsel_flags(sel); + const uint32_t* off = ray_rowsel_offsets(sel); + const uint16_t* idx = ray_rowsel_idx(sel); + uintptr_t lo = 0, hi = 0; + for (uint32_t s = 0; s < m->n_segs; s++) { + int64_t r0 = (int64_t)s * RAY_MORSEL_ELEMS; + if (fl[s] == RAY_SEL_ALL) { + int64_t r1 = r0 + RAY_MORSEL_ELEMS < rows ? r0 + RAY_MORSEL_ELEMS : rows; + select_scan_want_range((uintptr_t)(base + (size_t)r0 * esz), + (uintptr_t)(base + (size_t)r1 * esz), &lo, &hi); + } else if (fl[s] == RAY_SEL_MIX) { + for (uint32_t i = off[s]; i < off[s + 1]; i++) { + uintptr_t a = (uintptr_t)(base + (size_t)(r0 + idx[i]) * esz); + select_scan_want_range(a, a + esz, &lo, &hi); + } + } + } + if (hi) ray_vm_advise_willneed((void*)lo, hi - lo); +} + +/* The filter of the running select has produced `sel` (NULL when it kept + * every row, or returned a compacted table of `kept` rows). Request each + * column held back for it: whole when there is at least a quarter of a + * selected row per page of it, or too many rows to request one by one; + * else only the pages the selected rows fall on. */ +void ray_select_scan_filtered(ray_t* sel, int64_t kept) { + select_scan_t* ss = t_select_scan; + if (!ss || !ss->defer.n) return; + ray_pool_scan_t* d = &ss->defer; + int64_t rows = d->rows; + /* A compacted result was gathered already: nothing left to read. */ + if (!sel && kept < rows) { d->n = 0; return; } + int64_t pass = sel ? ray_rowsel_meta(sel)->total_pass : rows; + for (uint32_t k = 0; k < d->n; k++) { + double per_page = (double)pass / (double)rows * (4096.0 / d->esz[k]); + if (pass >= rows || per_page >= 0.25 || pass > SELECT_SCAN_SPARSE_MAX) { + if (ss->scan.n < RAY_POOL_SCAN_MAX) { + ss->scan.base[ss->scan.n] = d->base[k]; + ss->scan.esz[ss->scan.n] = d->esz[k]; + ss->scan.warm[ss->scan.n] = d->warm[k]; + ss->scan.n++; + } + } else if (pass > 0) { + select_scan_want_selected(d->base[k], d->esz[k], rows, sel); + } + } + d->n = 0; +} + +ray_t* ray_select(ray_t** args, int64_t n) { + ray_t* merged = n > 0 ? ray_select_merge_plan(args[0]) : NULL; + if (merged) args = &merged; + select_scan_t ss = { .args = args }; + exec_scan_init(&ss.scan); + exec_scan_init(&ss.defer); + select_scan_t* prev_ss = t_select_scan; + const ray_pool_scan_t* prev_scan = ray_pool_scan_get(); + t_select_scan = &ss; + ray_t* r = ray_select_impl(args, n, false); + t_select_scan = prev_ss; + ray_pool_scan_set(prev_scan); + if (ss.gate_hdr) scratch_free(ss.gate_hdr); + if (merged) ray_release(merged); + return r; +} + +/* The hidden name a bare computed by: key is grouped under (#707). */ +#define SELECT_COMPUTED_KEY "__by_key" + +/* The select dict with `from:` set to `tbl` (owned; `tbl` retained). */ +static ray_t* select_dict_with_from(ray_t* dict, ray_t* tbl) { + 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 ray_error("domain", "select: a clause dict"); + int64_t nd = ray_dict_len(dict); + int64_t id_from = ray_sym_intern("from", 4); + ray_t* ck = ray_vec_new(RAY_SYM, nd); + ray_t* cv = ray_list_new((int32_t)nd); + if (!ck || RAY_IS_ERR(ck) || !cv || RAY_IS_ERR(cv)) { + if (ck && !RAY_IS_ERR(ck)) ray_release(ck); + if (cv && !RAY_IS_ERR(cv)) ray_release(cv); + return ray_error("oom", NULL); + } + for (int64_t i = 0; i < nd && cv && !RAY_IS_ERR(cv); i++) { + int64_t kid = sym_cell_runtime_id(keys, i); + ((int64_t*)ray_data(ck))[ck->len++] = kid; + cv = ray_list_append(cv, kid == id_from ? tbl : ((ray_t**)ray_data(vals))[i]); + } + if (!cv || RAY_IS_ERR(cv)) { ray_release(ck); return cv ? cv : ray_error("oom", NULL); } + return ray_dict_new(ck, cv); +} + +static ray_t* sym_binding(int64_t s); + +/* Is `b` a builtin registered under one of `names`? A builtin carries the + * name it was registered under, whatever name a clause calls it by. */ +static bool builtin_named(const ray_t* b, const char* const* names, size_t n) { + if (!b || b->type <= RAY_LAMBDA || b->type > RAY_VARY) return false; + const char* own = ray_fn_name(b); + for (size_t i = 0; i < n; i++) if (strcmp(own, names[i]) == 0) return true; + return false; +} + +/* A builtin that runs code its clause does not show: a lambda literal, or + * text or a name evaluated at run time. */ +static bool builtin_runs_code(const ray_t* b) { + static const char* const code[] = { "fn", "eval", "parse", "resolve", "load", "value" }; + return builtin_named(b, code, sizeof code / sizeof code[0]); +} + +/* Does name `s` read a column of `tbl` (a dotted name: by its head)? As + * the evaluator resolves it: a lexical local of that name (a parameter, a + * let) comes first and hides the column; the column comes before a + * global. */ +static bool sym_names_col(ray_t* tbl, int64_t s) { + if (!tbl) return false; + int64_t head = s; + if (ray_sym_is_dotted(s)) { + const int64_t* segs; + if (ray_sym_segs(s, &segs) < 1) return false; + head = segs[0]; + } + if (ray_env_get_lexical_local(head)) return false; + return ray_table_get_col(tbl, head) != NULL; } -ray_t* ray_select(ray_t** args, int64_t n) { - return ray_select_impl(args, n, false); +static bool clause_runs_code_in(ray_t* v, ray_t* tbl, bool containers); + +/* Does key `e` name, anywhere, a builtin that binds a name or quotes its + * argument (let, set, quote), however it is called? */ +static bool key_names_binder(ray_t* e, ray_t* tbl) { + static const char* const binders[] = { "let", "set", "quote" }; + if (!e) return false; + if (builtin_named(e, binders, sizeof binders / sizeof binders[0])) return true; /* an object in the AST */ + if (e->type == -RAY_SYM) + return !sym_names_col(tbl, e->i64) && + builtin_named(sym_binding(e->i64), binders, sizeof binders / sizeof binders[0]); + if (e->type != RAY_LIST) return false; + ray_t** el = (ray_t**)ray_data(e); + for (int64_t i = 0; i < e->len; i++) if (key_names_binder(el[i], tbl)) return true; + return false; } -/* The hidden name a bare computed by: key is grouped under (#707). */ -#define SELECT_COMPUTED_KEY "__by_key" +/* The first free name in key `e` that is no column of `tbl` and no bound + * name, or -1. Only asked of a key that runs no code and binds no name + * (key_names_binder, clause_runs_code_in): a name such a form binds, in any + * nesting, is the evaluator's to resolve, and this check exists only to + * pick the error code, never to refuse a key the evaluator accepts. */ +static int64_t key_unknown_name(ray_t* e, ray_t* tbl) { + if (!e) return -1; + if (e->type == -RAY_SYM) { + if ((e->attrs & ATTR_QUOTED) || sym_names_col(tbl, e->i64)) return -1; + return sym_binding(e->i64) ? -1 : e->i64; + } + if (e->type != RAY_LIST || e->len < 1) return -1; + ray_t** el = (ray_t**)ray_data(e); + /* a named head is a function, whose own error stands */ + for (int64_t i = el[0]->type == -RAY_SYM ? 1 : 0; i < e->len; i++) { + int64_t m = key_unknown_name(el[i], tbl); + if (m >= 0) return m; + } + return -1; +} + +static bool parted_clauses_plain(ray_t* dict, ray_t* tbl); + +/* The columns of a parted table a select reads, flattened: every column a + * clause names, in the table's order; the whole table when a clause runs + * code whose column reads it does not show, or names no column. */ +static ray_t* parted_flatten_read_cols(ray_t* dict, ray_t* tbl) { + int64_t nc = ray_table_ncols(tbl); + ray_t* keys = ray_dict_keys(dict); + ray_t* vals = ray_dict_vals(dict); + if (nc <= 0 || nc > 256 || !keys || keys->type != RAY_SYM || !vals || vals->type != RAY_LIST || + !parted_clauses_plain(dict, tbl)) + return query_materialize_parted_table(tbl); + int64_t id_from = ray_sym_intern("from", 4); + int64_t refs[256]; + int nref = 0; + for (int64_t i = 0; i < ray_dict_len(dict); i++) { + if (sym_cell_runtime_id(keys, i) == id_from) continue; + ray_t* v = ((ray_t**)ray_data(vals))[i]; + int64_t nsym = v && v->type == -RAY_SYM ? 1 : (v && v->type == RAY_SYM ? v->len : 0); + for (int64_t j = 0; j < nsym; j++) { /* a sort key, quoted or not */ + int64_t s = v->type == -RAY_SYM ? v->i64 : sym_cell_runtime_id(v, j); + bool seen = false; + for (int r = 0; r < nref; r++) seen |= refs[r] == s; + if (!seen && nref < 256 && ray_table_get_col(tbl, s)) refs[nref++] = s; + } + if (nsym == 0) nref = collect_col_refs_set(v, tbl, refs, 256, nref); + } + if (nref == 0) return query_materialize_parted_table(tbl); + ray_t* out = ray_table_new(nref); + for (int64_t c = 0; c < nc && out && !RAY_IS_ERR(out); c++) { + int64_t cn = ray_table_col_name(tbl, c); + bool want = false; + for (int r = 0; r < nref; r++) want |= refs[r] == cn; + if (!want) continue; + ray_t* v = query_materialize_parted_col(ray_table_get_col_idx(tbl, c)); + if (!v || RAY_IS_ERR(v)) { ray_release(out); return v ? v : ray_error("oom", NULL); } + out = ray_table_add_col(out, cn, v); + ray_release(v); + } + return out ? out : ray_error("oom", NULL); +} /* 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 @@ -9027,6 +11535,9 @@ ray_t* ray_select(ray_t** args, int64_t n) { * 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. */ +/* Whether an expression, looking through the bodies of the helpers it + * names, holds a form that takes one condition or one value: such a key + * is evaluated row by row, as a derived output is. */ 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; @@ -9039,7 +11550,106 @@ static ray_t* select_plan_computed_key(ray_t* dict, ray_t* tbl, int64_t* key_nam 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; + /* A key the planner cannot lower (an opaque helper, a concat of + * collections, which the planner keeps for text, a builtin it has no + * kernel for: reverse, asc, til) is evaluated once over the whole + * table, where its column arguments keep their rows, and grouped as a + * hidden column named after the expression. */ + ray_t* keyed = NULL; /* the (filtered) source plus the evaluated key column */ + bool where_applied = false; + if (!ray_table_get_col(tbl, hidden)) { + ray_graph_t* g = ray_graph_new(tbl); + bool lowered = g && compile_expr_dag(g, by_expr) != NULL; + if (g) ray_graph_free(g); + if (!lowered) { + /* An unknown column reads as schema, as in a key that lowers. */ + int64_t miss = key_names_binder(by_expr, tbl) || clause_runs_code_in(by_expr, tbl, true) + ? -1 : key_unknown_name(by_expr, tbl); + if (miss >= 0) { + ray_t* mn = ray_sym_str(miss); + return mn ? ray_error("schema", "column '%.*s' not found", (int)ray_str_len(mn), ray_str_ptr(mn)) + : ray_error("schema", "column not found"); + } + /* The key sees only the rows `where:` keeps, as a planned key + * does, so a helper never runs on rows the filter removes. */ + ray_t* where_expr = dict_get(dict, "where"); + ray_t* base = tbl; + ray_retain(base); + if (where_expr) { + ray_t* fk = ray_vec_new(RAY_SYM, 2); + ray_t* fv = ray_list_new(2); + if (fk && !RAY_IS_ERR(fk)) { ((int64_t*)ray_data(fk))[0] = rid[0]; ((int64_t*)ray_data(fk))[1] = rid[1]; fk->len = 2; } + if (fv && !RAY_IS_ERR(fv)) fv = ray_list_append(fv, tbl); + if (fv && !RAY_IS_ERR(fv)) fv = ray_list_append(fv, where_expr); + ray_t* fdict = ray_dict_new(fk, fv); + if (!fdict || RAY_IS_ERR(fdict)) { ray_release(base); return fdict ? fdict : ray_error("oom", NULL); } + ray_t* filtered = ray_select_impl(&fdict, 1, true); + ray_release(fdict); + if (filtered && !RAY_IS_ERR(filtered) && ray_is_lazy(filtered)) filtered = ray_lazy_materialize(filtered); + if (!filtered || RAY_IS_ERR(filtered)) { ray_release(base); return filtered ? filtered : ray_error("oom", NULL); } + ray_release(base); + base = filtered; + where_applied = true; + } + /* Over a parted table the key reads whole columns, not the + * partitions: with no output, the first-rows path groups a + * flattened narrow copy (select_parted_first_rows); otherwise + * the columns the select reads are flattened here. A where: + * has flattened the rows it keeps already. */ + if (!where_applied && table_has_parted_columns(base)) { + bool any_out = false; + for (int64_t i = 0; i < nd && !any_out; i++) { + int64_t kid = sym_cell_runtime_id(keys, i); + bool rsv = false; + for (int r = 0; r < 7; r++) rsv |= kid == rid[r]; + any_out = !rsv; + } + if (!any_out) { ray_release(base); return NULL; } + ray_t* flat = parted_flatten_read_cols(dict, base); + ray_release(base); + if (!flat || RAY_IS_ERR(flat)) return flat ? flat : ray_error("oom", NULL); + base = flat; + } + /* The key sees the whole column. If a conditional inside it + * tested a vector derived from the rows, the body meant one + * row at a time: evaluate it again row by row, as a derived + * output with a condition is. */ + int64_t nrows = ray_table_nrows(base); + int32_t conds = __VM->rows_cond; + /* A body with an effect runs once per row, never whole first: + * a repeated run would repeat the effect. */ + key_bind_t pure_binds[KEY_PURE_MAX_BIND]; + key_pure_ctx_t pure_ctx = { NULL, pure_binds, 0, 0 }; + bool pure = key_expr_pure(by_expr, 0, &pure_ctx); + ray_t* keyvec = pure ? eval_expr_whole_column(by_expr, base) : NULL; + if (!pure) keyvec = eval_expr_per_row(by_expr, base, nrows); + else if (__VM->rows_cond != conds || !keyvec || RAY_IS_ERR(keyvec)) { + /* Also when the whole-column run failed: a body written for + * one row may not accept a column at all. The failure is + * swallowed whole: its `raise` payload and trace go with it, + * or the next `try` anywhere would receive them. */ + if (keyvec && RAY_IS_ERR(keyvec)) { + ray_error_free(keyvec); + if (__VM->raise_val) { ray_release(__VM->raise_val); __VM->raise_val = NULL; } + if (__VM->return_val) { ray_release(__VM->return_val); __VM->return_val = NULL; } + ray_clear_error_trace(); + __VM->err.msg[0] = '\0'; + } + else if (keyvec) ray_release(keyvec); + keyvec = eval_expr_per_row(by_expr, base, nrows); + } + if (keyvec && !RAY_IS_ERR(keyvec) && ray_is_lazy(keyvec)) keyvec = ray_lazy_materialize(keyvec); + if (!keyvec || RAY_IS_ERR(keyvec)) { ray_release(base); return keyvec ? keyvec : ray_error("oom", NULL); } + if (!(ray_is_vec(keyvec) || keyvec->type == RAY_LIST) || ray_len(keyvec) != nrows) { + ray_release(keyvec); ray_release(base); + return ray_error("length", "select by: key expression must yield one value per row"); + } + keyed = ray_table_add_col(base, hidden, keyvec); /* consumes base */ + ray_release(keyvec); + if (!keyed || RAY_IS_ERR(keyed)) return keyed ? keyed : ray_error("oom", NULL); + } + } + bool needs_eval = keyed != NULL; for (int64_t i = 0; i < nd; i++) { int64_t kid = sym_cell_runtime_id(keys, i); bool clause = false; @@ -9049,29 +11659,41 @@ static ray_t* select_plan_computed_key(ray_t* dict, ray_t* tbl, int64_t* key_nam 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_group_dag_agg_expr(v, tbl)) 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); + /* The hidden key is the expression itself, grouped by the engine, or + * the evaluated column, grouped as a plain column of that name. */ + ray_t* by_val; + if (keyed) { + by_val = ray_sym(hidden); + } else { + 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); + by_val = ray_dict_new(bk, bv); + } + if (!by_val || RAY_IS_ERR(by_val)) { if (keyed) ray_release(keyed); return by_val ? by_val : 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; + engine = k_by && !RAY_IS_ERR(k_by) ? ray_dict_upsert(engine, k_by, by_val) : engine; if (k_by) ray_release(k_by); - ray_release(by_dict); + ray_release(by_val); 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); + engine = ray_dict_upsert(engine, k_from, keyed ? keyed : tbl); if (k_from) ray_release(k_from); + if (keyed) ray_release(keyed); + if (where_applied && engine && !RAY_IS_ERR(engine)) { + ray_t* k_where = ray_sym(rid[1]); + if (k_where && !RAY_IS_ERR(k_where)) { engine = ray_dict_remove(engine, k_where); ray_release(k_where); } + } /* 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]); @@ -9113,12 +11735,561 @@ static ray_t* select_name_computed_key(ray_t* r, int64_t key_name) { 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); + int64_t key_at = -1; 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; + if (ray_table_col_name(r, c) == hidden) { ray_table_set_col_name(r, c, key_name); key_at = c; break; } + if (key_at < 0) return r; + /* With no outputs the engine returns every input column; the source + * column the key is named after yields to the key, as it does when the + * engine computed the key itself. */ + bool dup = false; + for (int64_t c = 0; c < nc; c++) if (c != key_at && ray_table_col_name(r, c) == key_name) dup = true; + if (!dup) return r; + ray_t* out = ray_table_new(nc); + for (int64_t c = 0; c < nc && out && !RAY_IS_ERR(out); c++) { + if (c != key_at && ray_table_col_name(r, c) == key_name) continue; + out = ray_table_add_col(out, ray_table_col_name(r, c), ray_table_get_col_idx(r, c)); + } + if (!out || RAY_IS_ERR(out)) { ray_release(r); return out ? out : ray_error("oom", NULL); } + ray_release(r); + return out; +} + +/* Does the clause value `v` name `s` anywhere: a name, a name list, a + * dict's keys or values, nested in a call? */ +static bool clause_names_sym(ray_t* v, int64_t s) { + if (!v || RAY_IS_ERR(v)) return false; + if (v->type == -RAY_SYM) return v->i64 == s; + if (v->type == RAY_SYM) { + for (int64_t i = 0; i < v->len; i++) if (sym_cell_runtime_id(v, i) == s) return true; + return false; + } + if (v->type == RAY_DICT) + return clause_names_sym(ray_dict_keys(v), s) || clause_names_sym(ray_dict_vals(v), s); + if (v->type != RAY_LIST) return false; + ray_t** el = (ray_t**)ray_data(v); + for (int64_t i = 0; i < v->len; i++) if (clause_names_sym(el[i], s)) return true; + return false; +} + +/* May the narrow copy of a parted table add a row-number column named + * `row_sym`? Not when the table has a column of that name or the select + * names it anywhere (as a key, an alias, or a value the column would + * shadow). A variable of that name is shadowed only through a name the + * select writes, or code it runs (parted_clauses_plain declines that). */ +static bool parted_row_name_free(ray_t* dict, ray_t* tbl, int64_t row_sym) { + if (ray_table_get_col(tbl, row_sym)) return false; + return !clause_names_sym(dict, row_sym); +} + +/* What a name is bound to, local before global; NULL when unbound. */ +static ray_t* sym_binding(int64_t s) { + ray_t* b = ray_env_get_lexical_local(s); + return b ? b : ray_env_get(s); +} + +/* Is a name bound to `b` code a clause runs: a lambda or a code-running + * builtin (builtin_runs_code), however named; a name of one (a call through + * it calls it); or (unquoted, when `containers`) a container that may hold + * lambdas? */ +static bool sym_binding_runs_code(ray_t* b, bool quoted, bool containers) { + if (!b) return false; + if (b->type == RAY_LAMBDA || builtin_runs_code(b)) return true; + if (b->type == -RAY_SYM) { + ray_t* to = sym_binding(b->i64); + return to && (to->type == RAY_LAMBDA || builtin_runs_code(to)); + } + return containers && !quoted && (b->type == RAY_LIST || b->type == RAY_DICT || b->type == RAY_TABLE); +} + +/* Does the clause value `v` run code whose column reads it does not show: + * a name -- plain, quoted or a dotted path -- bound to a lambda, to a + * lambda literal's form, or to a builtin that evaluates text or a name at + * run time, whatever it is called (and through one name hop); a call whose + * callee is computed; and, when `containers`, a name bound to a container + * that may hold lambdas? A name of a column of `tbl` is the column. */ +static bool clause_runs_code_in(ray_t* v, ray_t* tbl, bool containers) { + if (!v || RAY_IS_ERR(v)) return false; + if (v->type == RAY_LAMBDA || builtin_runs_code(v)) return true; /* an object in the AST */ + if (v->type == -RAY_SYM) { /* a dotted path too: ray_env_get walks it */ + if (!(v->attrs & ATTR_QUOTED) && sym_names_col(tbl, v->i64)) return false; + return sym_binding_runs_code(sym_binding(v->i64), (v->attrs & ATTR_QUOTED) != 0, containers); + } + if (v->type == RAY_DICT) { /* each value on its own: the values list is no call */ + ray_t* dv = ray_dict_vals(v); + if (!dv || dv->type != RAY_LIST) return clause_runs_code_in(dv, tbl, containers); + for (int64_t i = 0; i < dv->len; i++) + if (clause_runs_code_in(((ray_t**)ray_data(dv))[i], tbl, containers)) return true; + return false; + } + if (v->type != RAY_LIST) return false; + ray_t** el = (ray_t**)ray_data(v); + if (v->len > 0 && el[0]->type == RAY_LIST) return true; + for (int64_t i = 0; i < v->len; i++) if (clause_runs_code_in(el[i], tbl, containers)) return true; + return false; +} + +/* Does any clause but from: run code whose column reads it does not show + * (clause_runs_code_in)? NULL dict counts as code. */ +static bool clauses_run_code(ray_t* dict, ray_t* tbl, bool containers) { + 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 true; + int64_t id_from = ray_sym_intern("from", 4); + for (int64_t i = 0; i < ray_dict_len(dict); i++) + if (sym_cell_runtime_id(keys, i) != id_from && + clause_runs_code_in(((ray_t**)ray_data(vals))[i], tbl, containers)) return true; + return false; +} + +/* Can the narrow copy of a parted table answer this select: every column + * a clause reads is written in it (no code that reads columns unseen, a + * container of lambdas included). */ +static bool parted_clauses_plain(ray_t* dict, ray_t* tbl) { + return !clauses_run_code(dict, tbl, true); +} + +/* Do the clauses name every column they read, as far as narrowing a flat + * table before a filter needs: no lambda, call through a computed callee, + * or text evaluated at run time. Names bound to containers are taken as + * data: a config dict or a list a where: reads must not cost the + * projection. */ +static bool clauses_name_their_columns(ray_t* dict, ray_t* tbl) { + return !clauses_run_code(dict, tbl, false); +} + +/* Rows rv[0..n) of a parted table, gathered one column at a time without + * flattening the table: the rows are marked, a column is compacted to the + * marked rows (in ascending order) by sel_compact, and when rv is not + * ascending each row is put in its place by its rank among the marked + * ones. Every row marked: the column flattened, ranked by row number. */ +typedef struct { + ray_t* tbl; + ray_t* sel; /* the marked rows; NULL when every row is marked */ + ray_t* perm_hdr; + int64_t* perm; /* rank of each row; NULL when rv ascends */ + int64_t n; +} parted_rows_t; + +/* NULL, or the error; parted_rows_close either way. */ +static ray_t* parted_rows_open(parted_rows_t* pr, ray_t* tbl, const int64_t* rv, int64_t n) { + memset(pr, 0, sizeof(*pr)); + pr->tbl = tbl; + pr->n = n; + int64_t nrows = ray_table_nrows(tbl); + bool ascending = true; + for (int64_t i = 1; i < n && ascending; i++) if (rv[i] <= rv[i - 1]) ascending = false; + ray_t* mask = ray_vec_new(RAY_BOOL, nrows); + if (!mask || RAY_IS_ERR(mask)) return mask ? mask : ray_error("oom", NULL); + mask->len = nrows; + uint8_t* mk = (uint8_t*)ray_data(mask); + if (nrows > 0) memset(mk, 0, (size_t)nrows); + for (int64_t i = 0; i < n; i++) { + if (rv[i] < 0 || rv[i] >= nrows) { + ray_release(mask); + return ray_error("domain", "select: lost the rows of a parted table"); + } + mk[rv[i]] = 1; + } + int64_t nsel = 0; + for (int64_t r = 0; r < nrows; r++) nsel += mk[r]; + ray_t* err = NULL; + if (nsel != nrows) { + pr->sel = ray_rowsel_from_pred(mask); + if (!pr->sel) err = ray_error("oom", NULL); + } + if (!err && !ascending) { + pr->perm = (int64_t*)scratch_alloc(&pr->perm_hdr, (size_t)n * sizeof(int64_t)); + ray_t* asc_hdr = NULL; + int64_t* asc_rows = pr->sel ? (int64_t*)scratch_alloc(&asc_hdr, (size_t)(nsel > 0 ? nsel : 1) * sizeof(int64_t)) : NULL; + if (!pr->perm || (pr->sel && !asc_rows)) err = ray_error("oom", NULL); + else if (!pr->sel) { + for (int64_t i = 0; i < n; i++) pr->perm[i] = rv[i]; /* every row: rank = row */ + } else { + int64_t j = 0; + for (int64_t r = 0; r < nrows; r++) if (mk[r]) asc_rows[j++] = r; + for (int64_t i = 0; i < n; i++) { + int64_t lo = 0, hi = nsel - 1; + while (lo < hi) { + int64_t mid = lo + (hi - lo) / 2; + if (asc_rows[mid] < rv[i]) lo = mid + 1; else hi = mid; + } + pr->perm[i] = lo; + } + } + scratch_free(asc_hdr); + } + ray_release(mask); + return err; +} + +/* Column `c` of the table at the rows, owned. */ +static ray_t* parted_rows_gather(parted_rows_t* pr, int64_t c) { + ray_t* v; + if (!pr->sel) { + v = query_materialize_parted_col(ray_table_get_col_idx(pr->tbl, c)); + } else { + int64_t cn = ray_table_col_name(pr->tbl, c); + ray_t* one = sel_compact(NULL, pr->tbl, pr->sel, &cn, 1); + v = (one && !RAY_IS_ERR(one)) ? ray_table_get_col(one, cn) : one; + if (v && !RAY_IS_ERR(v)) ray_retain(v); + if (one && !RAY_IS_ERR(one)) ray_release(one); + } + if (v && !RAY_IS_ERR(v) && pr->perm) { + ray_t* placed = ray_group_gather(v, pr->perm, pr->n); + ray_release(v); + v = placed; + } + return v ? v : ray_error("domain", "select: lost a column of a parted table"); +} + +static void parted_rows_close(parted_rows_t* pr) { + if (pr->sel) ray_rowsel_release(pr->sel); + scratch_free(pr->perm_hdr); + pr->sel = NULL; + pr->perm_hdr = NULL; + pr->perm = NULL; +} + +/* A grouped select with no outputs returns the first row of each group, + * every column of it; its paths read plain columns. Over a parted table + * this groups a narrow copy instead of the flattened table: the columns + * the clauses name (and any whose name a key column may take), flattened, + * and one row-number column. The select run on it brings back the row + * each group kept; every other column is then gathered from the + * partitions at just those rows, one column at a time, and the result is + * laid out as the select lays out the flattened table. NULL when the + * shape is not handled here (the caller flattens the table). */ +static ray_t* select_parted_first_rows(ray_t* dict, ray_t* tbl, bool aliases_resolved) { + int64_t nc = ray_table_ncols(tbl); + int64_t nrows = ray_table_nrows(tbl); + if (nc <= 0 || nc > 256) return NULL; /* sel_compact's column limit */ + ray_t* by_expr = dict_get(dict, "by"); + if (!by_expr) return NULL; + int64_t row_sym = ray_sym_intern("__row", 5); + if (!parted_row_name_free(dict, tbl, row_sym) || !parted_clauses_plain(dict, tbl)) return NULL; + /* the key columns the result leads with */ + int64_t nkeys = by_expr->type == RAY_DICT ? ray_dict_len(by_expr) + : by_expr->type == RAY_SYM ? ray_len(by_expr) : 1; + + /* Names a key column may take: a computed key's derived name (`key` + * when it names no column), a dotted key's tail and full name, a + * by-dict's keys. A column of that name stays real: the key may + * replace it. */ + int64_t nkn_max = 3 + (by_expr->type == RAY_DICT ? ray_dict_len(by_expr) : 0); + ray_t* buf_hdr = NULL; + int64_t* refs = (int64_t*)scratch_alloc(&buf_hdr, + (size_t)(nc + nkn_max) * sizeof(int64_t) + (size_t)nc * sizeof(uint8_t)); + if (!refs) return ray_error("oom", NULL); + int64_t* keynames = refs + nc; + uint8_t* real = (uint8_t*)(keynames + nkn_max); + int nref = 0, nkn = 0; + static const char* const clause[] = { "by", "asc", "desc" }; + for (int i = 0; i < 3; i++) { + ray_t* v = dict_get(dict, clause[i]); + if (!v) continue; + /* A quoted symbol standing for the whole clause names a column + * there too (`by: 's`, `desc: 'h`); collect_col_refs_set takes + * only name references. */ + if (v->type == -RAY_SYM && (v->attrs & ATTR_QUOTED)) { + bool seen = !ray_table_get_col(tbl, v->i64); + for (int j = 0; j < nref && !seen; j++) if (refs[j] == v->i64) seen = true; + if (!seen && nref < nc) refs[nref++] = v->i64; + } else { + nref = collect_col_refs_set(v, tbl, refs, (int)nc, nref); + } + } + keynames[nkn++] = derived_key_name(by_expr); + if (by_expr->type == -RAY_SYM && ray_sym_is_dotted(by_expr->i64)) { + const int64_t* segs; + int ns = ray_sym_segs(by_expr->i64, &segs); + keynames[nkn++] = by_expr->i64; + if (ns > 0) keynames[nkn++] = segs[ns - 1]; + } + if (by_expr->type == RAY_DICT) { + ray_t* dk = ray_dict_keys(by_expr); + int64_t nd = ray_dict_len(by_expr); + if (dk && dk->type == RAY_SYM) + for (int64_t i = 0; i < nd && nkn < nkn_max; i++) + keynames[nkn++] = sym_cell_runtime_id(dk, i); + } + for (int64_t c = 0; c < nc; c++) { + int64_t cn = ray_table_col_name(tbl, c); + real[c] = 0; + for (int i = 0; i < nref && !real[c]; i++) if (refs[i] == cn) real[c] = 1; + for (int i = 0; i < nkn && !real[c]; i++) if (keynames[i] == cn) real[c] = 1; + } + + /* The narrow table: the real columns in the source's order, then the + * row number. */ + ray_t* narrow = ray_table_new(nc + 1); + for (int64_t c = 0; c < nc && narrow && !RAY_IS_ERR(narrow); c++) { + if (!real[c]) continue; + ray_t* v = query_materialize_parted_col(ray_table_get_col_idx(tbl, c)); + if (!v || RAY_IS_ERR(v)) { ray_release(narrow); narrow = v ? v : ray_error("oom", NULL); break; } + narrow = ray_table_add_col(narrow, ray_table_col_name(tbl, c), v); + ray_release(v); + } + if (narrow && !RAY_IS_ERR(narrow)) { + ray_t* rownum = ray_vec_new(RAY_I64, nrows); + if (!rownum || RAY_IS_ERR(rownum)) { + ray_release(narrow); + narrow = rownum ? rownum : ray_error("oom", NULL); + } else { + rownum->len = nrows; + for (int64_t r = 0; r < nrows; r++) ((int64_t*)ray_data(rownum))[r] = r; + narrow = ray_table_add_col(narrow, row_sym, rownum); + ray_release(rownum); + } + } + if (!narrow || RAY_IS_ERR(narrow)) { scratch_free(buf_hdr); return narrow ? narrow : ray_error("oom", NULL); } + + /* The select over it. */ + ray_t* engine = dict; + ray_retain(engine); + ray_t* k_from = ray_sym(ray_sym_intern("from", 4)); + if (k_from && !RAY_IS_ERR(k_from)) engine = ray_dict_upsert(engine, k_from, narrow); + if (k_from) ray_release(k_from); + ray_release(narrow); + if (!engine || RAY_IS_ERR(engine)) { scratch_free(buf_hdr); return engine ? engine : ray_error("oom", NULL); } + ray_t* res = ray_select_impl(&engine, 1, aliases_resolved); + ray_release(engine); + if (res && !RAY_IS_ERR(res) && ray_is_lazy(res)) res = ray_lazy_materialize(res); + if (!res || RAY_IS_ERR(res) || res->type != RAY_TABLE) { scratch_free(buf_hdr); return res ? res : ray_error("oom", NULL); } + + /* res holds the key columns, the narrow columns no key replaces (in + * order), the row number last. Any other layout: the caller flattens. */ + int64_t rc = ray_table_ncols(res); + bool fits = rc >= nkeys + 1 && ray_table_col_name(res, rc - 1) == row_sym; + int64_t pos = nkeys; + for (int64_t c = 0; c < nc && fits; c++) { + if (!real[c]) continue; + int64_t cn = ray_table_col_name(tbl, c); + bool is_key = false; + for (int64_t k = 0; k < nkeys; k++) if (ray_table_col_name(res, k) == cn) is_key = true; + if (is_key) continue; + if (pos >= rc - 1 || ray_table_col_name(res, pos) != cn) fits = false; + pos++; + } + ray_t* rows = fits && pos == rc - 1 ? ray_table_get_col_idx(res, rc - 1) : NULL; + if (!rows || rows->type != RAY_I64) { ray_release(res); scratch_free(buf_hdr); return NULL; } + int64_t n = rows->len; + const int64_t* rv = (const int64_t*)ray_data(rows); + parted_rows_t pr; + ray_t* err = parted_rows_open(&pr, tbl, rv, n); + + /* The result: the key columns, then the source's columns no key + * replaces, in its order -- a real one from res, any other gathered. */ + ray_t* out = err ? err : ray_table_new(rc + nc); + for (int64_t k = 0; k < nkeys && out && !RAY_IS_ERR(out); k++) { + ray_t* v = ray_table_get_col_idx(res, k); + ray_retain(v); + out = ray_table_add_col(out, ray_table_col_name(res, k), v); + ray_release(v); + } + for (int64_t c = 0; c < nc && out && !RAY_IS_ERR(out); c++) { + int64_t cn = ray_table_col_name(tbl, c); + bool is_key = false; + for (int64_t k = 0; k < nkeys; k++) if (ray_table_col_name(res, k) == cn) is_key = true; + if (is_key) continue; + ray_t* v; + if (real[c]) { /* res rows are in place already */ + v = ray_table_get_col(res, cn); + if (v) ray_retain(v); + else v = ray_error("domain", "select by: lost a column of a parted table"); + } else { + v = parted_rows_gather(&pr, c); + } + if (RAY_IS_ERR(v)) { ray_release(out); out = v; break; } + out = ray_table_add_col(out, cn, v); + ray_release(v); + } + parted_rows_close(&pr); + ray_release(res); + scratch_free(buf_hdr); + return out ? out : ray_error("oom", NULL); +} + +/* A sorted select without by: over a parted table that neither streaming + * path takes: the sort keys, flattened, and one row-number column are + * sorted (and taken) as asked; the rows that leaves are gathered from the + * partitions -- every column when the select has no outputs, else the + * columns its outputs name. Outputs must be bare columns, and each sort + * key a column of the table. NULL when the shape is not handled here + * (the caller flattens the table). */ +static ray_t* select_parted_sorted(ray_t* dict, ray_t* tbl, bool aliases_resolved) { + int64_t nc = ray_table_ncols(tbl); + if (nc <= 0 || nc > 256) return NULL; /* sel_compact's column limit */ + int64_t row_sym = ray_sym_intern("__row", 5); + if (!parted_row_name_free(dict, tbl, row_sym) || !parted_clauses_plain(dict, tbl)) return NULL; + ray_t* keys = ray_dict_keys(dict); + ray_t* vals = ray_dict_vals(dict); + int64_t nd = ray_dict_len(dict); + if (!keys || keys->type != RAY_SYM || !vals || vals->type != RAY_LIST) return NULL; + int64_t id_from = ray_sym_intern("from", 4), id_where = ray_sym_intern("where", 5), + id_by = ray_sym_intern("by", 2), id_take = ray_sym_intern("take", 4), + id_asc = ray_sym_intern("asc", 3), id_desc = ray_sym_intern("desc", 4), + id_nearest = ray_sym_intern("nearest", 7); + + ray_t* buf_hdr = NULL; + uint8_t* real = (uint8_t*)scratch_alloc(&buf_hdr, (size_t)nc); + if (!real) return ray_error("oom", NULL); + memset(real, 0, (size_t)nc); + int64_t n_out = 0, n_clause = 0; + bool ok = true; + for (int64_t i = 0; i < nd && ok; i++) { + int64_t kid = sym_cell_runtime_id(keys, i); + ray_t* v = ((ray_t**)ray_data(vals))[i]; + if (kid == id_where || kid == id_by || kid == id_nearest) ok = false; + else if (kid == id_from) continue; + else if (kid == id_take || kid == id_asc || kid == id_desc) n_clause++; + else if (!v || v->type != -RAY_SYM || (v->attrs & ATTR_QUOTED) || + !ray_table_get_col(tbl, v->i64) || !sym_names_col(tbl, v->i64)) + ok = false; /* a stored column the name reads (no local hides it) */ + else n_out++; + } + /* An output naming another output's alias reads that output, not the + * column (`{x: y z: x}`): left to the flat path. */ + for (int64_t i = 0; i < nd && ok; i++) { + int64_t kid = sym_cell_runtime_id(keys, i); + if (kid == id_from || kid == id_take || kid == id_asc || kid == id_desc) continue; + int64_t src = ((ray_t**)ray_data(vals))[i]->i64; + for (int64_t j = 0; j < nd && ok; j++) + if (j != i && sym_cell_runtime_id(keys, j) == src && src != id_from && + src != id_take && src != id_asc && src != id_desc && + ((ray_t**)ray_data(vals))[j]->i64 != src) ok = false; + } + /* Sort keys: columns of the table, read as columns whatever the outputs + * are named, as the flat sort reads them. */ + for (int64_t i = 0; i < nd && ok; i++) { + int64_t kid = sym_cell_runtime_id(keys, i); + if (kid != id_asc && kid != id_desc) continue; + ray_t* v = ((ray_t**)ray_data(vals))[i]; + int64_t nk = v && v->type == -RAY_SYM ? 1 : (v && v->type == RAY_SYM ? ray_len(v) : -1); + if (nk < 1) { ok = false; break; } + for (int64_t j = 0; j < nk && ok; j++) { + int64_t sk = v->type == -RAY_SYM ? v->i64 : sym_cell_runtime_id(v, j); + int64_t c = -1; + for (int64_t s = 0; s < nc && c < 0; s++) if (ray_table_col_name(tbl, s) == sk) c = s; + if (c < 0) { ok = false; break; } + real[c] = 1; + } + } + if (!ok) { scratch_free(buf_hdr); return NULL; } + + /* The narrow table: the sort keys, then the row number. */ + int64_t nrows = ray_table_nrows(tbl); + ray_t* narrow = ray_table_new(nc + 1); + for (int64_t c = 0; c < nc && narrow && !RAY_IS_ERR(narrow); c++) { + if (!real[c]) continue; + ray_t* v = query_materialize_parted_col(ray_table_get_col_idx(tbl, c)); + if (!v || RAY_IS_ERR(v)) { ray_release(narrow); narrow = v ? v : ray_error("oom", NULL); break; } + narrow = ray_table_add_col(narrow, ray_table_col_name(tbl, c), v); + ray_release(v); + } + if (narrow && !RAY_IS_ERR(narrow)) { + ray_t* rownum = ray_vec_new(RAY_I64, nrows); + if (!rownum || RAY_IS_ERR(rownum)) { + ray_release(narrow); + narrow = rownum ? rownum : ray_error("oom", NULL); + } else { + rownum->len = nrows; + for (int64_t r = 0; r < nrows; r++) ((int64_t*)ray_data(rownum))[r] = r; + narrow = ray_table_add_col(narrow, row_sym, rownum); + ray_release(rownum); + } + } + if (!narrow || RAY_IS_ERR(narrow)) { scratch_free(buf_hdr); return narrow ? narrow : ray_error("oom", NULL); } + + /* The sort over it: from:, then asc:/desc:/take: in the query's order. */ + ray_t* ck = ray_vec_new(RAY_SYM, n_clause + 1); + ray_t* cv = ray_list_new((int32_t)(n_clause + 1)); + if (ck && !RAY_IS_ERR(ck) && cv && !RAY_IS_ERR(cv)) { + ((int64_t*)ray_data(ck))[0] = id_from; + ck->len = 1; + cv = ray_list_append(cv, narrow); + for (int64_t i = 0; i < nd && cv && !RAY_IS_ERR(cv); i++) { + int64_t kid = sym_cell_runtime_id(keys, i); + if (kid != id_take && kid != id_asc && kid != id_desc) continue; + ((int64_t*)ray_data(ck))[ck->len++] = kid; + cv = ray_list_append(cv, ((ray_t**)ray_data(vals))[i]); + } + } + ray_release(narrow); + ray_t* engine = (ck && !RAY_IS_ERR(ck) && cv && !RAY_IS_ERR(cv)) ? ray_dict_new(ck, cv) : NULL; + if (!engine || RAY_IS_ERR(engine)) { + if (!engine) { + if (ck && !RAY_IS_ERR(ck)) ray_release(ck); + if (cv && !RAY_IS_ERR(cv)) ray_release(cv); + } + scratch_free(buf_hdr); + return engine ? engine : ray_error("oom", NULL); + } + ray_t* res = ray_select_impl(&engine, 1, aliases_resolved); + ray_release(engine); + if (res && !RAY_IS_ERR(res) && ray_is_lazy(res)) res = ray_lazy_materialize(res); + if (!res || RAY_IS_ERR(res) || res->type != RAY_TABLE) { scratch_free(buf_hdr); return res ? res : ray_error("oom", NULL); } + int64_t rc = ray_table_ncols(res); + ray_t* rows = rc > 0 && ray_table_col_name(res, rc - 1) == row_sym ? ray_table_get_col_idx(res, rc - 1) : NULL; + if (!rows || rows->type != RAY_I64) { ray_release(res); scratch_free(buf_hdr); return NULL; } + + parted_rows_t pr; + ray_t* err = parted_rows_open(&pr, tbl, (const int64_t*)ray_data(rows), rows->len); + ray_t* out = err ? err : ray_table_new(n_out > 0 ? n_out : nc); + /* every column of the table, or each output under its name */ + for (int64_t i = 0; i < (n_out > 0 ? nd : nc) && out && !RAY_IS_ERR(out); i++) { + int64_t name, src; + if (n_out > 0) { + int64_t kid = sym_cell_runtime_id(keys, i); + if (kid == id_from || kid == id_take || kid == id_asc || kid == id_desc) continue; + name = kid; + src = ((ray_t**)ray_data(vals))[i]->i64; + } else { + name = src = ray_table_col_name(tbl, i); + } + int64_t c = -1; + for (int64_t s = 0; s < nc && c < 0; s++) if (ray_table_col_name(tbl, s) == src) c = s; + ray_t* v; + if (c >= 0 && real[c]) { /* the sort rows are in place already */ + v = ray_table_get_col(res, src); + if (v) ray_retain(v); + else v = ray_error("domain", "select: lost a column of a parted table"); + } else { + v = c >= 0 ? parted_rows_gather(&pr, c) : ray_error("domain", "select: lost a column of a parted table"); + } + if (RAY_IS_ERR(v)) { ray_release(out); out = v; break; } + out = ray_table_add_col(out, name, v); + ray_release(v); + } + parted_rows_close(&pr); + ray_release(res); + scratch_free(buf_hdr); + return out ? out : ray_error("oom", NULL); } +/* References the select body owns for its whole run. It returns from + * dozens of places, so it hands them here and ray_select_impl releases them + * once, whichever exit the body took. */ +typedef struct { + ray_t* selection; /* the WHERE selection kept past the graph that owns + * it: the count(distinct) scatter reads it */ + ray_t* by_syms; /* by: rewritten into an owned symbol vector (a by-dict, + * a quoted key symbol); by_expr points into it */ +} select_owned_t; + +static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, + select_owned_t* own); + static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { + select_owned_t own = {0}; + ray_t* r = ray_select_body(args, n, aliases_resolved, &own); + if (own.selection) ray_release(own.selection); + if (own.by_syms) ray_release(own.by_syms); + return r; +} + +static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, + select_owned_t* own) { if (n < 1) return ray_error("arity", "select: expects a query dict, got %lld args", (long long)n); ray_t* dict = args[0]; if (!dict || dict->type != RAY_DICT) @@ -9178,6 +12349,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { 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)); } + select_scan_register(args, dict, tbl, where_expr); if (!aliases_resolved) { select_alias_plan_t plan; @@ -9185,7 +12357,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (engine && RAY_IS_ERR(engine)) { ray_release(tbl); return engine; } if (engine) { ray_t* r = ray_select_impl(&engine, 1, true); - if (plan.n_derived > 0) r = select_apply_derived(r, dict, &plan); + if (plan.n_derived > 0) r = select_apply_derived(r, dict, &plan, tbl); select_alias_plan_free(&plan); ray_release(engine); ray_release(tbl); @@ -9285,6 +12457,29 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (n_out == 0 && !where_expr && !by_expr && !take_expr && !has_sort && !nearest_expr) { DICT_VIEW_CLOSE(dv); return tbl; } + /* A grouped select with no outputs returns the first row of each group, + * every column of it, and its paths read plain columns: over a parted + * table it groups on the columns the clauses name and gathers the rest + * at the rows kept (select_parted_first_rows); a shape that helper does + * not take flattens the table. A where: flattens the rows it keeps. */ + if (n_out == 0 && by_expr && !where_expr && table_has_parted_columns(tbl)) { + ray_t* first = select_parted_first_rows(dict, tbl, aliases_resolved); + if (first) { ray_release(tbl); DICT_VIEW_CLOSE(dv); return first; } + ray_t* flat = query_materialize_parted_table(tbl); + if (!flat || RAY_IS_ERR(flat)) { ray_release(tbl); DICT_VIEW_CLOSE(dv); return flat ? flat : ray_error("oom", NULL); } + /* The select runs again over the flattened table, from the start: + * a key the planner cannot lower is evaluated over its columns + * there (select_plan_computed_key), as over any flat table. */ + ray_t* fd = select_dict_with_from(dict, flat); + ray_release(flat); + ray_release(tbl); + DICT_VIEW_CLOSE(dv); + if (!fd || RAY_IS_ERR(fd)) return fd ? fd : ray_error("oom", NULL); + ray_t* r = ray_select_impl(&fd, 1, true); + ray_release(fd); + return r; + } + /* Whole-table aggregates answered from column metadata: * `(select {from: T a: (sum c) b: (min d) …})` with no other clause, each * output one of count / min / max / sum / avg over a plain column that @@ -9339,6 +12534,19 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } } + /* Any other sort without by: over a parted table: the flat sort below + * reads plain columns. Sort the keys and gather the rows kept + * (select_parted_sorted); a shape it does not take flattens the table. + * A where: flattens the rows it keeps itself. */ + if (has_sort && !by_expr && !where_expr && !nearest_expr && table_has_parted_columns(tbl)) { + ray_t* sorted = select_parted_sorted(dict, tbl, aliases_resolved); + if (sorted) { ray_release(tbl); DICT_VIEW_CLOSE(dv); return sorted; } + ray_t* flat = query_materialize_parted_table(tbl); + ray_release(tbl); + if (!flat || RAY_IS_ERR(flat)) { DICT_VIEW_CLOSE(dv); return flat ? flat : ray_error("oom", NULL); } + tbl = flat; + } + /* Fused filter + top-K: shape `(select {col1: c1 col2: c2 … * from: T where: asc/desc: take: })` with no by/ * nearest clause and all output columns being plain SYM names of @@ -9488,7 +12696,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { ray_release(tbl); DICT_VIEW_CLOSE(dv); return res; } - if (res && RAY_IS_ERR(res)) ray_release(res); + if (res && RAY_IS_ERR(res)) ray_error_free(res); } if (n_sort_keys > 0 && k > 0 && k <= FPK_MAX_K && k < ray_table_nrows(tbl)) { ray_t* res = ray_fused_topk_select(tbl, where_expr, @@ -9502,7 +12710,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { ray_release(tbl); DICT_VIEW_CLOSE(dv); return res; } - if (res && RAY_IS_ERR(res)) ray_release(res); + if (res && RAY_IS_ERR(res)) ray_error_free(res); } } else if (tv) { ray_release(tv); @@ -9560,13 +12768,14 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { * column produces the SAME clean "column not found" error as a bare * `by: nonexistent` (rather than flowing into ray_elem_size on a literal * symbol and tripping UBSan). The owned name-ref rides in - * by_sym_vec_owned and is released with the other owned by-forms at - * function exit. Multi-key (RAY_DICT/list) and dotted by-forms are not + * own->by_syms, released by ray_select_impl with the other owned + * by-forms. Multi-key (RAY_DICT/list) and dotted by-forms are not * scalar -RAY_SYM literals and are left untouched. */ if (by_expr && by_expr->type == -RAY_SYM && (by_expr->attrs & ATTR_QUOTED)) { ray_t* nref = ray_sym(by_expr->i64); if (nref && !RAY_IS_ERR(nref)) { by_sym_vec_owned = nref; + own->by_syms = nref; by_expr = nref; } else if (nref) { ray_release(nref); @@ -9576,8 +12785,8 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { /* Selection saved across the path-A graph free for count(distinct * col_ref) non-aggs. Path B leaves this NULL because the * materialised filtered_tbl already encodes the selection in row - * positions. Declared here at function scope so the cleanup at - * the bottom of ray_select_fn can release it. */ + * positions. Borrowed: the reference is own->selection, released by + * ray_select_impl. */ ray_t* saved_selection = NULL; ray_t* post_group_where_expr = NULL; DICT_VIEW_DECL(byv); @@ -9677,6 +12886,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } ((int64_t*)ray_data(by_sym_vec_owned))[0] = base_key_name; by_sym_vec_owned->len = 1; + own->by_syms = by_sym_vec_owned; by_expr = by_sym_vec_owned; dep_key_base_sym = base_key_name; n_dep_keys = local_n_dep; @@ -9739,7 +12949,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (kid == from_id || kid == where_id || kid == by_id || kid == take_id || kid == asc_id || kid == desc_id || kid == nearest_id) continue; - if (!is_group_dag_agg_expr(dict_elems[i + 1])) defer_ok = false; + if (!is_group_dag_agg_expr(dict_elems[i + 1], tbl)) defer_ok = false; } for (int64_t i = 0; i < nk && defer_ok; i++) { ray_t* k = d_elems[i * 2]; @@ -9752,7 +12962,13 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (ray_table_get_col(tbl, k->i64) && !trivial_self) { defer_ok = false; break; /* alias shadows an input column */ } - if (v && v->type == RAY_LIST) continue; /* computed expr */ + if (v && v->type == RAY_LIST) { /* computed expr: one the planner lowers */ + ray_graph_t* pg = ray_graph_new(tbl); + bool lowers = pg && compile_expr_dag(pg, v) != NULL; + if (pg) ray_graph_free(pg); + if (!lowers) defer_ok = false; + continue; + } if (v && v->type == -RAY_SYM && !(v->attrs & ATTR_QUOTED)) { ray_t* src = ray_table_get_col(tbl, v->i64); if (!src || @@ -9772,6 +12988,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { int64_t* sv = (int64_t*)ray_data(by_sym_vec_owned); for (int64_t i = 0; i < nk; i++) sv[i] = d_elems[i * 2]->i64; by_sym_vec_owned->len = nk; + own->by_syms = by_sym_vec_owned; by_expr = by_sym_vec_owned; parted_bydict_deferred = true; deferred_bydict = by_dict_ast; @@ -9803,7 +13020,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { ray_group_emit_filter_t prefilter_top_count; memset(&prefilter_top_count, 0, sizeof(prefilter_top_count)); bool prefilter_top_n_match = - match_group_desc_count_take(dict_elems, dict_n, from_id, where_id, + match_group_desc_count_take(tbl, dict_elems, dict_n, from_id, where_id, by_id, take_id, asc_id, desc_id, &prefilter_top_count); /* A computed by-key (e.g. `(xbar EventTime …)`) is materialised over @@ -9835,7 +13052,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { kid == take_id || kid == asc_id || kid == desc_id || kid == nearest_id) continue; ray_t* val = dict_elems[i + 1]; - if (!is_group_dag_agg_expr(val)) continue; + if (!is_group_dag_agg_expr(val, tbl)) continue; ray_t** ae = (ray_t**)ray_data(val); if (!ae[0] || ae[0]->type != -RAY_SYM) continue; if (ae[0]->i64 == count_sym) continue; @@ -9883,7 +13100,12 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { n_keep = collect_col_refs_set(dict_elems[i + 1], tbl, keep_syms, (int)ncols_max, n_keep); } - int can_project = (n_keep > 0 && n_keep < ncols_max); + /* A select with no outputs returns every column of the table, + * in its order: there is nothing to narrow. Nor when a clause + * runs code (a helper) that reads columns the clauses do not + * name. */ + int can_project = (n_out > 0 && n_keep > 0 && n_keep < ncols_max && + clauses_name_their_columns(dict, tbl)); ray_t* narrow_tbl = NULL; if (can_project) { narrow_tbl = project_table_cols(tbl, keep_syms, n_keep); @@ -9941,6 +13163,71 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { where_expr = NULL; } + /* A literal in where: naming an alias about to become a column is + * wrapped first (select_where_shield_alias_literals); the select + * then runs again over the rewritten dict, as the materialized + * fallback does. */ + if (where_expr) { + where_shield_ctx_t wsc = { d_elems, nk, tbl, false }; + ray_t* shielded = select_where_shield_alias_literals(where_expr, &wsc); + if (!shielded || RAY_IS_ERR(shielded)) { + ray_release(tbl); + DICT_VIEW_CLOSE(dv); DICT_VIEW_CLOSE(byv); + return shielded ? shielded : ray_error("oom", NULL); + } + if (wsc.changed) { + /* The re-run takes the table `from:` already evaluated to, + * not the `from:` expression: evaluating that again would + * run its side effects twice. */ + ray_t* wkey = ray_sym(where_id); + ray_t* fkey = ray_sym(from_id); + ray_t* rewritten = NULL; + if (wkey && !RAY_IS_ERR(wkey) && fkey && !RAY_IS_ERR(fkey)) { + rewritten = dict; ray_retain(rewritten); + rewritten = ray_dict_upsert(rewritten, wkey, shielded); + if (rewritten && !RAY_IS_ERR(rewritten)) + rewritten = ray_dict_upsert(rewritten, fkey, tbl); + } + if (wkey && !RAY_IS_ERR(wkey)) ray_release(wkey); + if (fkey && !RAY_IS_ERR(fkey)) ray_release(fkey); + ray_release(shielded); + ray_release(tbl); + DICT_VIEW_CLOSE(dv); DICT_VIEW_CLOSE(byv); + if (!rewritten || RAY_IS_ERR(rewritten)) + return rewritten ? rewritten : ray_error("oom", NULL); + ray_t* r = ray_select_impl(&rewritten, 1, aliases_resolved); + ray_release(rewritten); + return r; + } + ray_release(shielded); + } + + /* A by-dict value the planner cannot lower (a helper, a builtin + * with no kernel) is evaluated below over whole columns: over a + * parted table, flatten the columns the select reads first (the + * whole table with no output, or when a clause runs code whose + * reads are unseen). */ + if (table_has_parted_columns(tbl)) { + bool unlowered = false; + for (int64_t i = 0; i < nk && !unlowered; i++) { + ray_t* v = d_elems[i * 2 + 1]; + if (!v || v->type != RAY_LIST) continue; + ray_graph_t* pg = ray_graph_new(tbl); + unlowered = !pg || compile_expr_dag(pg, v) == NULL; + if (pg) ray_graph_free(pg); + } + if (unlowered) { + ray_t* flat = n_out > 0 ? parted_flatten_read_cols(dict, tbl) + : query_materialize_parted_table(tbl); + ray_release(tbl); + if (!flat || RAY_IS_ERR(flat)) { + DICT_VIEW_CLOSE(dv); DICT_VIEW_CLOSE(byv); + return flat ? flat : ray_error("oom", NULL); + } + tbl = flat; + } + } + ray_env_push_query_scope(); int64_t in_ncols = ray_table_ncols(tbl); for (int64_t c = 0; c < in_ncols; c++) { @@ -10026,6 +13313,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { ray_release(tbl); DICT_VIEW_CLOSE(dv); DICT_VIEW_CLOSE(byv); return fail_err; } + own->by_syms = by_sym_vec_owned; by_expr = by_sym_vec_owned; } by_dict_done: @@ -10039,7 +13327,6 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { ray_graph_t* g = ray_graph_new(tbl); if (!g) { scratch_free(dep_src_hdr); /* bridged dep-key collector (dep path only; NULL otherwise) */ - if (by_sym_vec_owned) ray_release(by_sym_vec_owned); ray_release(tbl); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); } @@ -10060,7 +13347,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (kid == from_id || kid == where_id || kid == by_id || kid == take_id || kid == asc_id || kid == desc_id || kid == nearest_id) continue; - hidden_max += count_agg_subexprs(dict_elems[i + 1]); + hidden_max += count_agg_subexprs(dict_elems[i + 1], tbl); } if (n_out_max < 1) n_out_max = 1; /* zero-size alloc guard */ if (hidden_max < 1) hidden_max = 1; @@ -10087,7 +13374,6 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { (size_t)(nk_max + 2 * aggs_max) * sizeof(uint32_t)); if (!nonagg_names) { scratch_free(dep_src_hdr); - if (by_sym_vec_owned) ray_release(by_sym_vec_owned); ray_graph_free(g); ray_release(tbl); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); } ray_t** nonagg_exprs = (ray_t**)(nonagg_names + n_out_max); @@ -10126,7 +13412,10 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { int synth_count_col = 0; /* 1 if we synthesized OP_COUNT for group boundaries */ int has_list_agg = 0; /* 1 if any aggregate emits a LIST column (top/bot) */ - if (where_expr && by_expr && !nearest_expr && + /* Not without outputs: the deferred filter runs on the aggregated + * result, which a no-output select does not reach; it filters the rows + * first, as for any other key. */ + if (where_expr && by_expr && !nearest_expr && n_out > 0 && can_defer_single_key_where(by_expr, where_expr, tbl)) { post_group_where_expr = where_expr; where_expr = NULL; @@ -10561,7 +13850,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (by_expr) { ray_group_emit_filter_t cur_emit = ray_group_emit_filter_get(); if (!cur_emit.enabled && - match_group_desc_count_take(dict_elems, dict_n, from_id, where_id, + match_group_desc_count_take(tbl, dict_elems, dict_n, from_id, where_id, by_id, take_id, asc_id, desc_id, &pre_top_emit)) pre_top_emit_matched = true; @@ -10599,7 +13888,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { kid == take_id || kid == asc_id || kid == desc_id) continue; if (is_single_group_key_projection(by_expr, dict_elems[i + 1])) continue; - if (is_group_dag_agg_expr(dict_elems[i + 1])) continue; + if (is_group_dag_agg_expr(dict_elems[i + 1], tbl)) continue; /* Arithmetic over aggregates is served by hidden agg slots * plus one post-group evaluation on any key shape; it must * not push multi-key queries onto eval-level grouping. */ @@ -10704,7 +13993,14 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } else if (by_expr->type == RAY_SYM && ray_len(by_expr) == 1) { single_scalar_key = 1; } - if (!single_scalar_key) use_eval_group = 1; + /* A plain multi-key by: stays on the DAG path when the outputs + * the DAG cannot serve are count(distinct) aggregates and + * literal broadcasts (no true row expression): the scatter + * maps rows to groups through the composite key (#756). The + * eval-level grouping it took before is serial. */ + if (!single_scalar_key && + !(!any_true_nonagg && multikey_scatter_keys_ok(by_expr, tbl))) + use_eval_group = 1; } if (use_eval_group) { /* Apply WHERE filter first (if any), then eval-level groupby */ @@ -10747,6 +14043,10 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (!fres || RAY_IS_ERR(fres)) { ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return fres ? fres : ray_error("domain", "select: `where:` filter produced no result"); } if (ray_is_lazy(fres)) fres = ray_lazy_materialize(fres); if (!fres || RAY_IS_ERR(fres)) { ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return fres ? fres : ray_error("domain", "select: failed to materialize filtered result"); } + /* A filter that keeps every row hands back the input itself, with + * a reference of its own; the exits release eval_tbl only when it + * is another table. */ + if (fres == tbl) ray_release(fres); eval_tbl = fres; } else { ray_graph_free(g); g = NULL; @@ -10889,7 +14189,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (kid == from_id || kid == where_id || kid == by_id || kid == take_id || kid == asc_id || kid == desc_id) continue; ray_t* val_expr_item = dict_elems[i + 1]; - if (!is_plain_count_expr(val_expr_item)) { + if (!is_plain_count_expr(val_expr_item, eval_tbl)) { /* Not a plain count expr — use the general path * (never silently drop outputs). */ count_only = false; @@ -11183,7 +14483,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { continue; } - if (is_streaming_aggr_unary_call(val_expr_item)) { + if (is_streaming_aggr_unary_call(val_expr_item, eval_tbl)) { ray_t** agg_elems = (ray_t**)ray_data(val_expr_item); ray_t* agg_fn_name = agg_elems[0]; ray_t* agg_col_expr = agg_elems[1]; @@ -11193,13 +14493,11 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (src_col_val) ray_retain(src_col_val); } if (!src_col_val) { - src_col_val = ray_eval(agg_col_expr); - /* Materialize a lazy result up front: the - * per-group ray_at_fn consumes lazy args - * (see aggr_unary_per_group_buf). */ - if (src_col_val && ray_is_lazy(src_col_val)) - src_col_val = ray_lazy_materialize(src_col_val); - if (!src_col_val || RAY_IS_ERR(src_col_val)) { + /* An expression argument reads the columns: + * evaluate it over the selected rows with the + * columns in scope (#756). */ + src_col_val = select_eval_over_table(agg_col_expr, eval_tbl); + if (RAY_IS_ERR(src_col_val)) { for (int ai = 0; ai < n_agg_out; ai++) if (agg_results[ai]) ray_release(agg_results[ai]); scratch_free(aggnames_hdr); scratch_free(aggres_hdr); scratch_free(keycols_hdr); ray_release(groups); if (eval_tbl != tbl) ray_release(eval_tbl); ray_release(tbl); @@ -11284,7 +14582,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { agg_results[n_agg_out] = agg_vec; n_agg_out++; } else { - ray_t* per_group = nonagg_eval_per_group(val_expr_item, eval_tbl, groups, n_groups); + ray_t* per_group = nonagg_eval_per_group(val_expr_item, eval_tbl, groups, out_groups); if (!per_group || RAY_IS_ERR(per_group)) { for (int ai = 0; ai < n_agg_out; ai++) if (agg_results[ai]) ray_release(agg_results[ai]); scratch_free(aggnames_hdr); scratch_free(aggres_hdr); scratch_free(keycols_hdr); @@ -11779,7 +15077,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } } - if (is_streaming_aggr_unary_call(val_expr_item)) { + if (is_streaming_aggr_unary_call(val_expr_item, eval_tbl)) { /* Streaming-style per-group AGG branch. Accepts both * the resolve_agg_opcode whitelist (sum/avg/min/max/...) * and the broader RAY_FN_AGGR + RAY_UNARY set @@ -11797,12 +15095,10 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (src_col_val) ray_retain(src_col_val); } if (!src_col_val) { - src_col_val = ray_eval(agg_col_expr); - /* Materialize a lazy result up front: the - * per-group ray_at_fn consumes lazy args - * (see aggr_unary_per_group_buf). */ - if (src_col_val && !RAY_IS_ERR(src_col_val) && ray_is_lazy(src_col_val)) - src_col_val = ray_lazy_materialize(src_col_val); + /* An expression argument reads the columns: + * evaluate it over the selected rows with the + * columns in scope (#756). */ + src_col_val = select_eval_over_table(agg_col_expr, eval_tbl); if (RAY_IS_ERR(src_col_val)) { for (int ai = 0; ai < n_agg_out; ai++) { if (agg_results[ai]) ray_release(agg_results[ai]); } scratch_free(aggnames_hdr); scratch_free(aggres_hdr); @@ -12396,10 +15692,12 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { /* Retain a copy of the selection so it survives the * later ray_graph_free. count(distinct col_ref) needs * this in the n_nonaggs scatter to mask filtered-out - * rows in the row→gid build. */ + * rows in the row→gid build. ray_select_impl releases + * it after the select returns. */ if (g->selection) { saved_selection = g->selection; ray_retain(saved_selection); + own->selection = saved_selection; } } else { root = ray_optimize(g, root); @@ -12723,6 +16021,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (!fres || RAY_IS_ERR(fres)) { ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return fres ? fres : ray_error("domain", "select: `where:` filter produced no result"); } if (ray_is_lazy(fres)) fres = ray_lazy_materialize(fres); if (!fres || RAY_IS_ERR(fres)) { ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return fres ? fres : ray_error("domain", "select: failed to materialize filtered result"); } + if (fres == tbl) ray_release(fres); /* as eval_tbl above: every row kept */ filtered_tbl = fres; /* Rebuild graph on filtered table for GROUP+COUNT */ g = ray_graph_new(filtered_tbl); @@ -12765,6 +16064,15 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { key_sym = by_expr->i64; else if (by_expr->type == RAY_SYM && ray_len(by_expr) == 1) key_sym = ((int64_t*)ray_data(by_expr))[0]; + /* So must a name that is no column of the table (a global + * vector): the grouping above evaluated it as an expression. */ + if (key_sym >= 0 && !ray_table_get_col(filtered_tbl, key_sym)) + key_sym = -1; + /* And a column name the grouping did not read as that column: a + * local of the same name shadows it, the key is the local's value + * and its grouped column is not named after the column. */ + if (key_sym >= 0 && !ray_table_get_col(grouped, key_sym)) + key_sym = -1; if (n_groups == 0) { ray_release(grouped); @@ -12830,14 +16138,19 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { ray_table_get_col_idx(filtered_tbl, c)); } ray_t* ck_vec = ray_eval(by_expr); + if (ck_vec && !RAY_IS_ERR(ck_vec) && ray_is_lazy(ck_vec)) + ck_vec = ray_lazy_materialize(ck_vec); ray_env_pop_scope(); - if (ck_vec && !RAY_IS_ERR(ck_vec) && ray_is_vec(ck_vec)) { + if (ck_vec && !RAY_IS_ERR(ck_vec) && + (ray_is_vec(ck_vec) || ck_vec->type == RAY_LIST)) { int8_t kt = ck_vec->type; empty_key_vec = (kt == RAY_STR) ? ray_vec_new(RAY_STR, 0) : (kt == RAY_LIST) ? ray_list_new(0) : ray_vec_new(kt, 0); + } else if (ck_vec && !RAY_IS_ERR(ck_vec) && ck_vec->type < 0) { + empty_key_vec = atom_broadcast_vec(ck_vec, 0); /* one value */ } if (ck_vec && !RAY_IS_ERR(ck_vec)) ray_release(ck_vec); } @@ -12875,12 +16188,43 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } ray_t* computed_key = derived_key_over_sym_domain(by_expr, filtered_tbl, NULL); if (!computed_key) computed_key = ray_eval(by_expr); + if (computed_key && !RAY_IS_ERR(computed_key) && ray_is_lazy(computed_key)) + computed_key = ray_lazy_materialize(computed_key); /* `(mmax 2 x)` */ ray_env_pop_scope(); if (!computed_key || RAY_IS_ERR(computed_key)) { if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return computed_key ? computed_key : ray_error("domain", "select by: failed to evaluate group key expression"); } + /* One value (a name bound to an atom) is the key of every + * row, as the grouping above read it: one group. */ + if (computed_key->type < 0) { + ray_t* wide = atom_broadcast_vec(computed_key, ray_table_nrows(filtered_tbl)); + ray_release(computed_key); + if (!wide || RAY_IS_ERR(wide)) { + if (filtered_tbl != tbl) ray_release(filtered_tbl); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return wide ? wide : ray_error("type", "by: cannot broadcast the key"); + } + computed_key = wide; + } + /* A key of another length is no row-aligned key (the DAG + * group's rule; one value is one group): its group rows + * would index past the columns gathered below. */ + { + int64_t ck_rows = ray_table_nrows(filtered_tbl); + int64_t ck_len = (ray_is_vec(computed_key) || computed_key->type == RAY_LIST) + ? ray_len(computed_key) : ck_rows; + if (ck_len != ck_rows && ck_len != 1) { + ray_release(computed_key); + if (filtered_tbl != tbl) ray_release(filtered_tbl); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return ray_error("length", "by: key has %lld values for %lld rows", + (long long)ck_len, (long long)ck_rows); + } + } ray_t* groups2_dict = ray_group_indices_fn(computed_key); if (!groups2_dict || RAY_IS_ERR(groups2_dict)) { ray_release(computed_key); @@ -12975,45 +16319,46 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } } + /* Columns are gathered at the first row of each group by + * ray_group_gather, which builds every column type: STR + * (store_typed_elem has no STR case and left the cells + * unset), LIST, GUID and SYM over its own domain. */ ray_t* res2 = ray_table_new(tbl_ncols + 1); /* Key column: computed_key's first-of-group values, which * are the distinct grouping-key values surfaced to the * user. Using the source column at fi2 indices would lose * the transform (e.g. raw Timestamp instead of its `.ss`). */ - if (ray_is_vec(computed_key)) { - ray_t* kv = ray_vec_new(computed_key->type, ng2); - if (!RAY_IS_ERR(kv)) { - /* len BEFORE store loop — ray_vec_set_null (called - * by store_typed_elem for null atoms) range-checks - * idx against vec->len and silently no-ops - * otherwise. */ - kv->len = ng2; - for (int64_t g2 = 0; g2 < ng2; g2++) { - int a2 = 0; - ray_t* v2 = collection_elem(computed_key, fi2[g2], &a2); - store_typed_elem(kv, g2, v2); - if (a2) ray_release(v2); - } + if ((ray_is_vec(computed_key) || computed_key->type == RAY_LIST) && !RAY_IS_ERR(res2)) { + ray_t* kv = ray_group_gather(computed_key, fi2, ng2); + if (!kv || RAY_IS_ERR(kv)) { + ray_release(res2); + res2 = kv ? kv : ray_error("oom", NULL); + } else { res2 = ray_table_add_col(res2, ckey_name, kv); ray_release(kv); } } - for (int64_t c = 0; c < tbl_ncols; c++) { + for (int64_t c = 0; c < tbl_ncols && !RAY_IS_ERR(res2); c++) { int64_t cn = ray_table_col_name(filtered_tbl, c); /* Avoid duplicating a column name already used by the * key: e.g. `by: Timestamp` (plain, non-dotted) would * collide with the source Timestamp column. */ if (cn == ckey_name) continue; ray_t* sc = ray_table_get_col_idx(filtered_tbl, c); - ray_t* dc = ray_vec_new(sc->type, ng2); - dc->len = ng2; /* see note above — hoisted for null bits */ - for (int64_t g2 = 0; g2 < ng2; g2++) { int a2 = 0; ray_t* v2 = collection_elem(sc, fi2[g2], &a2); store_typed_elem(dc, g2, v2); if (a2) ray_release(v2); } + ray_t* dc = ray_group_gather(sc, fi2, ng2); + if (!dc || RAY_IS_ERR(dc)) { + ray_release(res2); + res2 = dc ? dc : ray_error("oom", NULL); + break; + } res2 = ray_table_add_col(res2, cn, dc); ray_release(dc); } if (fi2_hdr) ray_free(fi2_hdr); ray_release(groups2); ray_release(computed_key); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); + res2 = apply_sort_take(res2, dict_elems, dict_n, + asc_id, desc_id, take_id, NULL); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return res2; } @@ -13024,6 +16369,15 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { * grp_key_col points into grouped — must not access after release. */ ray_t* grp_key_col = ray_table_get_col(grouped, key_sym); int8_t kt = orig_key_col ? orig_key_col->type : 0; + /* Both hold once key_sym names a column the grouping read (see + * where key_sym is resolved); refuse rather than read unset keys. */ + if (!orig_key_col || !grp_key_col) { + ray_release(grouped); + if (filtered_tbl != tbl) ray_release(filtered_tbl); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return ray_error("domain", "select by: group key column not found"); + } /* Heap-allocate gk_vals when n_groups > 256 */ int64_t gk_stack[256]; @@ -13380,6 +16734,13 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { s_use_eval_fallback = 1; break; } + /* OP_GROUP's COUNT counts source rows. A constant collection + * has its own length, independent of the source or WHERE. */ + if (op == OP_COUNT && op_tree_is_scalar(g, s_agg_ins[s_n_aggs]->id) && + !op_tree_is_atom(g, s_agg_ins[s_n_aggs]->id)) { + s_use_eval_fallback = 1; + break; + } /* Canonical aggregand type-admission (same table as the scalar * builtins): reject non-numeric (SYM/STR/GUID) and, for sum, * absolute-temporal (DATE/TIMESTAMP) inputs so the DAG never @@ -13647,7 +17008,10 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { 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 */ + int64_t out_len = -1; /* common non-scalar column length */ + /* Compilation was abandoned; reuse its alias-id scratch. */ + uint32_t* scalar_cols = alias_ids; + int64_t output_col = 0; for (int64_t i = 0; i + 1 < dict_n; i += 2) { int64_t kid = dict_elems[i]->i64; if (kid == from_id || kid == where_id || kid == by_id || @@ -13657,17 +17021,19 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { * entire column and must be evaluated once, not scattered * 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 + * value is then broadcast. 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 whole_verb = is_whole_column_projection(expr, tbl); int one_value = !whole_verb && (!any_row_proj || - (select_fallback_has_agg(expr) && !expr_refs_row_column(expr, tbl))); + (select_fallback_has_agg(expr) && !expr_refs_row_column(expr, tbl)) || + (ray_is_atom(expr) && expr->type != -RAY_SYM)); + bool scalar_col = false; /* A row column mixed with an aggregate in one * expression: its aggregates are reduced once over * the whole table before the scatter, which would @@ -13680,27 +17046,59 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (reduced && !RAY_IS_ERR(reduced)) expr = reduced; } ray_t* col; + ray_t* expanded = NULL; + query_inline_scope_t scope = { .table = tbl }; + /* A helper called from this output reads source columns, + * not the aliases bound into the evaluation table. */ + ray_t* prev_source = g_query_source_table; + g_query_source_table = g->table; 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); + /* Expand after aggregate classification: a helper's + * own reduction retains its row-local scope. Use the + * source schema so prior aliases cannot capture free + * names; actual arguments still evaluate in tbl. */ + int inline_budget = 1024; + expanded = !query_expr_has_helper(expr) || query_expr_effect_free(expr) + ? query_inline_walk(expr, g->table, NULL, 0, 0, &inline_budget, false, &scope) + : NULL; + if (!expanded) { ray_retain(expr); expanded = expr; } + expr = expanded; + ray_t* eval_tbl = scope.table; + /* A helper may expose a collection concat that must + * consume its complete operands, just like inline. */ + if (!eval_tbl || RAY_IS_ERR(eval_tbl)) { + col = eval_tbl ? eval_tbl : ray_error("oom", NULL); + scope.owned = false; + } else { + if (!whole_verb) whole_verb = is_whole_column_projection(expr, eval_tbl); + col = select_fallback_passthrough_col(expr, eval_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_impl(expr, eval_tbl, 1) + : (whole_verb || one_value) + ? eval_expr_whole_column_impl(expr, eval_tbl) + : eval_expr_per_row_impl(expr, eval_tbl, nrows); + bool enlist_scalar = whole_verb && expr->type == RAY_LIST && + ((ray_t**)ray_data(expr))[0]->i64 == ray_sym_intern("enlist", 6); + scalar_col = col && !RAY_IS_ERR(col) && (one_value || enlist_scalar) && + (ray_is_atom(col) || (ray_is_vec(col) && ray_len(col) == 1)); + if (scalar_col) col = select_fallback_broadcast(col, 1); + } } if (reduced) ray_release(reduced); } + if (scope.owned && scope.table) ray_release(scope.table); + if (expanded) ray_release(expanded); + g_query_source_table = prev_source; if (!col || RAY_IS_ERR(col)) { ray_t* err = col ? col : ray_error("domain", "select: failed to evaluate output column expression"); ray_release(result); @@ -13714,9 +17112,10 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { * projection (e.g. distinct) beside a full-length column would * yield a ragged table. Reject rather than emit one. */ int64_t col_len = ray_len(col); - if (out_len < 0) { + scalar_cols[output_col++] = scalar_col; + if (!scalar_col && out_len < 0) { out_len = col_len; - } else if (col_len != out_len) { + } else if (!scalar_col && col_len != out_len) { ray_release(col); ray_release(result); if (nearest_handle_owned) ray_release(nearest_handle_owned); @@ -13732,8 +17131,13 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { * 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 (scalar_col || col_len == bcast_len) { + ray_t* alias_col = col; + ray_retain(alias_col); + if (scalar_col) alias_col = select_fallback_broadcast(alias_col, bcast_len); + ray_t* bound = !alias_col || RAY_IS_ERR(alias_col) ? alias_col + : select_fallback_bind_alias(tbl, kid, alias_col); + if (alias_col && !RAY_IS_ERR(alias_col)) ray_release(alias_col); if (!bound || RAY_IS_ERR(bound)) { ray_release(col); ray_release(result); @@ -13755,11 +17159,23 @@ 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 = select_fallback_finish_columns(result, scalar_cols, + out_len >= 0 ? out_len : bcast_len); + /* A sort key the projections do not output (`desc: n` over + * `{c: ...}`) is a source column; the DAG sorts before it + * projects, so it can read one. Carry such a key into the + * result for the sort and drop it after. */ + int64_t carried = 0; + if (has_sort && result && !RAY_IS_ERR(result)) + result = select_fallback_carry_sort_keys(result, tbl, dict_elems, dict_n, + asc_id, desc_id, &carried); 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); result = apply_sort_take(result, dict_elems, dict_n, asc_id, desc_id, take_id, NULL); + if (carried && result && !RAY_IS_ERR(result)) + result = select_fallback_drop_tail_cols(result, carried); scratch_free(colops_hdr); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } else { @@ -14168,11 +17584,21 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (ray_env_push_query_scope() != RAY_OK) { cerr = ray_error("oom", NULL); } else { + /* One value per group, each derived from the group's + * rows: the flag lets `concat` treat a reduced text cell + * as a cell (a null is empty text, a literal joins it) + * rather than as a collection. */ for (int hi = 0; hi < n_hidden_aggs; hi++) - ray_env_set_local(hidden_agg_names[hi], - ray_table_get_col_idx(result, - hbase + hi)); + (void)ray_env_set_local_rows(hidden_agg_names[hi], + ray_table_get_col_idx(result, hbase + hi), 1); int64_t n_groups = ray_table_nrows(result); + /* The wrappers are query text over the group result: + * `concat` and the other query-aware forms read the + * active table, as they do for a derived output. */ + ray_t* prev_aqt = g_active_query_table; + int64_t prev_aqr = g_active_query_row; + g_active_query_table = result; + g_active_query_row = -1; for (int ci = 0; ci < n_compound && !cerr; ci++) { ray_t* v = ray_eval(compound_rw[ci]); if (!v || RAY_IS_ERR(v)) { @@ -14191,6 +17617,8 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { ray_release(v); } else comp_cols[ci] = v; } + g_active_query_table = prev_aqt; + g_active_query_row = prev_aqr; ray_env_pop_scope(); } } @@ -14287,12 +17715,20 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } } - /* Resolve key sym — gated to single scalar key above. */ + /* Resolve key sym — a single scalar key, or the first key of a + * composite by: (routed here by multikey_scatter_keys_ok): the + * first key resolves the row count and the type checks below, + * and rgid_build_multikey maps rows over every key. */ int64_t ks = -1; + int64_t mk_nk = 0; if (by_expr->type == -RAY_SYM && !(by_expr->attrs & ATTR_QUOTED)) ks = by_expr->i64; else if (by_expr->type == RAY_SYM && ray_len(by_expr) == 1) ks = ((int64_t*)ray_data(by_expr))[0]; + else if (by_expr->type == RAY_SYM && ray_len(by_expr) > 1) { + mk_nk = ray_len(by_expr); + ks = ((int64_t*)ray_data(by_expr))[0]; + } if (ks < 0) { ray_release(result); ray_release(tbl); @@ -14342,11 +17778,13 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { case RAY_I16: (dst) = ((const int16_t* )_d)[idx]; break; \ case RAY_I32: (dst) = ((const int32_t* )_d)[idx]; break; \ case RAY_I64: (dst) = ((const int64_t* )_d)[idx]; break; \ - case RAY_F32: { uint32_t _u; \ - memcpy(&_u, &((const float*)_d)[idx], 4); \ + case RAY_F32: { uint32_t _u; /* -0.0 -> +0.0, as */ \ + memcpy(&_u, &((const float*)_d)[idx], 4); /* key_read_i64 */ \ + if (_u == 0x80000000u) _u = 0; \ (dst) = (int64_t)_u; break; } \ case RAY_F64: { int64_t _u; \ memcpy(&_u, &((const double*)_d)[idx], 8); \ + if (_u == INT64_MIN) _u = 0; \ (dst) = _u; break; } \ case RAY_DATE: case RAY_TIME: \ (dst) = ((const int32_t*)_d)[idx]; break; \ @@ -14433,7 +17871,18 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { * 5M * 730K ≈ 4T comparisons. Build a value→gid hash * instead so each row is one O(1) probe. */ int rgid_did_mask = 0; - if (okt == RAY_STR) { + if (mk_nk > 1) { + ray_t* mk_err = rgid_build_multikey(tbl, result, by_expr, nrows, + n_groups, saved_selection, row_gid); + if (mk_err) { + 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 mk_err; + } + rgid_did_mask = 1; /* the probe applied the selection */ + } else if (okt == RAY_STR) { /* Dict-code row_gid fast path: when the group key is a * dict-encoded STR column, exec_group already grouped on its * int32 codes and stashed the per-result-group codes. Build @@ -14861,7 +18310,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { * group and calling the unary fn directly into a typed * vec. Equivalent perf-class to the streaming AGG path * the eval-fallback uses for the same shapes. */ - if (is_streaming_aggr_unary_call(nonagg_exprs[ni])) { + if (is_streaming_aggr_unary_call(nonagg_exprs[ni], tbl)) { ray_t* col = NULL; /* `(med col)` fast path — bucket-scatter values * into a reused scratch and quickselect, skipping @@ -15023,7 +18472,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { for (int64_t ni = 0; ni < n_nonaggs; ni++) { ray_t* expr = nonagg_exprs[ni]; ray_t* empty_list = match_count_distinct(expr) ? ray_vec_new(RAY_I64, 0) - : is_streaming_aggr_unary_call(expr) ? aggr_unary_per_group_buf(expr, tbl, NULL, NULL, NULL, 0) + : is_streaming_aggr_unary_call(expr, tbl) ? aggr_unary_per_group_buf(expr, tbl, NULL, NULL, NULL, 0) : can_atom_broadcast(expr) ? atom_broadcast_vec(expr, 0) : ray_list_new(0); if (!empty_list || RAY_IS_ERR(empty_list)) { ray_release(result); ray_release(tbl); @@ -15076,6 +18525,12 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } } + /* Fallback outputs are appended after native aggregates. Restore the + * requested output order using the same layout pass as derived aliases. */ + if (by_expr && result && !RAY_IS_ERR(result)) { + select_alias_plan_t layout = {0}; + result = select_apply_derived(result, dict, &layout, tbl); + } ray_release(tbl); /* Post-process: apply sort/take for group-by queries. Runs @@ -15086,8 +18541,6 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { take_id, take_pre.kind ? &take_pre : NULL); - if (by_sym_vec_owned) ray_release(by_sym_vec_owned); - if (saved_selection) ray_release(saved_selection); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } @@ -15310,6 +18763,10 @@ static int8_t typeless_col_type(ray_t* payload) { * appending to an existing column (for insert/upsert). */ static ray_t* append_atom_to_col(ray_t* col_vec, ray_t* atom) { if (RAY_ATOM_IS_NULL(atom)) { + /* A string column's null is the empty string, a pool payload like + * any other: it cannot be appended as a fixed-width zero cell. */ + if (col_vec->type == RAY_STR) + return ray_str_vec_append(col_vec, "", 0); int64_t idx = col_vec->len; uint8_t zero[16] = {0}; col_vec = ray_vec_append(col_vec, zero); @@ -15418,7 +18875,9 @@ static ray_t* append_boxed_table_col(ray_t* orig_col, ray_t* payload, if (cells[r]) ray_retain(cells[r]); } } else { - dst[orig_col->len] = payload; + /* A row that leaves this column out boxes the null object: a C + * NULL cell is not a value, and reading one aborts. */ + dst[orig_col->len] = payload ? payload : RAY_NULL_OBJ; if (payload) ray_retain(payload); } out->len = orig_col->len + tail; @@ -15518,12 +18977,12 @@ static int update_where_index_rows(ray_t* tbl, ray_t* where_expr, int64_t key = ok ? (col->type == RAY_SYM ? v->i64 : upsert_atom_int(v)) : 0; ray_release(v); if (!ok) return 0; - const int64_t* ids = NULL; int64_t n = 0; + ray_idx_rows_t ids = { NULL, false }; int64_t n = 0; int hit = ray_index_hash_group(col, key, &ids, &n); if (hit < 0) return 0; int64_t* out = (int64_t*)scratch_alloc(rows_hdr, (size_t)(n > 0 ? n : 1) * sizeof(int64_t)); if (!out) return 0; - if (n > 0) memcpy(out, ids, (size_t)n * sizeof(int64_t)); + for (int64_t i = 0; i < n; i++) out[i] = ray_idx_rows_at(ids, i); *rows = out; *n_out = n; return 1; } @@ -15546,11 +19005,10 @@ static ray_t* update_where_mask_vec(ray_t* tbl, ray_t* where_expr) { ray_graph_free(g); } 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++) - ray_env_set_query_local(ray_table_col_name(tbl, c), ray_table_get_col_idx(tbl, c)); - mask_vec = ray_eval(where_expr); + ray_t* prev_table = bind_all_columns(tbl); + mask_vec = eval_query_expr(where_expr, tbl); + g_active_query_table = prev_table; ray_env_pop_scope(); } if (!mask_vec) return ray_error("type", "update: `where:` predicate evaluation failed"); @@ -15703,11 +19161,16 @@ static bool update_dag_err_final(ray_t* out, bool if_refused) { * 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) { +/* `dag_declined`, when given, belongs to one grouped update: the planner + * declining the expression over one group would decline it over the next, + * so the groups after the first skip the graph and go to the evaluator + * directly. The ungrouped callers pass NULL and always try the planner, + * whose error (a misspelt column) is the one reported. */ +static ray_t* update_eval_on_impl(ray_t* sub, ray_t* expr, bool expand, bool* dag_declined) { ray_t* out = NULL; ray_t* cerr = NULL; bool if_refused = false; - ray_graph_t* g = ray_graph_new(sub); + ray_graph_t* g = dag_declined && *dag_declined ? NULL : ray_graph_new(sub); if (g) { ray_op_t* op = compile_expr_dag(g, expr); if (op) { @@ -15715,6 +19178,7 @@ static ray_t* update_eval_on(ray_t* sub, ray_t* expr) { out = ray_execute(g, op); } else { cerr = graph_take_compile_err(g); + if (dag_declined) *dag_declined = true; } if_refused = g->if_refused; ray_graph_free(g); @@ -15744,14 +19208,14 @@ static ray_t* update_eval_on(ray_t* sub, ray_t* expr) { 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_t* prev_table = bind_all_columns(sub); + out = expand ? eval_query_expr(expr, sub) : ray_eval(expr); + g_active_query_table = prev_table; ray_env_pop_scope(); } else { - out = eval_expr_per_row(expr, sub, nrows); + out = expand ? eval_expr_per_row(expr, sub, nrows) + : eval_expr_per_row_impl(expr, sub, nrows); } if ((!out || RAY_IS_ERR(out)) && cerr) { if (out) ray_error_free(out); @@ -15765,6 +19229,10 @@ static ray_t* update_eval_on(ray_t* sub, ray_t* expr) { return update_scalar_vec(out, ray_table_nrows(sub)); } +static ray_t* update_eval_on(ray_t* sub, ray_t* expr) { + return update_eval_on_impl(sub, expr, true, NULL); +} + static bool update_numeric_promo(int8_t ct, int8_t et) { return (ct == RAY_I64 || ct == RAY_I32 || ct == RAY_F64) && (et == RAY_I64 || et == RAY_I32 || et == RAY_F64); @@ -16161,9 +19629,14 @@ ray_t* ray_update(ray_t** args, int64_t n) { ray_t** upd_cols = (ray_t**)(upd_names + upd_slots); uint8_t* upd_used = (uint8_t*)(upd_cols + upd_slots); + ray_t* prepared_expr = NULL; + query_dependency_cache_t dependencies = {0}; #define UPDATE_BY_CLEANUP_COLS() do { \ for (int64_t _ui = 0; _ui < n_updates; _ui++) \ if (upd_cols[_ui]) ray_release(upd_cols[_ui]); \ + if (prepared_expr) { ray_release(prepared_expr); prepared_expr = NULL; } \ + for (int _di = 0; _di < dependencies.n; _di++) ray_release(dependencies.exprs[_di]); \ + dependencies.n = 0; \ scratch_free(upd_hdr); \ } while (0) @@ -16173,6 +19646,22 @@ ray_t* ray_update(ray_t** args, int64_t n) { int64_t kid = dict_elems[d]->i64; if (kid == from_id || kid == where_id || kid == by_id) continue; ray_t* agg_expr = dict_elems[d + 1]; + /* Pure helpers can be expanded once for every group's identical + * schema. Keep effectful expressions on the per-group path. */ + /* The expansion is text over the schema, the same for every + * group, so it is made once; an opaque helper left in it is + * called per group by the evaluator. Only a pure expansion also + * caches its dependency analysis across groups. */ + bool expand = false; + bool pure_expansion = false; + if (query_expr_has_helper(agg_expr)) { + ray_t* candidate = query_inline_helpers(agg_expr, tbl); + prepared_expr = candidate; + agg_expr = candidate; + pure_expansion = query_inline_pure(candidate, 0); + } + bool cache_dependencies = (prepared_expr ? pure_expansion : query_inline_pure(agg_expr, 0)); + bool dag_declined = false; /* the planner declined this expression for a group */ /* We need to evaluate the aggregate per group. * Build the result column by evaluating the expression on each group's subset. */ @@ -16245,7 +19734,13 @@ ray_t* ray_update(ray_t** args, int64_t n) { * 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); + query_dependency_cache_t* prev_dependencies = g_query_dependencies; + if (cache_dependencies) { + dependencies.table = sub_tbl; + g_query_dependencies = &dependencies; + } + ray_t* agg_result = update_eval_on_impl(sub_tbl, agg_expr, expand, &dag_declined); + g_query_dependencies = prev_dependencies; 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; } @@ -16327,6 +19822,9 @@ ray_t* ray_update(ray_t** args, int64_t n) { upd_names[upd_i] = kid; upd_cols[upd_i] = out_col; upd_i++; + if (prepared_expr) { ray_release(prepared_expr); prepared_expr = NULL; } + for (int di = 0; di < dependencies.n; di++) ray_release(dependencies.exprs[di]); + dependencies.n = 0; } /* Build result in schema order: replace existing targets in place, then @@ -16404,14 +19902,10 @@ ray_t* ray_update(ray_t** args, int64_t n) { /* Fallback: eval-level predicate evaluation */ 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(); - for (int64_t c = 0; c < ncols2; c++) { - int64_t cn = ray_table_col_name(tbl, c); - ray_t* col = ray_table_get_col_idx(tbl, c); - ray_env_set_query_local(cn, col); - } - mask_vec = ray_eval(where_expr); + ray_t* prev_table = bind_all_columns(tbl); + mask_vec = eval_query_expr(where_expr, tbl); + g_active_query_table = prev_table; 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"); } @@ -18593,7 +22087,7 @@ ray_t* ray_insert(ray_t** args, int64_t n) { if (ct == RAY_LIST) { /* Boxed column: a table payload supplies a LIST whose cells * are rows and is spliced; any other row shape boxes its - * payload (or a NULL slot) as one cell — the same contract + * payload (or the null object) as one cell — the same contract * as append_boxed_table_col, minus the copy. */ if (tbl_row_list) { if (!pay || RAY_IS_ERR(pay) || pay->type != RAY_LIST) { @@ -18608,7 +22102,8 @@ ray_t* ray_insert(ray_t** args, int64_t n) { } } } else { - res = ray_list_append(col, pay); + /* a left-out column boxes the null object, as above */ + res = ray_list_append(col, pay ? pay : RAY_NULL_OBJ); } } else if (!pay) { ray_t* null_atom = ray_typed_null(-ct); @@ -19107,7 +22602,7 @@ static bool ukey_grow(ray_index_t* ix, int64_t entries) { if (cap < old_cap) cap = old_cap; if (cap > UKEY_MAX_CAP) return false; ray_t* fresh = ray_vec_new(RAY_I64, (int64_t)cap); - if (!fresh || RAY_IS_ERR(fresh)) { if (fresh) ray_release(fresh); return false; } + if (!fresh || RAY_IS_ERR(fresh)) { ray_error_free(fresh); return false; } fresh->len = (int64_t)cap; int64_t* dst = (int64_t*)ray_data(fresh); memset(dst, 0, (size_t)cap * sizeof(int64_t)); @@ -19248,7 +22743,7 @@ static ray_t* upsert_write_cell(ray_t** slots, int64_t c, int64_t row, ray_t* ce return NULL; } -/* Append one row; a NULL cell lands as the column's null (a NULL slot +/* Append one row; a NULL cell lands as the column's null (the null object * for a boxed column), mirroring the legacy insert arm. */ static ray_t* upsert_append_row(ray_t** slots, int64_t ncols, ray_t** cells) { for (int64_t c = 0; c < ncols; c++) { @@ -19256,7 +22751,7 @@ static ray_t* upsert_append_row(ray_t** slots, int64_t ncols, ray_t** cells) { ray_t* cell = cells[c]; ray_t* res; if (col->type == RAY_LIST) { - res = ray_list_append(col, cell); + res = ray_list_append(col, cell ? cell : RAY_NULL_OBJ); } else if (!cell) { ray_t* na = ray_typed_null(-col->type); res = append_atom_to_col(col, na); @@ -19584,6 +23079,24 @@ static ray_t* upsert_apply_vectors(ray_t** slots, int64_t ncols, * `tbl` is borrowed. Returns the result (the binding's symbol, or a * fresh table) or an error, and sets *handled; returns NULL with * *handled false when a gate misses and the legacy arms should run. */ +/* A multi-row payload's columns (NULL = left out) against `m` key values: + * each must be a list or vector of exactly m cells. NULL on yes, the error + * otherwise. Both multi-row writers ask this before they read a cell; a + * writer that skipped it read past a shorter value vector. */ +static ray_t* upsert_check_multirow(ray_t** cols, int64_t ncols, int64_t m) { + for (int64_t c = 0; c < ncols; c++) { + ray_t* sc = cols[c]; + if (!sc) continue; + if (!is_collection(sc)) + return ray_error("type", "upsert: multi-row value for column %lld must be a list or vector, got %s", + (long long)c, ray_type_name(sc->type)); + if (ray_len(sc) != m) + return ray_error("length", "upsert: column %lld has %lld values, key has %lld", + (long long)c, (long long)ray_len(sc), (long long)m); + } + return NULL; +} + static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, const int64_t* kci, int64_t nk, ray_t** src_cols, ray_t** atoms, int64_t m, @@ -19641,19 +23154,10 @@ static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, if (vec_path) { /* typed payload vectors are read in place */ } else if (src_cols) { + err = upsert_check_multirow(src_cols, ncols, m); for (int64_t c = 0; c < ncols && !err; c++) { ray_t* sc = src_cols[c]; if (!sc) continue; - if (!is_collection(sc)) { - err = ray_error("type", "upsert: multi-row value for column %lld must be a list or vector, got %s", - (long long)c, ray_type_name(sc->type)); - break; - } - if (ray_len(sc) != m) { - err = ray_error("length", "upsert: column %lld has %lld values, key has %lld", - (long long)c, (long long)ray_len(sc), (long long)m); - break; - } for (int64_t r = 0; r < m; r++) { int alloc = 0; ray_t* e = collection_elem(sc, r, &alloc); @@ -20044,25 +23548,22 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { } int64_t n_pairs = dkeys->len; - /* Schema-strictness: every column name must appear exactly once - * on each side. Mirrors the table-payload path. */ - if (n_pairs != ncols) { - ray_release(tbl); ray_release(key_sym); ray_release(row); - return ray_error("value", NULL); - } - for (int64_t c = 0; c < ncols; c++) { - int64_t cn = ray_table_col_name(tbl, c); + /* Schema-strictness, as for a table payload: a dict row is a + * partial row too. Every dict key must name exactly one target + * column and appear once; columns it leaves out are null-filled, + * as insert fills them. Requiring every column refused a dict + * that a one-row table with the same columns upserts. */ + for (int64_t d = 0; d < n_pairs; d++) { + /* dict-key cell vs runtime column NAME id (see insert) */ + int64_t dk = sym_cell_runtime_id(dkeys, d); int64_t tbl_matches = 0, dict_matches = 0; for (int64_t i = 0; i < ncols; i++) - if (ray_table_col_name(tbl, i) == cn) tbl_matches++; - for (int64_t d = 0; d < n_pairs; d++) { - /* dict-key cell vs runtime column NAME id (see insert) */ - int64_t dk = sym_cell_runtime_id(dkeys, d); - if (dk == cn) dict_matches++; - } + if (ray_table_col_name(tbl, i) == dk) tbl_matches++; + for (int64_t e = 0; e < n_pairs; e++) + if (sym_cell_runtime_id(dkeys, e) == dk) dict_matches++; if (tbl_matches != 1 || dict_matches != 1) { ray_release(tbl); ray_release(key_sym); ray_release(row); - return ray_error("value", NULL); + return ray_error("value", "upsert: dict row key must name one target column, once"); } } @@ -20124,9 +23625,18 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { return ray_error("type", "upsert: key must be a symbol or integer, got %s", ray_type_name(ks_t)); } + /* Every key column must carry a value: a dict row (or a row a table + * payload left a column out of) may not, and the match reads them. */ + for (int64_t k = 0; k < n_key_cols; k++) { + if (!row_elems[key_col_indices[k]]) { + scratch_free(kci_hdr); + ray_release(tbl); ray_release(key_sym); ray_release(row); + return ray_error("value", "upsert: row is missing a key column"); + } + } + /* Multi-row upsert: if row values are vectors, iterate row-by-row */ ray_t* key_elem = row_elems[key_col_indices[0]]; - if (!key_elem) { scratch_free(kci_hdr); ray_release(tbl); ray_release(key_sym); ray_release(row); return ray_error("domain", "upsert: key value missing"); } { bool multi = ray_is_vec(key_elem) || key_elem->type == RAY_LIST; bool fast_handled = false; @@ -20141,6 +23651,14 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { } if (ray_is_vec(key_elem) || key_elem->type == RAY_LIST) { int64_t new_nrows = ray_len(key_elem); + /* A target upsert_apply declines (mapped, sliced, narrow symbols) + * comes here: the same shape check before any cell is read. */ + ray_t* shape_err = upsert_check_multirow(row_elems, ncols, new_nrows); + if (shape_err) { + scratch_free(kci_hdr); + ray_release(tbl); ray_release(key_sym); ray_release(row); + return shape_err; + } ray_t* cur_tbl = tbl; ray_retain(cur_tbl); for (int64_t r = 0; r < new_nrows; r++) { @@ -20152,7 +23670,8 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { ray_t** sr = (ray_t**)ray_data(single_row); for (int64_t c = 0; c < ncols; c++) { int alloc = 0; - sr[c] = collection_elem(row_elems[c], r, &alloc); + /* A column a dict row left out stays a NULL slot. */ + sr[c] = row_elems[c] ? collection_elem(row_elems[c], r, &alloc) : NULL; if (!alloc && sr[c]) ray_retain(sr[c]); } /* Upsert single row into current table */ @@ -21813,7 +25332,7 @@ static ray_t* asof_parted_select_operand(ray_t* arg_ast, ray_t** out_dict) { ray_t* from_expr = dict_get(dict, "from"); if (!from_expr) return NULL; ray_t* tbl = ray_eval(from_expr); - if (!tbl || RAY_IS_ERR(tbl)) { if (tbl) ray_release(tbl); return NULL; } + if (!tbl || RAY_IS_ERR(tbl)) { ray_error_free(tbl); return NULL; } if (tbl->type != RAY_TABLE || asof_parted_seg_count(tbl) < 0) { ray_release(tbl); return NULL; @@ -22157,8 +25676,9 @@ static ray_t* try_stream_parted_order_by( * pure per-row gather, so per-partition evaluation is row-preserving. An * aggregate/expression output would collapse per segment (one row per * partition) and diverge from flat, so it declines. - * 5. Every sort key resolves to an output column (its alias), so the - * candidate table carries the sort column for the final merge. */ + * 5. Every sort key is an output carrying that column under its own name + * (`k: k`), so the candidate table carries the sort column for the + * final merge, and the merge sorts on what each segment sorted on. */ static ray_t* try_stream_parted_order_by_topk( ray_t* dict, ray_t* tbl, ray_t** dict_elems, int64_t dict_n, int64_t from_id, int64_t where_id, int64_t by_id, int64_t take_id, @@ -22203,8 +25723,9 @@ static ray_t* try_stream_parted_order_by_topk( if (!ray_table_get_col(tbl, v->i64)) return NULL; } - /* Every sort key must appear as an output alias (dict key of an output - * column), so the candidate table carries the sort column. */ + /* Every sort key must be an output of that column under its name: the + * segments sort on the column, the merge on the output (`{x: y asc: x}` + * declines). */ for (int64_t i = 0; i + 1 < dict_n; i += 2) { int64_t kid = dict_elems[i]->i64; if (kid != asc_id && kid != desc_id) continue; @@ -22222,7 +25743,10 @@ static ray_t* try_stream_parted_order_by_topk( if (okid == from_id || okid == where_id || okid == by_id || okid == take_id || okid == asc_id || okid == desc_id || okid == nearest_id) continue; - if (okid == sk) found = true; + if (okid == sk) { + if (dict_elems[j + 1]->i64 != sk) return NULL; + found = true; + } } if (!found) return NULL; } diff --git a/src/ops/select_merge.c b/src/ops/select_merge.c new file mode 100644 index 000000000..1918d1112 --- /dev/null +++ b/src/ops/select_merge.c @@ -0,0 +1,446 @@ +/* Copyright (c) 2026 Anton Kundenko + * SPDX-License-Identifier: MIT + * + * Conservative composition of literal select/from/select pairs (#752). + * This is an admission proof, not a general expression simplifier. Only + * total, row-local expressions may move across a filter. In particular, + * (- x (avg x)), windows, vector literals, user calls and casts are barriers. + */ +#include "lang/internal.h" +#include "lang/env.h" +#include "ops/internal.h" +#include "table/dict.h" +#include "table/sym.h" +#include + +#define MERGE_COLS 128 +#define MERGE_NODES 1024 +#define MERGE_MIN_ROWS 8192 +#define MERGE_PREFIX_ROWS 64 + +/* Runtime restarts invalidate intern IDs. Keep the cache thread-local and + * refresh it once per symbol-table lifetime, not once per clause lookup. */ +static _Thread_local uint64_t merge_epoch; +static _Thread_local int64_t merge_ids[9]; + +typedef struct { + int64_t name; + ray_t* expr; /* owned, expanded against the base */ + int type; + unsigned uses; + bool computed; +} merge_col_t; + +typedef struct { + ray_t* table; + merge_col_t cols[MERGE_COLS]; + int n, nodes; + bool projected; +} merge_scope_t; + +static void merge_drop(ray_t* x) { + if (x && RAY_IS_ERR(x)) ray_error_free(x); + else if (x) ray_release(x); +} + +static ray_t* merge_ref(ray_t* x) { ray_retain(x); return x; } + +/* Fresh fixed-arity lists need no COW/growth operation. There is no partially + * built list to lose if an append allocation fails. */ +static ray_t* merge_call(ray_t* head, ray_t* a, ray_t* b) { + ray_t* r = ray_list_new(b ? 3 : 2); + if (!r || RAY_IS_ERR(r)) { merge_drop(r); return NULL; } + ray_t** es = ray_data(r); + es[0] = merge_ref(head); es[1] = merge_ref(a); + if (b) es[2] = merge_ref(b); + r->len = b ? 3 : 2; + return r; +} + +static int merge_clause(int64_t id) { + for (int i = 1; i <= 7; i++) if (id == merge_ids[i]) return i; + return 0; +} + +static bool merge_dict_shape(ray_t* d) { + if (!d || d->type != RAY_DICT) return false; + ray_t* k = ray_dict_keys(d), *v = ray_dict_vals(d); + if (!k || k->type != RAY_SYM || !v || v->type != RAY_LIST || k->len != v->len || + k->len > MERGE_COLS) return false; + return true; +} + +static bool merge_dict_ok(ray_t* d) { + if (!merge_dict_shape(d)) return false; + ray_t* k = ray_dict_keys(d); + /* A duplicate clause has evaluation-order semantics; never normalize it. */ + for (int64_t i = 0; i < k->len; i++) + for (int64_t j = 0; j < i; j++) + if (sym_cell_runtime_id(k, i) == sym_cell_runtime_id(k, j)) return false; + return true; +} + +static ray_t* merge_get(ray_t* d, int clause) { + ray_t* k = ray_dict_keys(d), **v = ray_data(ray_dict_vals(d)); + for (int64_t i = 0; i < k->len; i++) + if (sym_cell_runtime_id(k, i) == merge_ids[clause]) return v[i]; + return NULL; +} + +static ray_t* merge_put(ray_t* d, int64_t id, ray_t* value) { + ray_t* k = ray_sym(id); + if (!k || RAY_IS_ERR(k)) { merge_drop(k); merge_drop(d); return NULL; } + ray_t* r = ray_dict_upsert(d, k, value); + ray_release(k); + if (r && RAY_IS_ERR(r)) { merge_drop(r); return NULL; } + return r; +} + +/* Reject shadowed builtins, including source columns used as call heads. */ +static ray_t* merge_fn(merge_scope_t* s, ray_t* head) { + if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED) || + ray_table_get_col(s->table, head->i64) || ray_env_has_lexical_local(head->i64)) return NULL; + for (int i = 0; i < s->n; i++) if (s->cols[i].name == head->i64) return NULL; + return ray_env_get(head->i64); +} + +static bool merge_numeric(int t) { return t == RAY_I64 || t == RAY_F64; } + +/* Charge the expanded tree, not just alias references. Repeated aliases can + * otherwise turn a small input DAG into exponential work for the compiler. */ +static bool merge_charge(merge_scope_t* s, ray_t* e, int depth) { + if (depth > 16 || ++s->nodes > MERGE_NODES) return false; + if (e->type != RAY_LIST) return true; + ray_t** es = ray_data(e); + for (int64_t i = 1; i < e->len; i++) if (!merge_charge(s, es[i], depth + 1)) return false; + return true; +} + +/* Return an owned expansion, or NULL to decline. `column` distinguishes + * scalar expressions from expressions preserving the input row count. */ +static ray_t* merge_expr(merge_scope_t* s, ray_t* e, int* type, bool* column, int depth) { + *column = false; + if (!e || depth > 16 || ++s->nodes > MERGE_NODES) return NULL; + if (e->type == -RAY_SYM) { + if (!(e->attrs & ATTR_QUOTED) && ray_env_has_lexical_local(e->i64)) return NULL; + for (int i = s->n - 1; i >= 0; i--) if (s->cols[i].name == e->i64) { + if (++s->cols[i].uses > 1 && s->cols[i].computed) return NULL; + if (!merge_charge(s, s->cols[i].expr, depth)) return NULL; + *type = s->cols[i].type; *column = true; + return merge_ref(s->cols[i].expr); + } + ray_t* col = ray_table_get_col(s->table, e->i64); + if (col && !s->projected && col->type > 0 && col->type <= RAY_STR) { + *type = col->type; *column = true; + return merge_ref(e); + } + /* A quoted literal must not become a column reference after merge. */ + if (!(e->attrs & ATTR_QUOTED) || col) return NULL; + *type = RAY_SYM; + return merge_ref(e); + } + if (e->type < 0 && (merge_numeric(-e->type) || e->type == -RAY_BOOL || e->type == -RAY_STR)) { + *type = -e->type; + return merge_ref(e); + } + if (e->type != RAY_LIST || e->len != 3 || (e->attrs & ATTR_QUOTED)) return NULL; + ray_t** es = ray_data(e), *fn = merge_fn(s, es[0]); + if (!fn) return NULL; + int kind = 0; + if (fn->type == RAY_BINARY) { + ray_binary_fn f = (ray_binary_fn)(uintptr_t)fn->i64; + if (f == ray_add_fn || f == ray_sub_fn || f == ray_mul_fn) kind = 1; + if (f == ray_eq_fn || f == ray_neq_fn) kind = 2; + if (f == ray_lt_fn || f == ray_lte_fn || f == ray_gt_fn || f == ray_gte_fn) kind = 3; + } + if (fn->type == RAY_VARY && ((ray_vary_fn)(uintptr_t)fn->i64 == ray_and_vary_fn || + (ray_vary_fn)(uintptr_t)fn->i64 == ray_or_vary_fn)) kind = 4; + if (!kind) return NULL; + int lt = 0, rt = 0; bool lc = false, rc = false; + ray_t* l = merge_expr(s, es[1], <, &lc, depth + 1); + ray_t* r = l ? merge_expr(s, es[2], &rt, &rc, depth + 1) : NULL; + bool numeric = merge_numeric(lt) && merge_numeric(rt); + bool ok = kind == 1 ? numeric : kind == 4 ? lt == RAY_BOOL && rt == RAY_BOOL : + numeric || (lt == rt && (lt == RAY_BOOL || (kind == 2 && (lt == RAY_SYM || lt == RAY_STR)))); + ray_t* out = NULL; + if (l && r && ok) { + *type = kind == 1 ? (lt == RAY_F64 || rt == RAY_F64 ? RAY_F64 : RAY_I64) : RAY_BOOL; + *column = lc || rc; + out = merge_call(es[0], l, r); + } + merge_drop(l); merge_drop(r); + return out; +} + +/* Computed aggregates admit only literal scales of an F64 column. Other + * arithmetic can create null lanes that existing flat reduction paths do + * not handle like a materialized vector: offsets, column products, and I64 + * intermediates (even when a later multiplier promotes the result to F64). */ +static bool merge_scaled_f64(ray_t* table, ray_t* e) { + if (e->type == -RAY_SYM) { + ray_t* col = ray_table_get_col(table, e->i64); + return col && col->type == RAY_F64; + } + if (e->type != RAY_LIST || e->len != 3) return false; + ray_t** es = ray_data(e); + ray_t* fn = ray_env_get(es[0]->i64); + if (!fn || fn->type != RAY_BINARY || (ray_binary_fn)(uintptr_t)fn->i64 != ray_mul_fn) return false; + for (int i = 1; i <= 2; i++) + if ((es[i]->type == -RAY_I64 || es[i]->type == -RAY_F64) && !RAY_ATOM_IS_NULL(es[i]) && + merge_scaled_f64(table, es[3 - i])) return true; + return false; +} + +static ray_t* merge_output(merge_scope_t* s, ray_t* e, int* type) { + bool col; + if (e && e->type == RAY_LIST && e->len == 2) { + ray_t** es = ray_data(e), *fn = merge_fn(s, es[0]); + if (!fn || fn->type != RAY_UNARY) return NULL; + ray_unary_fn f = (ray_unary_fn)(uintptr_t)fn->i64; + if (f != ray_sum_fn && f != ray_avg_fn && f != ray_min_fn && f != ray_max_fn && f != ray_count_fn) + return NULL; + ray_t* arg = merge_expr(s, es[1], type, &col, 0); + if (!arg || !col || (!merge_numeric(*type) && f != ray_count_fn)) { merge_drop(arg); return NULL; } + if (arg->type == RAY_LIST && !merge_scaled_f64(s->table, arg)) { + merge_drop(arg); return NULL; + } + ray_t* r = merge_call(es[0], arg, NULL); + merge_drop(arg); + if (r && RAY_IS_ERR(r)) { merge_drop(r); return NULL; } + return r; + } + ray_t* r = merge_expr(s, e, type, &col, 0); + if (!col) { merge_drop(r); return NULL; } + return r; +} + +static bool merge_identity(ray_t* e, int64_t name) { + return e && e->type == -RAY_SYM && e->i64 == name; +} + +static bool merge_mentions(ray_t* e, int64_t name) { + if (e->type == -RAY_SYM) return e->i64 == name; + if (e->type != RAY_LIST) return false; + ray_t** es = ray_data(e); + for (int64_t i = 1; i < e->len; i++) if (merge_mentions(es[i], name)) return true; + return false; +} + +/* A nonempty PREFIX proves the source is nonempty without scanning for a rare + * or absent match. This check visits at most 64 rows, independent of table size. + * If it cannot prove nonemptiness, leave the original query materialized. The + * existing aggregate paths distinguish an empty source from an empty filter. + */ +static bool merge_prefix_nonempty(ray_t* table, ray_t* where) { + int64_t nc = ray_table_ncols(table); + ray_t* prefix = ray_table_new(nc); + if (!prefix || RAY_IS_ERR(prefix)) { merge_drop(prefix); return false; } + for (int64_t i = 0; i < nc; i++) { + ray_t* c = ray_vec_slice(ray_table_get_col_idx(table, i), 0, MERGE_PREFIX_ROWS); + if (!c || RAY_IS_ERR(c)) { merge_drop(c); merge_drop(prefix); return false; } + prefix = ray_table_add_col(prefix, ray_table_col_name(table, i), c); + merge_drop(c); + if (!prefix || RAY_IS_ERR(prefix)) { merge_drop(prefix); return false; } + } + ray_t* d = ray_dict_new(ray_vec_new(RAY_SYM, 0), ray_list_new(0)); + if (!d || RAY_IS_ERR(d)) { merge_drop(d); merge_drop(prefix); return false; } + d = merge_put(d, merge_ids[1], prefix); + merge_drop(prefix); + if (d) d = merge_put(d, merge_ids[2], where); + if (!d) return false; + ray_t* r = ray_select(&d, 1); + bool nonempty = r && !RAY_IS_ERR(r) && r->type == RAY_TABLE && ray_table_nrows(r) > 0; + merge_drop(r); merge_drop(d); + return nonempty; +} + +static ray_t* merge_pair(ray_t* outer, ray_t* inner) { + ray_t* base = merge_get(inner, 1); + ray_t* tbl = base; + /* ray_env_get searches caller scopes before globals (env_lookup_flat), + * so a shadowing lambda source supplies the rows and types proved here. */ + if (base && base->type == -RAY_SYM && !(base->attrs & ATTR_QUOTED) && !ray_sym_is_dotted(base->i64)) + tbl = ray_env_get(base->i64); + if (!tbl || tbl->type != RAY_TABLE || ray_table_nrows(tbl) < MERGE_MIN_ROWS) return NULL; + /* Partitioned/lazy and list columns need their own materialization proof, + * including errors from columns an outer projection would discard. */ + for (int64_t i = 0; i < ray_table_ncols(tbl); i++) { + ray_t* c = ray_table_get_col_idx(tbl, i); + if (!c || c->type <= 0 || c->type > RAY_STR) return NULL; + } + ray_t* ik = ray_dict_keys(inner), **iv = ray_data(ray_dict_vals(inner)); + ray_t* ok = ray_dict_keys(outer), **ov = ray_data(ray_dict_vals(outer)); + for (int64_t i = 0; i < ik->len; i++) if (merge_clause(sym_cell_runtime_id(ik, i)) > 2) return NULL; + if (merge_get(outer, 7)) return NULL; + /* Scalar reductions can lose to compacting a selective inner filter, + * even with an outer predicate. Keep them materialized until the planner + * has a cost estimate that accounts for the inner filter's selectivity. */ + if (merge_get(inner, 2) && !merge_get(outer, 3)) { + for (int64_t i = 0; i < ok->len; i++) + if (!merge_clause(sym_cell_runtime_id(ok, i)) && + ov[i]->type == RAY_LIST && ov[i]->len == 2) return NULL; + } + /* Avoid introducing the AND + take early-stop regression reported in #752. */ + if (merge_get(outer, 4) && merge_get(inner, 2) && merge_get(outer, 2)) return NULL; + merge_scope_t s = {.table = tbl}; + ray_t* where = NULL, *out = NULL, *v = NULL; + int type; bool col; + if (merge_get(inner, 2)) { + where = merge_expr(&s, merge_get(inner, 2), &type, &col, 0); + if (!where || type != RAY_BOOL || !col) goto done; + } + for (int64_t i = 0; i < ik->len; i++) { + int64_t name = sym_cell_runtime_id(ik, i); + if (merge_clause(name)) continue; + v = merge_expr(&s, iv[i], &type, &col, 0); + if (!v || !col || (ray_table_get_col(tbl, name) && !merge_identity(v, name))) goto done; + s.cols[s.n++] = (merge_col_t){.name = name, .expr = v, .type = type, + .computed = v->type == RAY_LIST}; + v = NULL; + } + s.projected = s.n > 0; + out = ray_dict_new(ray_vec_new(RAY_SYM, 0), ray_list_new(0)); + if (!out || RAY_IS_ERR(out)) goto done; + out = merge_put(out, merge_ids[1], base); + if (!out) goto done; + if (merge_get(outer, 2)) { + v = merge_expr(&s, merge_get(outer, 2), &type, &col, 0); + if (!v || type != RAY_BOOL || !col) goto decline; + if (where) { + ray_t* head = ray_sym(merge_ids[8]); + ray_t* fn = head && !RAY_IS_ERR(head) ? merge_fn(&s, head) : NULL; + if (!fn || fn->type != RAY_VARY || (ray_vary_fn)(uintptr_t)fn->i64 != ray_and_vary_fn) { + merge_drop(head); goto decline; + } + ray_t* both = merge_call(head, where, v); + merge_drop(head); merge_drop(where); merge_drop(v); v = NULL; where = both; + if (!where || RAY_IS_ERR(where)) goto decline; + } else { where = v; v = NULL; } + } + if (where) out = merge_put(out, merge_ids[2], where); + if (!out) goto done; + int64_t outputs[MERGE_COLS]; int nout = 0; + bool aggregate = false; + for (int64_t i = 0; i < ok->len; i++) { + int64_t name = sym_cell_runtime_id(ok, i); + int clause = merge_clause(name); + if (clause == 1 || clause == 2) continue; + if (clause == 4) { + if (ov[i]->type != -RAY_I64 || RAY_ATOM_IS_NULL(ov[i]) || ov[i]->i64 < 0) goto decline; + v = merge_ref(ov[i]); + } else if (clause == 3) { + /* Keep group-key labels: only identity keys in this first pass. */ + v = merge_expr(&s, ov[i], &type, &col, 0); + if (!v || !col || ov[i]->type != -RAY_SYM || !merge_identity(v, ov[i]->i64)) goto decline; + } else if (clause == 5 || clause == 6) { + /* Sort names refer to the result, not the source. No substitution. */ + if (ov[i]->type != -RAY_SYM) goto decline; + v = merge_ref(ov[i]); + } else { + v = merge_output(&s, ov[i], &type); + if (!v || (ray_table_get_col(tbl, name) && !merge_identity(v, name))) goto decline; + aggregate |= v->type == RAY_LIST && v->len == 2; + if (merge_get(outer, 4) && !(v->type == RAY_LIST && v->len == 2) && + (type == RAY_SYM || type == RAY_STR)) goto decline; + /* Expansion must not capture an earlier output alias. */ + for (int j = 0; j < nout; j++) + if (merge_mentions(v, outputs[j]) || merge_mentions(ov[i], outputs[j])) goto decline; + outputs[nout++] = name; + } + out = merge_put(out, name, v); merge_drop(v); v = NULL; + if (!out) goto done; + } + if (!nout && s.projected) { + if (merge_get(outer, 3)) goto decline; + for (int i = 0; i < s.n; i++) { + if (++s.cols[i].uses > 1 && s.cols[i].computed) goto decline; + /* The take/filter gather and projection paths currently retain + * different text HAS_NULLS metadata. Keep their wire result stable. */ + if (merge_get(outer, 4) && (s.cols[i].type == RAY_SYM || s.cols[i].type == RAY_STR)) goto decline; + out = merge_put(out, s.cols[i].name, s.cols[i].expr); + if (!out) goto done; + } + } + if (!nout && !s.projected && merge_get(outer, 4)) { + for (int64_t i = 0; i < ray_table_ncols(tbl); i++) { + ray_t* c = ray_table_get_col_idx(tbl, i); + if (!c || c->type == RAY_SYM || c->type == RAY_STR) goto decline; + } + } + for (int clause = 5; clause <= 6; clause++) { + ray_t* sort = merge_get(outer, clause); + if (!sort) continue; + /* The flat planner cannot sort this computed/renamed projection yet. Keep + * the inner result materialized so its sort key is a stored column. */ + for (int i = 0; i < s.n; i++) + if (s.cols[i].name == sort->i64 && + !merge_identity(s.cols[i].expr, sort->i64)) goto decline; + bool visible = !nout && !s.projected && ray_table_get_col(tbl, sort->i64); + for (int i = 0; i < nout; i++) visible |= outputs[i] == sort->i64; + if (!nout) for (int i = 0; i < s.n; i++) visible |= s.cols[i].name == sort->i64; + /* A group key is also an output even without an explicit projection. */ + ray_t* by = merge_get(outer, 3); + visible |= by && merge_identity(by, sort->i64); + if (!visible) goto decline; + } + for (int i = 0; i < s.n; i++) if (s.cols[i].computed && !s.cols[i].uses) goto decline; + if (aggregate && merge_get(inner, 2) && !merge_prefix_nonempty(tbl, merge_get(inner, 2))) goto decline; + goto done; +decline: + merge_drop(out); out = NULL; +done: + if (out && RAY_IS_ERR(out)) { merge_drop(out); out = NULL; } + merge_drop(where); merge_drop(v); + for (int i = 0; i < s.n; i++) merge_drop(s.cols[i].expr); + return out; +} + +static bool merge_row_shape(ray_t* e, int depth) { + if (!e || depth > 16) return false; + if (e->type < 0) return true; + if (e->type != RAY_LIST || e->len != 3) return false; + ray_t** es = ray_data(e); + return merge_row_shape(es[1], depth + 1) && merge_row_shape(es[2], depth + 1); +} + +static ray_t* merge_plan(ray_t* dict, int depth) { + if (depth > 8 || !merge_dict_shape(dict)) return NULL; + ray_t* from = merge_get(dict, 1); + if (!from || from->type != RAY_LIST || from->len != 2 || (from->attrs & ATTR_QUOTED)) return NULL; + ray_t** es = ray_data(from); + if (!es[0] || es[0]->type != -RAY_SYM || (es[0]->attrs & ATTR_QUOTED) || + es[0]->i64 != merge_ids[0]) return NULL; + if (!merge_dict_shape(es[1])) return NULL; + /* Tiny wide projections must also skip quadratic duplicate-key checks. */ + ray_t* base = merge_get(es[1], 1), *table = base; + if (base && base->type == -RAY_SYM && !(base->attrs & ATTR_QUOTED) && !ray_sym_is_dotted(base->i64)) + table = ray_env_get(base->i64); + if (table && table->type == RAY_TABLE && ray_table_nrows(table) < MERGE_MIN_ROWS) return NULL; + ray_t* fn = ray_env_get(es[0]->i64); + if (!fn || fn->type != RAY_VARY || (ray_vary_fn)(uintptr_t)fn->i64 != ray_select || + !merge_dict_ok(dict) || !merge_dict_ok(es[1])) return NULL; + /* Do not speculatively plan (and probe) an aggregate child only to throw + * the plan away because the parent cannot cross that aggregate. */ + ray_t* keys = ray_dict_keys(es[1]), **vals = ray_data(ray_dict_vals(es[1])); + for (int64_t i = 0; i < keys->len; i++) { + int clause = merge_clause(sym_cell_runtime_id(keys, i)); + if (clause > 2 || (!clause && !merge_row_shape(vals[i], 0))) return NULL; + } + ray_t* inner = merge_plan(es[1], depth + 1); + ray_t* out = merge_pair(dict, inner ? inner : es[1]); + merge_drop(inner); + return out; +} + +ray_t* ray_select_merge_plan(ray_t* dict) { + uint64_t epoch = ray_sym_epoch(); + if (merge_epoch != epoch) { + static const char* const names[] = {"select", "from", "where", "by", "take", "asc", "desc", "nearest", "and"}; + for (int i = 0; i < 9; i++) { + merge_ids[i] = ray_sym_intern(names[i], strlen(names[i])); + if (merge_ids[i] < 0) return NULL; + } + merge_epoch = epoch; + } + return merge_plan(dict, 0); +} diff --git a/src/ops/string.c b/src/ops/string.c index 389175147..73bd2792b 100644 --- a/src/ops/string.c +++ b/src/ops/string.c @@ -27,6 +27,7 @@ #include "ops/rowsel.h" #include "core/pool.h" #include "lang/format.h" /* ray_type_name (error context) */ +#include "lang/env.h" #include "lang/internal.h" /* ray_like_fn (list-of-strings delegate) */ /* ============================================================================ @@ -1404,54 +1405,31 @@ ray_t* exec_replace(ray_graph_t* g, ray_op_t* op) { return result; } -/* CONCAT(a, b, ...) */ -ray_t* exec_concat(ray_graph_t* g, ray_op_t* op) { - ray_op_ext_t* ext = find_ext(g, op->id); - if (!ext) return ray_error("nyi", NULL); - int64_t raw_nargs = ext->sym; - if (raw_nargs < 2 || raw_nargs > 255) return ray_error("arity", "concat: expected 2 to 255 arguments, got %lld", (long long)raw_nargs); - int n_args = (int)raw_nargs; - - /* Evaluate all inputs */ - ray_t* args_stack[16]; - ray_t** args = args_stack; - ray_t* args_hdr = NULL; - if (n_args > 16) { - args = (ray_t**)scratch_calloc(&args_hdr, (size_t)n_args * sizeof(ray_t*)); - if (!args) return ray_error("oom", NULL); - } - - args[0] = exec_node(g, op_child(g, op, 0)); - args[1] = exec_node(g, op_child(g, op, 1)); - uint32_t* trail = (uint32_t*)((char*)(ext + 1)); - for (int i = 2; i < n_args; i++) { - args[i] = exec_node(g, &g->nodes[trail[i - 2]]); - } - /* Error check */ - for (int i = 0; i < n_args; i++) { - if (!args[i] || RAY_IS_ERR(args[i])) { - ray_t* err = args[i]; - for (int j = 0; j < n_args; j++) { - if (j != i && args[j] && !RAY_IS_ERR(args[j])) ray_release(args[j]); - } - scratch_free(args_hdr); - return err; - } - } - - /* Derive nrows from first vector arg (scalar args have byte-length in len) */ +/* Shared text kernel. Consumes one reference to each argument. A STR + * vector makes the result STR; `str_out` says a STR atom does too (a cell + * of a STR column read row by row). */ +/* `cells[a]` (one flag per argument, or NULL for none): argument a is a + * cell of the query's rows (a column's element, or a text column reduced to + * one value by first/last/min/max), so a null there is empty text, as the + * vector kernel reads a null element; a null literal operand nulls the row. */ +static ray_t* concat_text_values(ray_t** args, int n_args, bool str_out, const uint8_t* cells) { + /* Only atoms broadcast. A one-row vector is still a vector, and an + * empty vector must never be indexed as if it contained row zero. */ int64_t nrows = 1; - bool out_str = false; + bool out_str = str_out, has_vector = false; for (int a = 0; a < n_args; a++) { - int8_t at = args[a]->type; - if (at == RAY_STR) { out_str = true; if (nrows == 1) nrows = args[a]->len; } - if (RAY_IS_SYM(at)) { if (nrows == 1) nrows = args[a]->len; } - if (!ray_is_atom(args[a]) && nrows == 1) { nrows = args[a]->len; } + if (args[a]->type == RAY_STR) out_str = true; + if (ray_is_atom(args[a])) continue; + if (has_vector && args[a]->len != nrows) { + for (int i = 0; i < n_args; i++) ray_release(args[i]); + return ray_error("length", "concat: text columns must have equal lengths"); + } + nrows = args[a]->len; + has_vector = true; } ray_t* result = ray_vec_new(out_str ? RAY_STR : RAY_SYM, nrows); if (!result || RAY_IS_ERR(result)) { for (int i = 0; i < n_args; i++) ray_release(args[i]); - scratch_free(args_hdr); return result; } if (!out_str) result->len = nrows; @@ -1461,8 +1439,9 @@ ray_t* exec_concat(ray_graph_t* g, ray_op_t* op) { /* Check if any arg is null at this row */ bool any_null = false; for (int a = 0; a < n_args; a++) { - /* SYM atoms can be null (sym 0); STR/SYM vecs cannot. */ - if (ray_is_atom(args[a]) && RAY_ATOM_IS_NULL(args[a])) { any_null = true; break; } + /* SYM atoms can be null (sym 0); STR/SYM vecs cannot. A null + * cell (cells[a]) reads as empty text below. */ + if (!(cells && cells[a]) && ray_is_atom(args[a]) && RAY_ATOM_IS_NULL(args[a])) { any_null = true; break; } } if (any_null) { if (out_str) { @@ -1482,11 +1461,11 @@ ray_t* exec_concat(ray_graph_t* g, ray_op_t* op) { if (t == RAY_STR) { const ray_str_t* elems; const char* p; str_resolve(args[a], &elems, &p); - int64_t ar = ray_is_atom(args[a]) ? 0 : (r < args[a]->len ? r : 0); + int64_t ar = r; total += elems[ar].len; } else if (RAY_IS_SYM(t)) { const char* sp; size_t sl; - int64_t ar = ray_is_atom(args[a]) ? 0 : (r < args[a]->len ? r : 0); + int64_t ar = r; sym_elem(args[a], ar, &sp, &sl); total += sl; } else if (t == -RAY_STR) { @@ -1508,7 +1487,6 @@ ray_t* exec_concat(ray_graph_t* g, ray_op_t* op) { if (!buf) { ray_release(result); for (int i = 0; i < n_args; i++) ray_release(args[i]); - scratch_free(args_hdr); return ray_error("oom", NULL); } buf_cap = total + 1; @@ -1519,13 +1497,13 @@ ray_t* exec_concat(ray_graph_t* g, ray_op_t* op) { if (t == RAY_STR) { const ray_str_t* elems; const char* pool; str_resolve(args[a], &elems, &pool); - int64_t ar = ray_is_atom(args[a]) ? 0 : (r < args[a]->len ? r : 0); + int64_t ar = r; const char* sp = ray_str_t_ptr(&elems[ar], pool); size_t sl = elems[ar].len; if (bi + sl < buf_cap) { memcpy(buf + bi, sp, sl); bi += sl; } } else if (RAY_IS_SYM(t)) { const char* sp; size_t sl; - int64_t ar = ray_is_atom(args[a]) ? 0 : (r < args[a]->len ? r : 0); + int64_t ar = r; sym_elem(args[a], ar, &sp, &sl); if (bi + sl < buf_cap) { memcpy(buf + bi, sp, sl); bi += sl; } } else if (t == -RAY_STR) { @@ -1550,6 +1528,114 @@ ray_t* exec_concat(ray_graph_t* g, ray_op_t* op) { scratch_free(dyn_hdr); } for (int i = 0; i < n_args; i++) ray_release(args[i]); + return result; +} + +/* CONCAT(a, b, ...) */ +ray_t* exec_concat(ray_graph_t* g, ray_op_t* op) { + ray_op_ext_t* ext = find_ext(g, op->id); + if (!ext) return ray_error("nyi", NULL); + int64_t raw_nargs = ext->sym; + if (raw_nargs < 2 || raw_nargs > 255) return ray_error("arity", "concat: expected 2 to 255 arguments, got %lld", (long long)raw_nargs); + int n_args = (int)raw_nargs; + + /* Evaluate all inputs */ + ray_t* args_stack[16]; + ray_t** args = args_stack; + ray_t* args_hdr = NULL; + if (n_args > 16) { + args = (ray_t**)scratch_calloc(&args_hdr, (size_t)n_args * sizeof(ray_t*)); + if (!args) return ray_error("oom", NULL); + } + + args[0] = exec_node(g, op_child(g, op, 0)); + args[1] = exec_node(g, op_child(g, op, 1)); + uint32_t* trail = (uint32_t*)((char*)(ext + 1)); + for (int i = 2; i < n_args; i++) { + args[i] = exec_node(g, &g->nodes[trail[i - 2]]); + } + /* Error check */ + for (int i = 0; i < n_args; i++) { + if (!args[i] || RAY_IS_ERR(args[i])) { + ray_t* err = args[i]; + for (int j = 0; j < n_args; j++) { + if (j != i && args[j] && !RAY_IS_ERR(args[j])) ray_release(args[j]); + } + scratch_free(args_hdr); + return err; + } + } + + /* An operand that reduces a text column to one value (first, last, min, + * max) is a cell of the rows: a null there is empty text, and a cell of + * a STR column makes the result STR, as a STR column itself does. One + * flag per operand, at every position (up to 255 of them). */ + uint8_t cells[256] = { 0 }; + bool str_out = false; + for (int i = 0; i < n_args; i++) { + ray_op_t* child = i < 2 ? op_child(g, op, i) : &g->nodes[trail[i - 2]]; + if (child && (child->opcode == OP_FIRST || child->opcode == OP_LAST || + child->opcode == OP_MIN || child->opcode == OP_MAX)) { + cells[i] = 1; + if (child->out_type == RAY_STR) str_out = true; + } + } + ray_t* result = concat_text_values(args, n_args, str_out, cells); scratch_free(args_hdr); return result; } + +/* Query fallback uses the same text kernel after checking argument syntax. + * Ordinary builtin calls retain collection semantics. */ +ray_t* ray_concat_text_fn(ray_t* a, ray_t* b, bool str_out, uint8_t rows_mask) { + bool atoms = ray_is_atom(a) && ray_is_atom(b); + /* A null cell of a column is empty text, as the vector kernel reads a + * null element; a null literal operand follows the kernel's null rule. */ + bool a_null = RAY_ATOM_IS_NULL(a), b_null = RAY_ATOM_IS_NULL(b); + /* Two STR literals join as strings, as the planner folds them; a STR + * cell beside a null literal follows the kernel's null rule. */ + if (a->type == -RAY_STR && b->type == -RAY_STR && (rows_mask == 0 || (!a_null && !b_null))) + return ray_concat_fn(a, b); + if (atoms && (a->type == -RAY_SYM || a->type == -RAY_STR) && + (b->type == -RAY_SYM || b->type == -RAY_STR) && + (!a_null || (rows_mask & 1)) && (!b_null || (rows_mask & 2))) { + /* Two cells, the row-by-row case: build the atom directly rather + * than a one-row vector that is unpacked again. */ + ray_t* sa = a->type == -RAY_SYM && !a_null ? ray_sym_str(a->i64) : NULL; + ray_t* sb = b->type == -RAY_SYM && !b_null ? ray_sym_str(b->i64) : NULL; + if ((a->type == -RAY_SYM && !a_null && !sa) || (b->type == -RAY_SYM && !b_null && !sb)) { + if (sa) ray_release(sa); + if (sb) ray_release(sb); + return ray_error("oom", NULL); + } + const char* pa = a_null ? "" : sa ? ray_str_ptr(sa) : ray_str_ptr(a); + const char* pb = b_null ? "" : sb ? ray_str_ptr(sb) : ray_str_ptr(b); + size_t la = a_null ? 0 : sa ? ray_str_len(sa) : ray_str_len(a); + size_t lb = b_null ? 0 : sb ? ray_str_len(sb) : ray_str_len(b); + char small[256]; + ray_t* hdr = NULL; + char* buf = la + lb <= sizeof small ? small : (char*)scratch_calloc(&hdr, la + lb + 1); + ray_t* out; + if (!buf) out = ray_error("oom", NULL); + else { + memcpy(buf, pa, la); + memcpy(buf + la, pb, lb); + out = str_out ? ray_str(buf, la + lb) : ray_sym(ray_sym_intern(buf, la + lb)); + } + if (hdr) scratch_free(hdr); + if (sa) ray_release(sa); + if (sb) ray_release(sb); + return out; + } + ray_t* args[2] = { a, b }; + uint8_t cells[2] = { (uint8_t)(rows_mask & 1), (uint8_t)((rows_mask >> 1) & 1) }; + ray_retain(a); + ray_retain(b); + ray_t* result = concat_text_values(args, 2, str_out, cells); + if (!atoms || !result || RAY_IS_ERR(result)) return result; + int allocated = 0; + ray_t* atom = collection_elem(result, 0, &allocated); + if (atom && !allocated) ray_retain(atom); + ray_release(result); + return atom; +} diff --git a/src/ops/symcmp.c b/src/ops/symcmp.c new file mode 100644 index 000000000..88f90c35d --- /dev/null +++ b/src/ops/symcmp.c @@ -0,0 +1,281 @@ +/* + * 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. + */ + +/* Ordered symbol predicates. Scratch follows the ids used by this scan, + * never the process-wide vocabulary. Each worker owns its maps and ranks. */ +#include "ops/internal.h" +#include "ops/hash.h" +#include "table/domain.h" +#include "table/sym.h" +#include +#include + +typedef struct { int64_t id, value; } sym_order_slot_t; +typedef struct { + int64_t base; + int64_t* dense; + sym_order_slot_t* slots; + size_t cap, used; +} sym_order_map_t; + +static void sym_order_map_free(sym_order_map_t* m) { + ray_free_raw(m->dense); + ray_free_raw(m->slots); +} + +static bool sym_order_map_grow(sym_order_map_t* m) { + size_t cap = m->cap ? m->cap * 2 : 16; + if (cap < m->cap || cap > SIZE_MAX / sizeof(sym_order_slot_t)) return false; + sym_order_slot_t* slots = ray_calloc_raw(cap * sizeof(*slots)); + if (!slots) return false; + for (size_t i = 0; i < m->cap; i++) { + if (!m->slots[i].value) continue; + size_t h = ray_hash_i64(m->slots[i].id) & (cap - 1); + while (slots[h].value) h = (h + 1) & (cap - 1); + slots[h] = m->slots[i]; + } + ray_free_raw(m->slots); + m->slots = slots; m->cap = cap; + return true; +} + +/* A zero value denotes an unseen id. Callers immediately fill new slots. + * Dense storage is bounded by both the rows and a small absolute budget; + * widely separated ids use a growing hash map, even in a huge domain. */ +static int64_t* sym_order_slot(sym_order_map_t* m, int64_t id) { + if (m->dense) return &m->dense[id - m->base]; + size_t h = ray_hash_i64(id) & (m->cap - 1); + while (m->slots[h].value) { + if (m->slots[h].id == id) return &m->slots[h].value; + h = (h + 1) & (m->cap - 1); + } + if (m->used >= m->cap / 2) { + if (!sym_order_map_grow(m)) return NULL; + h = ray_hash_i64(id) & (m->cap - 1); + while (m->slots[h].value) h = (h + 1) & (m->cap - 1); + } + m->slots[h].id = id; + m->used++; + return &m->slots[h].value; +} + +static bool sym_order_map_init(sym_order_map_t* m, ray_t* v, + int64_t start, int64_t end) { + const void* data = ray_data(v); + int64_t lo = INT64_MAX, hi = 0; +#define SYM_BOUNDS(T) do { \ + const T* p = data; \ + for (int64_t i = start; i < end; i++) { \ + int64_t id = p[i]; \ + if (id < lo) lo = id; \ + if (id > hi) hi = id; \ + } \ +} while (0) + switch (v->attrs & RAY_SYM_W_MASK) { + case RAY_SYM_W8: SYM_BOUNDS(uint8_t); break; + case RAY_SYM_W16: SYM_BOUNDS(uint16_t); break; + case RAY_SYM_W32: SYM_BOUNDS(uint32_t); break; + default: SYM_BOUNDS(int64_t); break; + } +#undef SYM_BOUNDS + uint64_t span = (uint64_t)hi - (uint64_t)lo + 1; + if (span <= 65536 && span <= (uint64_t)(end - start) * 4 + 32) { + m->dense = ray_calloc_raw((size_t)span * sizeof(int64_t)); + m->base = lo; + return m->dense != NULL; + } + return sym_order_map_grow(m); +} + +static int sym_order_bytes(const char* a, size_t al, const char* b, size_t bl) { + size_t n = al < bl ? al : bl; + int c = n ? memcmp(a, b, n) : 0; + return c ? c : (al > bl) - (al < bl); +} + +static bool sym_order_apply(uint16_t op, int c) { + switch (op) { + case OP_LT: return c < 0; + case OP_LE: return c <= 0; + case OP_GT: return c > 0; + default: return c >= 0; + } +} + +typedef struct { + const char* bytes; + size_t len; + int64_t id; + int side; +} sym_order_entry_t; + +static int sym_order_entry_cmp(const void* a, const void* b) { + const sym_order_entry_t* l = a; + const sym_order_entry_t* r = b; + return sym_order_bytes(l->bytes, l->len, r->bytes, r->len); +} + +typedef struct { + ray_t* left; + ray_t* right; /* NULL for column/literal */ + const char* literal; + size_t literal_len; + bool reverse; + uint16_t opcode; + int64_t nrows; + uint32_t ntasks; + bool* out; + int failed; +} sym_order_ctx_t; + +static void sym_order_task(void* raw, uint32_t wid, int64_t task, int64_t task_end) { + (void)wid; (void)task_end; + sym_order_ctx_t* c = raw; + /* dispatch_n gives one contiguous range to each task. Rank setup is + * once per task, not once per morsel, and needs no shared mutable cache. */ + int64_t chunk = c->nrows / c->ntasks; + int64_t start = task * chunk; + int64_t end = task + 1 == c->ntasks ? c->nrows : start + chunk; + sym_order_map_t maps[2] = {{0}, {0}}; + sym_order_entry_t* entries = NULL; + size_t used = 0, cap = 0; + ray_t* cols[] = {c->left, c->right}; + if (!sym_order_map_init(&maps[0], cols[0], start, end)) goto oom; + if (!c->right) { + ray_sym_domain_t* dom = ray_sym_vec_domain(c->left); + const void* data = ray_data(c->left); + for (int64_t i = start; i < end; i++) { + int64_t id = ray_read_sym(data, i, RAY_SYM, c->left->attrs); + int64_t* verdict = sym_order_slot(&maps[0], id); + if (!verdict) goto oom; + if (!*verdict) { + ray_t* s = ray_sym_domain_str(dom, id); + if (!s) goto oom; + int cmp = sym_order_bytes(ray_str_ptr(s), ray_str_len(s), + c->literal, c->literal_len); + if (c->reverse) cmp = -((cmp > 0) - (cmp < 0)); + *verdict = 1 + sym_order_apply(c->opcode, cmp); + } + c->out[i] = *verdict == 2; + } + } else { + if (!sym_order_map_init(&maps[1], cols[1], start, end)) goto oom; + /* Collect distinct ids present in these rows. An unrelated symbol + * is never resolved or sorted. Cross-domain equal strings receive + * the same rank when the two used vocabularies are sorted together. */ + for (int side = 0; side < 2; side++) { + ray_t* v = cols[side]; + const void* data = ray_data(v); + ray_sym_domain_t* dom = ray_sym_vec_domain(v); + for (int64_t i = start; i < end; i++) { + int64_t id = ray_read_sym(data, i, RAY_SYM, v->attrs); + int64_t* seen = sym_order_slot(&maps[side], id); + if (!seen) goto oom; + if (*seen) continue; + if (used == cap) { + size_t next = cap ? cap * 2 : 16; + if (next < cap || next > SIZE_MAX / sizeof(*entries)) goto oom; + void* p = ray_realloc_raw(entries, next * sizeof(*entries)); + if (!p) goto oom; + entries = p; cap = next; + } + ray_t* s = ray_sym_domain_str(dom, id); + if (!s) goto oom; + entries[used++] = (sym_order_entry_t){ray_str_ptr(s), ray_str_len(s), id, side}; + *seen = 1; + } + } + qsort(entries, used, sizeof(*entries), sym_order_entry_cmp); + int64_t rank = 1; + for (size_t j = 0; j < used; j++) { + if (j && sym_order_entry_cmp(&entries[j - 1], &entries[j])) rank++; + *sym_order_slot(&maps[entries[j].side], entries[j].id) = rank; + } + const void* ld = ray_data(c->left); + const void* rd = ray_data(c->right); + for (int64_t i = start; i < end; i++) { + int64_t l = *sym_order_slot(&maps[0], ray_read_sym(ld, i, RAY_SYM, c->left->attrs)); + int64_t r = *sym_order_slot(&maps[1], ray_read_sym(rd, i, RAY_SYM, c->right->attrs)); + c->out[i] = sym_order_apply(c->opcode, (l > r) - (l < r)); + } + } + goto done; +oom: + __atomic_store_n(&c->failed, 1, __ATOMIC_RELAXED); +done: + ray_free_raw(entries); + sym_order_map_free(&maps[0]); sym_order_map_free(&maps[1]); +} + +/* Borrow scalar bytes in their original domain. No interning, including + * length-one FILE-domain vectors used as query scalar broadcasts. */ +static bool sym_order_scalar(ray_t* v, const char** bytes, size_t* len) { + ray_t* s = v; + if (v->type == -RAY_SYM) s = ray_sym_str(v->i64); + else if (v->type == RAY_SYM) s = ray_sym_vec_cell(v, 0); + else if (v->type == RAY_STR) { + *bytes = ray_str_vec_get(v, 0, len); + return true; + } + if (!s) return false; + *bytes = ray_str_ptr(s); *len = ray_str_len(s); + return true; +} + +ray_t* exec_sym_order(uint16_t opcode, ray_t* lhs, ray_t* rhs, + bool l_scalar, bool r_scalar) { + if ((!l_scalar && lhs->type != RAY_SYM) || + (!r_scalar && rhs->type != RAY_SYM)) + return ray_error("type", "symbol ordering requires symbol columns or string/symbol scalars"); + int64_t n = !l_scalar ? lhs->len : !r_scalar ? rhs->len : 1; + ray_t* out = ray_vec_new(RAY_BOOL, n); + if (!out || RAY_IS_ERR(out)) return out; + out->len = n; + if (!n) return out; + sym_order_ctx_t c = {.opcode = opcode, .nrows = n, .ntasks = 1, .out = ray_data(out)}; + if (l_scalar && r_scalar) { + const char *l, *r; size_t ll, rl; + if (!sym_order_scalar(lhs, &l, &ll) || !sym_order_scalar(rhs, &r, &rl)) { + ray_release(out); + return ray_error("oom", "symbol ordering scalar"); + } + c.out[0] = sym_order_apply(opcode, sym_order_bytes(l, ll, r, rl)); + return out; + } + c.left = l_scalar ? rhs : lhs; + if (l_scalar || r_scalar) { + c.reverse = l_scalar; + if (!sym_order_scalar(l_scalar ? lhs : rhs, &c.literal, &c.literal_len)) { + ray_release(out); + return ray_error("oom", "symbol ordering scalar"); + } + } else c.right = rhs; + ray_pool_t* pool = ray_pool_get(); + if (pool && n >= RAY_PARALLEL_THRESHOLD) { + c.ntasks = ray_pool_total_workers(pool); + if (c.ntasks > (uint64_t)n) c.ntasks = (uint32_t)n; + ray_pool_dispatch_n(pool, sym_order_task, &c, c.ntasks); + } else sym_order_task(&c, 0, 0, 1); + if (c.failed) { ray_release(out); return ray_error("oom", "symbol ordering scratch"); } + return out; +} diff --git a/src/ops/system.c b/src/ops/system.c index 720146b31..46e35fb73 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -37,6 +37,7 @@ #include "core/block.h" #include "ops/idxop.h" #include "core/profile.h" /* g_ray_profile — (.sys.prof) */ +#include "core/runtime.h" /* __VM — (return x) parks its value on the VM */ #include "core/qmeasure.h" /* shared per-query measurement lifecycle */ #include "core/qlog.h" /* g_qlog — (.sys.querylog) */ #include "store/serde.h" @@ -651,7 +652,7 @@ static bool objsize_seen_insert(ray_objsize_walk_t* w, ray_t* p, bool* ok) { static size_t objsize_shallow(ray_t* v) { if (v->attrs & RAY_ATTR_SLICE) return sizeof(ray_t); if (v->type == RAY_LAMBDA) - return sizeof(ray_t) + 7 * sizeof(ray_t*); + return sizeof(ray_t) + LAMBDA_SLOTS * sizeof(ray_t*); if (v->type == RAY_INDEX) return sizeof(ray_t) + sizeof(ray_index_t); if (RAY_IS_PARTED(v->type)) @@ -697,8 +698,10 @@ static bool objsize_push_children(ray_objsize_walk_t* w, ray_t* v) { if (v->type == RAY_LAMBDA) { ray_t** slots = (ray_t**)ray_data(v); for (int i = 0; i < 4; i++) OBJSIZE_PUSH(slots[i]); - OBJSIZE_PUSH(slots[5]); - OBJSIZE_PUSH(slots[6]); + OBJSIZE_PUSH(LAMBDA_NFO(v)); + OBJSIZE_PUSH(LAMBDA_DBG(v)); + OBJSIZE_PUSH(LAMBDA_CLOSURE(v)); + OBJSIZE_PUSH(LAMBDA_CAPROWS(v)); return true; } if (ray_is_atom(v)) { @@ -872,8 +875,10 @@ ray_t* ray_gc_fn(ray_t** args, int64_t n) { (void)args; if (n != 0) return ray_error("arity", ".sys.gc takes no arguments"); ray_heap_gc(); - /* Same statement-boundary rule as the REPL: an explicit maintenance - * call is also a chance to notice the process has gone quiet. */ + /* Same statement-boundary rules as the REPL: under memory pressure what + * is free goes back now, and an explicit maintenance call is also a + * chance to notice the process has gone quiet. */ + ray_heap_relieve(); ray_heap_decay(); return ray_i64(0); } @@ -1104,15 +1109,21 @@ ray_t* ray_quote_fn(ray_t** args, int64_t n) { return a; } -/* (return) | (return x) — early exit from enclosing compiled lambda. - * Outside a compiled lambda (e.g. value position: (map return xs), or - * REPL top-level) this collapses to: identity for one arg, null for - * zero, domain error otherwise. The early-exit semantics are emitted - * by the bytecode compiler — see compile.c. */ +/* (return) | (return x) — early exit from the enclosing lambda. The + * bytecode compiler emits the exit itself (see compile.c); this is the + * tree walker's form. Inside a lambda it parks the value on the VM and + * returns the `return` marker, an error-typed value every form propagates + * and the lambda call boundary turns back into the value (`try` lets it + * through). Outside any lambda (REPL top level) it is the identity: the + * value, or null for no arg. */ ray_t* ray_return_fn(ray_t** args, int64_t n) { - if (n == 0) return RAY_NULL_OBJ; - if (n == 1) { ray_retain(args[0]); return args[0]; } - return ray_error("domain", "return expects 0 or 1 argument"); + if (n > 1) return ray_error("domain", "return expects 0 or 1 argument"); + ray_t* val = n == 1 ? args[0] : RAY_NULL_OBJ; + ray_retain(val); + if (!__VM || __VM->lambda_depth == 0) return val; + if (__VM->return_val) ray_release(__VM->return_val); + __VM->return_val = val; + return ray_error("return", NULL); } /* (rc x) -- return reference count of object */ diff --git a/src/store/col.c b/src/store/col.c index 4763ef6b2..ebdd8d286 100644 --- a/src/store/col.c +++ b/src/store/col.c @@ -29,6 +29,7 @@ #include "col.h" #include "core/platform.h" +#include "core/pool.h" /* ray_pool_want — large scattered-row requests */ #include "mem/heap.h" #include "mem/sys.h" /* ray_sys_alloc — the shared-mapping descriptor */ #include "store/serde.h" @@ -48,6 +49,12 @@ #else #include #endif +#if defined(RAY_OS_LINUX) +#include /* fallocate: the in-place hash region */ +#include +#include +#include /* fstatfs: the filesystems it is built in place on */ +#endif /* -------------------------------------------------------------------------- * validate_sym_bounds -- check all indices in a RAY_SYM column are < sym_count @@ -528,6 +535,13 @@ static ray_t* col_read_recursive(const uint8_t** pp, size_t* remaining) { *pp += data_size; *remaining -= data_size; if (type == RAY_STR) { + /* The nested format carries no hash mark, and files from before + * the hash cache hold padding in the descriptor's last four + * bytes. Drop whatever was copied: a zero hash32 is the lazy + * state every consumer computes from (ray_str_t_hash32). */ + ray_str_t* elems = (ray_str_t*)ray_data(vec); + for (int64_t i = 0; i < len; i++) + if (!ray_str_is_inline(&elems[i])) elems[i].hash32 = 0; if (*remaining < 8) { ray_release(vec); return ray_error("corrupt", NULL); } uint64_t pool_size; memcpy(&pool_size, *pp, 8); @@ -766,6 +780,148 @@ ray_err_t ray_col_append_index(const char* path, const void* ix_v, return err; } +#if defined(RAY_OS_LINUX) +/* Debug builds: RAY_HASH_INJECT names a step of the in-place build to fail + * there, for the tests — "fs": the filesystem is not one it trusts; + * "fs:": the filesystem's type is taken to be (a magic number + * as fstatfs reports it), so filesystems the tests cannot mount are + * classified too; "grow", "map": the region cannot be allocated, or + * mapped; "build": an interrupt as soon as it is mapped; "premarker": the + * process ends with the region written, before the marker. */ +static bool col_hash_inject(const char* step) { +#if defined(DEBUG) + const char* e = getenv("RAY_HASH_INJECT"); + return e && strcmp(e, step) == 0; +#else + (void)step; + return false; +#endif +} +static bool col_hash_inject_fs_type(unsigned long* type) { +#if defined(DEBUG) + const char* e = getenv("RAY_HASH_INJECT"); + if (!e || strncmp(e, "fs:", 3) != 0) return false; + char* end = NULL; + unsigned long t = strtoul(e + 3, &end, 16); + if (end == e + 3 || *end) return false; + *type = t; + return true; +#else + (void)type; + return false; +#endif +} + +/* Writing the region through a shared mapping is safe only where the + * blocks it lands on are held before the first write: a write fault that + * needs a block on a full disk is a SIGBUS, and a writeback that fails is + * lost without a word (the fwrite append gets ENOSPC instead). So the + * filesystems whose fallocate reserves what the writes use — not + * copy-on-write ones (ZFS, btrfs, bcachefs: an overwrite takes new space), + * nor network or user ones (NFS, SMB, Ceph, FUSE: the server decides). + * Nor overlayfs: it hands the mapping and the fallocate to its upper layer, + * which can be any of those, and fstatfs reports the overlay — its upper + * directory, named in the mount options, is often not even reachable from + * where the overlay is used (a container). */ +static bool col_fs_reserves(int fd) { + if (col_hash_inject("fs")) return false; + unsigned long type = 0; + if (!col_hash_inject_fs_type(&type)) { + struct statfs sf; + if (fstatfs(fd, &sf) != 0) return false; + type = (unsigned long)sf.f_type; + } + switch (type) { + case 0xEF53UL: /* ext4 (an ext2/3 one has no fallocate: refused there) */ + case 0x58465342UL: /* xfs */ + case 0x01021994UL: /* tmpfs */ + return true; + default: + return false; + } +} + +/* A column file's index region, mapped writable for a build in place. */ +typedef struct { + int fd; + int64_t payload_end; /* the file's length before: the column payload */ + int64_t region_off; /* where the region starts: the payload, 32-aligned */ + uint8_t* map; /* the mapping, from the page holding region_off */ + size_t map_len; + bool refused; /* the region could not be allocated or mapped */ +} col_region_t; + +/* ray_index_region_fn: `bytes` of region at region_off, zero-filled, its + * blocks allocated first — a full disk fails here, not as a fault on a write + * through the mapping. NULL (refused) when either cannot be done. */ +static uint8_t* col_region_map(void* raw, int64_t bytes) { + col_region_t* r = (col_region_t*)raw; + if (r->map || bytes <= 0) return NULL; + int64_t end = r->region_off + bytes; + if (col_hash_inject("grow") || + fallocate(r->fd, 0, (off_t)r->payload_end, (off_t)(end - r->payload_end)) != 0) { + r->refused = true; + return NULL; + } + long ps = sysconf(_SC_PAGESIZE); + int64_t pg = ps > 0 ? (int64_t)ps : 4096; + int64_t moff = r->region_off & ~(pg - 1); + void* p = col_hash_inject("map") ? MAP_FAILED + : mmap(NULL, (size_t)(end - moff), PROT_READ | PROT_WRITE, MAP_SHARED, + r->fd, (off_t)moff); + if (p == MAP_FAILED) { r->refused = true; return NULL; } + r->map = (uint8_t*)p; + r->map_len = (size_t)(end - moff); + if (col_hash_inject("build")) ray_request_interrupt(); + return r->map + (r->region_off - moff); +} +#endif + +ray_err_t ray_col_build_hash_index(const char* path, ray_t* col, void* trace) { +#if !defined(RAY_OS_LINUX) + /* Elsewhere the blocks a mapped write lands on cannot be held up front + * (macOS: APFS is copy-on-write) — the caller builds in memory. */ + (void)path; (void)col; (void)trace; + return RAY_ERR_NYI; +#else + if (!path || !col || RAY_IS_ERR(col)) return RAY_ERR_DOMAIN; + if (col->type == RAY_STR) return RAY_ERR_NYI; + ray_hash_trace_t* tr = (ray_hash_trace_t*)trace; + int fd = open(path, O_RDWR | O_CLOEXEC); + if (fd < 0) return RAY_ERR_IO; + uint32_t mg = 0; + struct stat st; + if (pread(fd, &mg, 4, 0) != 4 || fstat(fd, &st) != 0 || st.st_size < 32) { + close(fd); + return RAY_ERR_IO; + } + if (mg == COL_IDX_AUX_MAGIC) { close(fd); return RAY_ERR_CORRUPT; } /* indexed already */ + if (!col_fs_reserves(fd)) { close(fd); return RAY_ERR_NYI; } + col_region_t r = { .fd = fd, .payload_end = (int64_t)st.st_size, + .region_off = ((int64_t)st.st_size + 31) & ~(int64_t)31 }; + ray_err_t err = ray_index_hash_build_region(col, col_region_map, &r, tr); + ray_hash_mark_t tm = tr ? ray_hash_trace_mark() : (ray_hash_mark_t){0}; + /* the pages stay in the page cache, dirty: the writeback is the kernel's */ + if (r.map) munmap(r.map, r.map_len); + if (err == RAY_OK) { + if (col_hash_inject("premarker")) _exit(86); + /* the region is in the file before the marker claims it */ + mg = COL_IDX_AUX_MAGIC; + if (pwrite(fd, &mg, 4, 0) != 4) err = RAY_ERR_IO; + } + /* Without the marker the loader requires the exact payload length. + * Best effort, as in ray_col_append_index. */ + if (err != RAY_OK) (void)!ftruncate(fd, (off_t)r.payload_end); + /* A region that could not be allocated or mapped is no reason to go + * without the index: the caller builds it in memory and appends it, + * where a full disk is an ENOSPC like any other write. */ + if (err == RAY_ERR_IO && r.refused) err = RAY_ERR_NYI; + if (close(fd) != 0 && err == RAY_OK) err = RAY_ERR_IO; + if (tr) ray_hash_trace_add(tr, RAY_HXT_APPEND, tm, 0); + return err; +#endif +} + /* Does the payload hold the type's null sentinel anywhere? Sequential * read with an early return on the first hit; resolves a slice through * its parent like every other reader. Types without a sentinel (BOOL, @@ -898,6 +1054,9 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { /* For RAY_SYM: store sym count in rc field (always 0 on disk otherwise). * This serves as O(1) fast-reject metadata on load. */ header.rc = (vec->type == RAY_SYM) ? ray_sym_count() : 0; + /* STR: every pooled descriptor goes to disk with its content hash + * (filled in below), and the header says so (col.h). */ + if (vec->type == RAY_STR) ray_col_stamp_str_hashed(&header); /* HAS_INDEX rebase: an attached accelerator index displaces the * 16-byte aux union with an index pointer. Strip HAS_INDEX from the @@ -997,7 +1156,40 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { data = ray_data(vec); } - if (data_size > 0) { + if (data_size > 0 && vec->type == RAY_STR) { + /* Pooled descriptors are written with their content hash filled + * in (RAY_COL_STR_HASHED). They are staged through a bounded + * buffer: the source may be a mapped or shared column, and a + * save must not write into it. A hash the column already + * caches is reused; a missing one (lazy, 0) is computed here. */ + const ray_str_t* src = (const ray_str_t*)data; + ray_t* pool_owner = (vec->attrs & RAY_ATTR_SLICE) ? vec->slice_parent : vec; + const char* pool_base = NULL; + size_t pool_len = 0; + if (pool_owner->str_pool && !RAY_IS_ERR(pool_owner->str_pool) && + pool_owner->str_pool->len > 0) { + pool_base = (const char*)ray_data(pool_owner->str_pool); + pool_len = (size_t)pool_owner->str_pool->len; + } + ray_str_t buf[1024]; + for (int64_t off = 0; off < vec->len; ) { + int64_t cnt = vec->len - off < 1024 ? vec->len - off : 1024; + memcpy(buf, src + off, (size_t)cnt * sizeof(ray_str_t)); + for (int64_t i = 0; i < cnt; i++) { + if (ray_str_is_inline(&buf[i])) continue; + if (!pool_base || buf[i].pool_off > pool_len || + buf[i].len > pool_len - buf[i].pool_off) { + fclose(f); remove(tmp_path); return RAY_ERR_CORRUPT; + } + buf[i].hash32 = ray_str_t_hash32(&buf[i], pool_base); + } + written = fwrite(buf, 1, (size_t)cnt * sizeof(ray_str_t), f); + if (written != (size_t)cnt * sizeof(ray_str_t)) { + fclose(f); remove(tmp_path); return RAY_ERR_IO; + } + off += cnt; + } + } else if (data_size > 0) { written = fwrite(data, 1, data_size, f); if (written != data_size) { fclose(f); remove(tmp_path); ray_free_raw(sym_xlate); return RAY_ERR_IO; } } @@ -1337,7 +1529,12 @@ static ray_err_t col_validate_str_region(ray_t* hdr, const void* ptr, } } - /* Pre-hash-cache column files persisted the descriptor's final four + /* A current writer stores every pooled descriptor's content hash and + * marks the header (RAY_COL_STR_HASHED, col.h): those descriptors are + * taken as written, so mapping the column reads no string bytes and + * dirties no descriptor page. + * + * Pre-hash-cache column files persisted the descriptor's final four * bytes as uninitialized padding. A nonzero legacy value must never be * trusted as a content hash: equal strings could otherwise probe * different join/group slots and silently produce wrong results. @@ -1345,11 +1542,19 @@ static ray_err_t col_validate_str_region(ray_t* hdr, const void* ptr, * ray_vm_map_file is MAP_PRIVATE / copy-on-write, so refreshing the * validated descriptors repairs both callers: ray_col_load copies these * values into its buddy block, while ray_col_mmap retains the private - * repaired mapping without modifying the file. */ - for (int64_t i = 0; i < hdr->len; i++) { - if (ray_str_is_inline(&elems[i])) continue; - uint32_t h = (uint32_t)ray_str_t_hash(&elems[i], pool_base); - elems[i].hash32 = h != 0 ? h : 1u; + * repaired mapping without modifying the file. Only a descriptor whose + * stored value is wrong is written, so pages that happen to be right + * stay shared with the page cache. Read rc with memcpy: file bytes are + * not atomic storage. */ + uint32_t disk_rc; + memcpy(&disk_rc, (const char*)hdr + offsetof(ray_t, rc), sizeof(disk_rc)); + if (disk_rc != RAY_COL_STR_HASHED) { + for (int64_t i = 0; i < hdr->len; i++) { + if (ray_str_is_inline(&elems[i])) continue; + uint32_t h = (uint32_t)ray_str_t_hash(&elems[i], pool_base); + h = h != 0 ? h : 1u; + if (elems[i].hash32 != h) elems[i].hash32 = h; + } } out->has_str_pool = true; @@ -1820,6 +2025,124 @@ ray_t* ray_col_mmap(const char* path) { return col_mmap_impl(path, NULL, false); } +static size_t col_fixed_esz(const ray_t* col) { + if (!col || col->mmod != 1 || col->type <= 0 || RAY_IS_PARTED(col->type) || + col->type == RAY_MAPCOMMON || col->type == RAY_LIST || col->type == RAY_STR || + col->len <= 0) return 0; + return ray_sym_elem_size(col->type, col->attrs); +} + +bool ray_col_cold(ray_t* col) { + size_t esz = col_fixed_esz(col); + return esz && !ray_vm_resident(ray_data(col), (size_t)col->len * esz); +} + +void ray_col_want_row(ray_t* col, int64_t row) { + if (!ray_pool_scan_on()) return; + size_t esz = ray_sym_elem_size(col->type, col->attrs); + ray_vm_advise_willneed((uint8_t*)ray_data(col) + (size_t)row * esz, esz); +} + +/* A run of pages to request, and the pool task that requests a range of + * such runs (col_want_runs_fn). */ +typedef struct { uintptr_t a; size_t bytes; } col_want_run_t; +typedef struct { const col_want_run_t* runs; size_t nr, per; } col_want_ctx_t; + +/* Task `start` of a dispatch_n: runs [start * per, (start + 1) * per). */ +static void col_want_runs_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; (void)end; + const col_want_ctx_t* c = raw; + size_t a = (size_t)start * c->per, b = a + c->per < c->nr ? a + c->per : c->nr; + for (size_t i = a; i < b; i++) ray_vm_advise_willneed((void*)c->runs[i].a, c->runs[i].bytes); +} + +void ray_col_want_rows(ray_t* col, const int64_t* idx, int64_t n) { + size_t esz = col_fixed_esz(col); + if (!esz || n <= 0 || !ray_pool_scan_on()) return; + const uint8_t* base = (const uint8_t*)ray_data(col); + /* A few rows: the first one's page stands for the column (one probe); + * more: a sample of the column's pages. */ + if (n <= 64 ? (idx[0] >= 0 && idx[0] < col->len && + ray_vm_resident(base + (size_t)idx[0] * esz, esz)) + : !ray_col_cold(col)) return; + size_t bytes = (size_t)col->len * esz; + /* As many rows as the column holds: about every page of it. */ + if (n >= col->len) { ray_pool_want(base, bytes); return; } + /* More than a few: mark the pages the rows fall on, then request each + * run of marked pages as one range. The rows may come in any order (a + * grouping lists one group's after another's); each page is asked for + * once, and only the pages they touch. */ + uintptr_t p0 = UINTPTR_MAX, p1 = 0; + size_t pages = 0; + uint64_t* mark = NULL; + if (n > 64) { + /* the bitmap spans the pages the rows touch, not the column */ + for (int64_t i = 0; i < n; i++) { + if (idx[i] < 0 || idx[i] >= col->len) continue; + uintptr_t pg = ((uintptr_t)base + (size_t)idx[i] * esz) >> 12; + if (pg < p0) p0 = pg; + if (pg > p1) p1 = pg; + } + if (p0 > p1) return; + pages = p1 - p0 + 1; + mark = ray_calloc_raw((pages + 63) / 64 * sizeof(uint64_t)); + } + uintptr_t last = UINTPTR_MAX; + for (int64_t i = 0; i < n; i++) { + if (idx[i] < 0 || idx[i] >= col->len) continue; + const uint8_t* p = base + (size_t)idx[i] * esz; + if (((uintptr_t)p >> 12) == last) continue; + last = (uintptr_t)p >> 12; + if (mark) mark[(last - p0) >> 6] |= UINT64_C(1) << ((last - p0) & 63); + else ray_vm_advise_willneed((void*)p, esz); + } + if (!mark) return; + /* The runs of marked pages, listed: a run starts at each page marked + * whose lower neighbour is not. */ + const size_t words = (pages + 63) / 64; + size_t n_runs = 0; + for (size_t w = 0; w < words; w++) { + uint64_t m = mark[w], below = (m << 1) | (w ? mark[w - 1] >> 63 : 0); + n_runs += (size_t)__builtin_popcountll(m & ~below); + } + col_want_run_t* runs = n_runs ? ray_alloc_raw(n_runs * sizeof *runs) : NULL; + size_t run = 0, nr = 0; + bool open = false; + for (size_t w = 0; runs && w < words; w++) { + uint64_t m = mark[w]; + if (m == (open ? ~UINT64_C(0) : 0)) continue; + for (unsigned b = 0; b < 64; b++) { + bool on = (m >> b) & 1; + if (on == open) continue; + size_t pg = w * 64 + b; + if (on) run = pg; + else runs[nr++] = (col_want_run_t){ (p0 + run) << 12, (pg - run) << 12 }; + open = on; + } + } + if (open && runs) runs[nr++] = (col_want_run_t){ (p0 + run) << 12, (pages - run) << 12 }; + ray_free_raw(mark); + if (!runs) return; + /* Many short runs — a sparse sample of a large column, a page apiece — + * are requested over the pool's threads, a task per 256 of them + * (ray_pool_dispatch_n: the plain dispatch cuts at 8,192 elements, and + * thousands of runs would stay on one task): one request costs a few + * microseconds of the kernel's, and 30,000 of them on this thread + * 100 ms. Few, or long, each through ray_pool_want, which splits a + * long range over the threads itself. */ + enum { RUNS_PER_TASK = 256 }; + ray_pool_t* pool = ray_pool_get(); + if (nr >= 2 * RUNS_PER_TASK && ray_pool_par_dispatch_ok(pool, (int64_t)nr, 2 * RUNS_PER_TASK)) { + size_t tasks = (nr + RUNS_PER_TASK - 1) / RUNS_PER_TASK; + if (tasks > RAY_POOL_INIT_TASKS) tasks = RAY_POOL_INIT_TASKS; + col_want_ctx_t ctx = { runs, nr, (nr + tasks - 1) / tasks }; + ray_pool_dispatch_n(pool, col_want_runs_fn, &ctx, (uint32_t)tasks); + } else { + for (size_t i = 0; i < nr; i++) ray_pool_want((void*)runs[i].a, runs[i].bytes); + } + ray_free_raw(runs); +} + ray_t* ray_col_mmap_splayed_dom(const char* path, struct ray_sym_domain_s* dom) { return col_mmap_impl(path, dom, true); } diff --git a/src/store/col.h b/src/store/col.h index 61b3da3ab..12c415b53 100644 --- a/src/store/col.h +++ b/src/store/col.h @@ -74,6 +74,21 @@ static inline ray_err_t ray_col_check_format(const ray_t* header) { return header->order == RAY_COL_FORMAT_MAJOR ? RAY_OK : RAY_ERR_VERSION; } +/* STR column files: a writer that stored every pooled descriptor's content + * hash (ray_str_t.hash32) says so by putting this value in the header's + * `rc` field, which is otherwise 0 on disk for STR (RAY_SYM uses it for + * the saved dictionary count). A reader that sees the mark takes the + * descriptors as written; without it (files from before the hash cache, + * whose final four descriptor bytes are padding) the loaders recompute the + * hashes and repair them in the private mapping. Mapping a marked file + * therefore costs no pass over the pool and leaves the descriptor pages + * shared with the page cache. */ +#define RAY_COL_STR_HASHED ((uint32_t)0x48534148) /* "HASH" */ + +static inline void ray_col_stamp_str_hashed(ray_t* header) { + header->rc = RAY_COL_STR_HASHED; +} + /* Column file I/O. * * The bare save/load/mmap entry points keep PROCESS-LOCAL semantics for @@ -111,6 +126,20 @@ ray_err_t ray_col_save_sym_encoded(ray_t* vec, const char* path, ray_t* ray_col_load_dom(const char* path, struct ray_sym_domain_s* dom); ray_t* ray_col_mmap_splayed_dom(const char* path, struct ray_sym_domain_s* dom); +/* Scattered reads of a mapped column. A sampler or a gather that reads + * scattered rows of a column mapped from a file and not cached waits on one + * page fault per row; asking for the rows' pages first turns that into + * about one wait. ray_col_cold: `col` is a mapped fixed-width column whose + * pages are not resident (a few page probes), so a pre-pass pays off. + * ray_col_want_row: request the page of one row (no checks). + * ray_col_want_rows: request the pages of rows idx[0..n) of a mapped + * column, skipping a column found resident: each page once and runs of + * adjacent pages as one range, whatever order the rows come in (the whole + * column for n >= its length). */ +bool ray_col_cold(ray_t* col); +void ray_col_want_row(ray_t* col, int64_t row); +void ray_col_want_rows(ray_t* col, const int64_t* idx, int64_t n); + /* Append an inline index region to an existing (index-less) column file — used * by the streaming .csv.splayed builder which writes raw columns first. `ix` * is a const ray_index_t* (void to avoid the ops/ type dependency in this @@ -118,6 +147,23 @@ 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); +/* Build the hash index of `col`, the payload of index-less column file + * `path`, and append it as the inline region, built in place: the file is + * extended (its blocks allocated) and the region mapped, and the arrays are + * written there once instead of staged in memory and copied in. Same bytes + * as ray_col_append_index of the index ray_index_attach_hash builds. The + * marker is stamped last; on failure the file is cut back to the payload. + * RAY_ERR_NYI (the file left at, or cut back to, its payload) where the + * in-place build does not apply and the caller builds in memory and appends + * instead: a STR column; a platform or filesystem where the region's blocks + * cannot be held before the mapping writes them (anything but Linux on + * ext4, xfs or tmpfs: overlayfs too, whose upper layer cannot be told); + * or a region that could not be allocated + * or mapped this time. Any other error is final (RAY_ERR_CANCEL, OOM, an + * I/O error on the marker, RAY_ERR_CORRUPT for a file already indexed). + * `trace` is a ray_hash_trace_t* (NULL: none), void as `ix` above. */ +ray_err_t ray_col_build_hash_index(const char* path, ray_t* col, void* trace); + /* 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. */ diff --git a/src/store/part.c b/src/store/part.c index 1a7109c8f..b888a8477 100644 --- a/src/store/part.c +++ b/src/store/part.c @@ -29,6 +29,7 @@ #include "part.h" #include "core/runtime.h" #include "mem/sys.h" +#include "mem/heap.h" #include "ops/ops.h" #include "store/splay.h" #include "table/sym.h" @@ -257,6 +258,287 @@ static ray_t* collect_part_dirs(const char* db_root, char*** out_dirs, return NULL; } +/* -------------------------------------------------------------------------- + * Partition reuse across mounts + * + * ray_read_parted used to open every partition of the table from scratch + * on every call. A process that follows a database another process + * appends to has to call it again to see a new or replaced partition, and + * at a few microseconds per column file an unchanged root of twenty + * thousand files cost a tenth of a second per call before any row was + * read. Loaded partition tables are therefore kept here, keyed by the + * partition's table path, and reused while the generation directory they + * were read from and every file in it are the ones on disk. + * + * Identity includes the resolved generation, device, inode, size, mtime + * and ctime of every schema/column file. Symbol columns must also use + * the domain opened for this mount (in particular, a missing .sym must + * not be hidden by reuse). + * + * Ownership is thread-local: ray_t reference counts are not atomic on + * ordinary callers. Each thread keeps at most RAY_PART_CACHE_MAX tables; + * oldest entries are evicted first. GC, symbol-domain opens and the next + * mount discard entries whose columns have no users outside the cache. + * Heap abandon/destroy releases the rest before the heap changes owner + * or is unmapped. + * -------------------------------------------------------------------------- */ + +typedef struct { + uint64_t dev; + uint64_t ino; + uint64_t size; + int64_t mtime_s; + int64_t mtime_ns; + int64_t ctime_s; + int64_t ctime_ns; +} part_file_sig_t; + +typedef struct part_cache_entry_s { + char* key; /* "//" as mounted */ + char* resolved; /* generation directory the table came from */ + ray_t* tbl; /* the loaded splayed table; one ref held here */ + part_file_sig_t* sigs; /* [0] = .d, then one per column in table order */ + int64_t nsigs; + uint64_t seq; /* the last mount that touched this entry */ + struct part_cache_entry_s* next; +} part_cache_entry_t; + +#define RAY_PART_CACHE_MAX 1024 +static RAY_TLS part_cache_entry_t* g_part_cache; +static RAY_TLS uint64_t g_part_seq; +static RAY_TLS size_t g_part_count; + +static bool part_file_sig(const char* path, part_file_sig_t* out) { + struct stat st; + if (stat(path, &st) != 0) return false; + out->dev = (uint64_t)st.st_dev; + out->ino = (uint64_t)st.st_ino; + out->size = (uint64_t)st.st_size; +#if defined(__APPLE__) + out->mtime_s = (int64_t)st.st_mtimespec.tv_sec; + out->mtime_ns = (int64_t)st.st_mtimespec.tv_nsec; + out->ctime_s = (int64_t)st.st_ctimespec.tv_sec; + out->ctime_ns = (int64_t)st.st_ctimespec.tv_nsec; +#elif defined(RAY_OS_WINDOWS) + out->mtime_s = (int64_t)st.st_mtime; + out->mtime_ns = 0; + out->ctime_s = (int64_t)st.st_ctime; + out->ctime_ns = 0; +#else + out->mtime_s = (int64_t)st.st_mtim.tv_sec; + out->mtime_ns = (int64_t)st.st_mtim.tv_nsec; + out->ctime_s = (int64_t)st.st_ctim.tv_sec; + out->ctime_ns = (int64_t)st.st_ctim.tv_nsec; +#endif + return true; +} + +static bool part_sig_eq(const part_file_sig_t* a, const part_file_sig_t* b) { + return a->dev == b->dev && a->ino == b->ino && a->size == b->size && + a->mtime_s == b->mtime_s && a->mtime_ns == b->mtime_ns && + a->ctime_s == b->ctime_s && a->ctime_ns == b->ctime_ns; +} + +/* Path of signature slot i: the schema file, then the table's columns. */ +static bool part_sig_path(const char* resolved, ray_t* tbl, int64_t i, + char* out, size_t out_sz) { + int n; + if (i == 0) { + n = snprintf(out, out_sz, "%s/.d", resolved); + } else { + ray_t* name = ray_sym_str(ray_table_col_name(tbl, i - 1)); + if (!name || RAY_IS_ERR(name)) return false; + n = snprintf(out, out_sz, "%s/%.*s", resolved, + (int)ray_str_len(name), ray_str_ptr(name)); + } + return n > 0 && (size_t)n < out_sz; +} + +static bool part_sigs_take(const char* resolved, ray_t* tbl, + part_file_sig_t* sigs, int64_t n) { + char path[1100]; + for (int64_t i = 0; i < n; i++) { + if (!part_sig_path(resolved, tbl, i, path, sizeof(path))) return false; + if (!part_file_sig(path, &sigs[i])) return false; + } + return true; +} + +/* Every file the entry was taken from is still the same file. */ +static bool part_entry_current(const part_cache_entry_t* e) { + char path[1100]; + part_file_sig_t now; + for (int64_t i = 0; i < e->nsigs; i++) { + if (!part_sig_path(e->resolved, e->tbl, i, path, sizeof(path))) return false; + if (!part_file_sig(path, &now)) return false; + if (!part_sig_eq(&now, &e->sigs[i])) return false; + } + return true; +} + +static char* part_strdup(const char* s) { + size_t n = strlen(s) + 1; + char* d = (char*)ray_sys_alloc(n); + if (d) memcpy(d, s, n); + return d; +} + +static void part_entry_free(part_cache_entry_t* e) { + if (!e) return; + if (e->tbl) ray_release(e->tbl); + ray_sys_free(e->key); + ray_sys_free(e->resolved); + ray_sys_free(e->sigs); + ray_sys_free(e); +} + +/* Describe a freshly loaded partition. NULL when it cannot be described + * (a path too long, a file already gone): the load is still returned to + * the caller, it just is not kept. */ +static part_cache_entry_t* part_entry_new(const char* key, const char* resolved, + ray_t* tbl) { + int64_t n = 1 + ray_table_ncols(tbl); + part_cache_entry_t* e = (part_cache_entry_t*)ray_sys_alloc(sizeof(*e)); + if (!e) return NULL; + memset(e, 0, sizeof(*e)); + e->key = part_strdup(key); + e->resolved = part_strdup(resolved); + e->sigs = (part_file_sig_t*)ray_sys_alloc((size_t)n * sizeof(part_file_sig_t)); + e->nsigs = n; + if (!e->key || !e->resolved || !e->sigs || + !part_sigs_take(resolved, tbl, e->sigs, n)) { + part_entry_free(e); + return NULL; + } + e->tbl = tbl; + ray_retain(tbl); + return e; +} + +/* Only the owning thread visits or releases its cached objects. */ +static void part_cache_drop(bool (*keep)(const part_cache_entry_t*, const void*), + const void* ctx) { + for (part_cache_entry_t** pp = &g_part_cache; *pp; ) { + part_cache_entry_t* e = *pp; + if (keep(e, ctx)) { pp = &e->next; continue; } + *pp = e->next; + g_part_count--; + part_entry_free(e); + } +} + +static bool part_keep_used(const part_cache_entry_t* e, const void* ctx) { + (void)ctx; + if (ray_atomic_load(&e->tbl->rc) > 1) return true; + for (int64_t i = 0; i < ray_table_ncols(e->tbl); i++) { + ray_t* col = ray_table_get_col_idx(e->tbl, i); + if (col && ray_atomic_load(&col->rc) > 1) return true; + } + return false; +} + +void ray_parted_cache_prune(void) { + part_cache_drop(part_keep_used, NULL); +} + +static bool part_domain_matches(ray_t* tbl, struct ray_sym_domain_s* dom) { + for (int64_t i = 0; i < ray_table_ncols(tbl); i++) { + ray_t* col = ray_table_get_col_idx(tbl, i); + if (col && col->type == RAY_SYM && ray_sym_vec_domain(col) != dom) + return false; + } + return true; +} + +/* Open one partition's table for mount `seq`: the kept table when the + * partition is unchanged, otherwise a fresh load that replaces whatever + * was kept for this path. Errors come back exactly as from + * ray_read_splayed_dom. */ +static ray_t* part_open(const char* path, struct ray_sym_domain_s* dom, + uint64_t seq, bool* reused) { + *reused = false; + char resolved[1024]; + if (ray_splay_resolve_dir(path, resolved, sizeof(resolved)) != RAY_OK) + return ray_read_splayed_dom(path, dom); /* the loader reports it */ + + for (part_cache_entry_t* e = g_part_cache; e; e = e->next) { + if (strcmp(e->key, path) != 0) continue; + if (strcmp(e->resolved, resolved) == 0 && + part_domain_matches(e->tbl, dom) && part_entry_current(e)) { + e->seq = seq; + ray_t* tbl = e->tbl; + ray_retain(tbl); + *reused = true; + return tbl; + } + break; /* changed: replaced below once the fresh load succeeds */ + } + + ray_t* tbl = ray_read_splayed_dom(path, dom); + if (!tbl || RAY_IS_ERR(tbl)) return tbl; + + /* Keep it only if the generation did not move during the load; the + * table and the signature must describe the same directory. */ + char now[1024]; + if (ray_splay_resolve_dir(path, now, sizeof(now)) != RAY_OK || + strcmp(now, resolved) != 0) + return tbl; + part_cache_entry_t* fresh = part_entry_new(path, resolved, tbl); + if (!fresh) return tbl; + + for (part_cache_entry_t** pp = &g_part_cache; *pp; pp = &(*pp)->next) { + if (strcmp((*pp)->key, path) == 0) { + part_cache_entry_t* old = *pp; + *pp = old->next; + g_part_count--; + part_entry_free(old); + break; + } + } + fresh->seq = seq; + fresh->next = g_part_cache; + g_part_cache = fresh; + if (++g_part_count > RAY_PART_CACHE_MAX) { + part_cache_entry_t** oldest = &g_part_cache; + for (part_cache_entry_t** pp = &g_part_cache; *pp; pp = &(*pp)->next) + if ((*pp)->seq <= (*oldest)->seq) oldest = pp; + part_cache_entry_t* dead = *oldest; + *oldest = dead->next; + g_part_count--; + part_entry_free(dead); + } + return tbl; +} + +/* After a complete mount of /: drop the entries of + * that table the mount did not touch — partitions that are gone. */ +typedef struct { const char* root; const char* table; uint64_t seq; } part_sweep_t; +static bool part_keep_touched(const part_cache_entry_t* e, const void* ctx) { + const part_sweep_t* s = (const part_sweep_t*)ctx; + size_t rl = strlen(s->root), tl = strlen(s->table), kl = strlen(e->key); + /* "//" */ + bool ours = kl > rl + tl + 2 && + strncmp(e->key, s->root, rl) == 0 && e->key[rl] == '/' && + strcmp(e->key + kl - tl, s->table) == 0 && + e->key[kl - tl - 1] == '/' && + memchr(e->key + rl + 1, '/', kl - tl - rl - 2) == NULL; + return !ours || e->seq == s->seq; +} +static void part_cache_sweep(const char* db_root, const char* table_name, + uint64_t seq) { + part_sweep_t s = { db_root, table_name, seq }; + part_cache_drop(part_keep_touched, &s); +} + +static bool part_keep_none(const part_cache_entry_t* e, const void* ctx) { + (void)e; (void)ctx; + return false; +} + +void ray_parted_cache_clear(void) { + part_cache_drop(part_keep_none, NULL); +} + /* -------------------------------------------------------------------------- * ray_read_parted — zero-copy open of a partitioned table * @@ -276,6 +558,9 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { strstr(table_name, "..") || table_name[0] == '.') return ray_error("io", NULL); + /* Release unused domains before opening a possibly rebuilt root. */ + ray_parted_cache_prune(); + /* Build sym_path. */ char sym_path[1024]; int sn = snprintf(sym_path, sizeof(sym_path), "%s/.sym", db_root); @@ -288,14 +573,17 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { * RAY_SYM columns never produce a symfile, so a missing root-level * symfile is normal — the loud "sym" error fires only if a SYM * column is actually encountered (store/col.c). */ + uint64_t seq = ++g_part_seq; struct ray_sym_domain_s* dom = NULL; struct stat sym_st; if (stat(sym_path, &sym_st) == 0) { dom = ray_sym_domain_open(sym_path); - if (!dom) + if (!dom) { + part_cache_sweep(db_root, table_name, seq); return ray_error("corrupt", "symfile %s: unreadable or invalid (bad magic, torn record, " "or missing \"\" at position 0)", sym_path); + } } /* Scan db_root for partition directories (the ".sym" dotfile is skipped); @@ -309,15 +597,16 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { fprintf(stderr, "parted.get: collect dirs failed err=%s\n", ray_err_code(collect_err)); if (dom) ray_sym_domain_release(dom); + part_cache_sweep(db_root, table_name, seq); return collect_err; } - if (trace) - fprintf(stderr, "parted.get: parts=%" PRId64 "\n", part_count); + int64_t reused_n = 0; /* No partitions: there is no named table to read. Unlike * .db.parted.tables (which lists nothing), reading data from an empty * or non-parted root is a genuine error. */ if (part_count <= 0) { + part_cache_sweep(db_root, table_name, seq); if (dom) ray_sym_domain_release(dom); return ray_error("io", "parted %s: no partition directories", db_root); } @@ -346,8 +635,11 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { } /* 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); + * appended by a concurrent publisher are visible before columns load. + * An unchanged partition comes back from the previous mount. */ + bool reused = false; + part_tables[p] = part_open(path, dom, seq, &reused); + if (reused) reused_n++; if (!part_tables[p] || RAY_IS_ERR(part_tables[p])) { if (trace) fprintf(stderr, "parted.get: splayed load failed part=%" PRId64 " path=%s err=%s\n", @@ -363,6 +655,12 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { } } + /* Every partition is open: forget the ones this root no longer has. */ + part_cache_sweep(db_root, table_name, seq); + if (trace) + fprintf(stderr, "parted.get: parts=%" PRId64 " reused=%" PRId64 "\n", + part_count, reused_n); + /* Get schema from first partition */ int64_t ncols = ray_table_ncols(part_tables[0]); if (ncols <= 0) { @@ -569,14 +867,10 @@ 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 tdir[1024], resolved[1024], dpath[1100]; + char tdir[1024]; 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 */ + if (!ray_splay_has_schema(tdir)) continue; /* not a table */ if (count >= cap) { int64_t ncap = cap == 0 ? 16 : cap * 2; char** tmp = (char**)ray_realloc_raw(names, (size_t)ncap * sizeof(char*)); @@ -612,14 +906,10 @@ 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 tdir[1024], resolved[1024], dpath[1100]; + char tdir[1024]; 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); + return ray_splay_has_schema(tdir); } /* Build a 0-row table with the same column names and types as `tmpl`. */ diff --git a/src/store/part.h b/src/store/part.h index f67558290..094f624b0 100644 --- a/src/store/part.h +++ b/src/store/part.h @@ -29,6 +29,13 @@ /* Partitioned table */ ray_t* ray_read_parted(const char* db_root, const char* table_name); +/* Release this thread's cached partitions. GC and symbol-domain opens + * prune those whose columns have no external references; heap abandon/destroy + * and runtime shutdown clear everything before the owning heap or symbol + * table goes away. */ +void ray_parted_cache_clear(void); +void ray_parted_cache_prune(void); + /* Enumerate the table names under a parted db root — the splayed-table * subdirectories (those with a `.d` schema) of the first partition. * Returns a sorted RAY_SYM vector of names suitable for ray_read_parted, diff --git a/src/store/serde.c b/src/store/serde.c index d4a58652a..bbf7bfb57 100644 --- a/src/store/serde.c +++ b/src/store/serde.c @@ -1150,16 +1150,19 @@ static ray_t* de_raw_inner(uint8_t* buf, int64_t* len) { ray_release(body); return closure; } - if (closure->type != RAY_DICT) { + ray_t* ck = closure->type == RAY_DICT ? ray_dict_keys(closure) : NULL; + ray_t* cv = closure->type == RAY_DICT ? ray_dict_vals(closure) : NULL; + if (!ck || !cv || ck->type != RAY_SYM || cv->type != RAY_LIST || ck->len != cv->len) { ray_release(params); ray_release(body); ray_release(closure); - return ray_error("type", "deserialize lambda: closure must be a dict"); + return ray_error("type", "deserialize lambda: closure must be a dict of SYM keys to a LIST of values"); } } - /* Build lambda: allocate with 8 slots (same as eval.c). */ - ray_t* lambda = ray_alloc(8 * sizeof(ray_t*)); + /* Build lambda with the layout eval.c uses; the row-provenance + * slots stay empty, they never travel. */ + ray_t* lambda = ray_alloc(LAMBDA_SLOTS * sizeof(ray_t*)); if (!lambda || RAY_IS_ERR(lambda)) { ray_release(params); ray_release(body); @@ -1169,7 +1172,7 @@ static ray_t* de_raw_inner(uint8_t* buf, int64_t* len) { lambda->type = RAY_LAMBDA; lambda->attrs = 0; lambda->len = 0; - memset(ray_data(lambda), 0, 8 * sizeof(ray_t*)); + memset(ray_data(lambda), 0, LAMBDA_SLOTS * sizeof(ray_t*)); ((ray_t**)ray_data(lambda))[0] = params; ((ray_t**)ray_data(lambda))[1] = body; LAMBDA_CLOSURE(lambda) = closure; diff --git a/src/store/splay.c b/src/store/splay.c index 32c00ae39..069747a1e 100644 --- a/src/store/splay.c +++ b/src/store/splay.c @@ -281,6 +281,15 @@ static bool splay_generation_is_current(const ray_splay_write_t* write) { active && strcmp(current, write->dir) == 0; } +/* The first write of a table is made in its directory; its columns are the + * table until the first publish. From then on readers resolve .current, so + * the root schema is renamed out of the way (older binaries then fail loudly + * instead of reading obsolete files) and the columns it names are removed, + * with their .link sidecars. Only what the schema names goes: the root also + * holds the symfile, the lock file, the generations and, for a table written + * into a database root, the partitions. .legacy.d goes last, once every + * file it names is gone, so a cleanup cut short is finished by the next + * publish. */ static void splay_retire_legacy_schema(const char* root) { char schema[1024], retired[1024]; int n = snprintf(schema, sizeof(schema), "%s/.d", root); @@ -288,14 +297,54 @@ static void splay_retire_legacy_schema(const char* 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); + if (access(schema, F_OK) == 0) { + (void)unlink(retired); + if (rename(schema, retired) != 0) { + (void)unlink(schema); + return; + } + } + if (access(retired, F_OK) != 0) return; + + ray_t* names = ray_col_load(retired); + if (!names || RAY_IS_ERR(names)) { + if (names) ray_error_free(names); + return; + } + bool all_gone = names->type == RAY_STR; + for (int64_t c = 0; all_gone && c < names->len; c++) { + size_t len = 0; + const char* name = ray_str_vec_get(names, c, &len); + if (!name || !splay_col_name_safe(name, len)) { + all_gone = false; + break; + } + static const char* const suffix[] = {"", ".link"}; + for (size_t k = 0; k < sizeof(suffix) / sizeof(suffix[0]); k++) { + char path[1100]; + int pn = snprintf(path, sizeof(path), "%s/%.*s%s", root, + (int)len, name, suffix[k]); + if (pn < 0 || (size_t)pn >= sizeof(path)) { all_gone = false; break; } + struct stat st; +#ifdef RAY_OS_WINDOWS + if (stat(path, &st) != 0) continue; +#else + if (lstat(path, &st) != 0) continue; +#endif + if (S_ISDIR(st.st_mode)) continue; /* not a column file */ + if (unlink(path) != 0) all_gone = false; + } + } + ray_release(names); + if (all_gone) (void)unlink(retired); } -static void splay_prune_generations(const char* root, const char* current, - const char* previous) { +/* Every generation but the selected one goes. A reader that resolved an + * older one and has not opened all its files yet finds one missing, resolves + * again and reads the selected generation (see splay_load_impl); files it + * already mapped stay readable until unmapped. Removal is best-effort: where + * an open file cannot be deleted (Windows), the next publish tries again. */ +static void splay_prune_generations(const char* root, const char* current) { char generations[1024]; int n = snprintf(generations, sizeof(generations), "%s/.generations", root); if (n < 0 || (size_t)n >= sizeof(generations)) return; @@ -312,9 +361,7 @@ static void splay_prune_generations(const char* root, const char* current, 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; + if (current && strcmp(rel, current) == 0) continue; splay_remove_tree_best_effort(full); } closedir(d); @@ -686,12 +733,7 @@ static void splay_remove_created(const ray_splay_write_t* write, bool unlink_loc ray_err_t ray_splay_write_finish(ray_splay_write_t* write, ray_err_t result, bool durable) { - 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); @@ -702,8 +744,7 @@ ray_err_t ray_splay_write_finish(ray_splay_write_t* write, ray_err_t result, 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); + splay_prune_generations(write->root, write->generation); } } if (result != RAY_OK && write->staged && write->dir[0] && @@ -1013,14 +1054,51 @@ static ray_t* splay_load_dom_impl(const char* dir, ray_sym_domain_t* dom, return tbl; } +/* Only the selected generation is kept, so one a reader resolved can be + * removed before the reader has opened all its files. A read that fails is + * tried again while the table keeps resolving to a different generation; + * a failure on the generation still selected is the table's own. Each retry + * follows a completed publish, so the reader is not counted out: a reader + * that is slow to open its files (many columns, slow storage, a busy CPU) + * would otherwise fail after a fixed number of saves. It gives up once the + * table has kept changing under it for SPLAY_RESOLVE_WAIT_NS (after at + * least SPLAY_RESOLVE_ATTEMPTS attempts), or when interrupted. */ +#define SPLAY_RESOLVE_WAIT_NS (INT64_C(60) * 1000000000) +#define SPLAY_RESOLVE_ATTEMPTS 8 + +static bool splay_moved_on(const char* dir, const char* resolved) { + char again[1024]; + return ray_splay_resolve_dir(dir, again, sizeof(again)) == RAY_OK && + strcmp(again, resolved) != 0; +} + +/* Whether a read of `resolved` that failed (attempt `attempt` of a loop + * started at `t0`) is tried again: 1 yes; 0 no, the failure is the table's + * own; -1 interrupted; -2 the table kept changing for too long. */ +static int splay_retry(const char* dir, const char* resolved, int attempt, int64_t t0) { + if (!resolved[0] || !splay_moved_on(dir, resolved)) return 0; + if (ray_interrupted()) return -1; + if (attempt >= SPLAY_RESOLVE_ATTEMPTS && + ray_profile_now_ns() - t0 >= SPLAY_RESOLVE_WAIT_NS) return -2; + return 1; +} + +/* The error a reader that stopped retrying (splay_retry < 0) returns in + * place of its last attempt's, which only reflects the race. */ +static ray_t* splay_retry_error(int why, const char* dir, ray_t* last) { + if (last && RAY_IS_ERR(last)) ray_error_free(last); + if (why == -1) return ray_error("cancel", "interrupted"); + return ray_error("io", "splayed %s: the table kept changing while it was read", dir); +} + /* Resolve sym_path to a FILE domain. Missing file → NULL domain with * RAY_OK (only an error if a SYM column is later encountered — the * symbol-free-table exemption must hold for reads too); existing but * 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)); +static ray_t* splay_load_once(const char* dir, const char* sym_path, + bool use_mmap, char* resolved, size_t resolved_sz, + ray_sym_domain_t** held) { + ray_err_t err = ray_splay_resolve_dir(dir, resolved, resolved_sz); 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 @@ -1031,21 +1109,83 @@ static ray_t* splay_load_impl(const char* dir, const char* sym_path, struct stat st; if (stat(sym_path, &st) == 0) { dom = ray_sym_domain_open(sym_path); + /* The previous attempt's domain stays open until here, so a + * retry extends it instead of reading the symfile again. */ + if (*held) { ray_sym_domain_release(*held); *held = NULL; } if (!dom) return ray_error("corrupt", "symfile %s: unreadable or invalid (bad magic, torn " "record, or missing \"\" at position 0)", sym_path); } } + /* An earlier attempt's domain not replaced above (no symfile this + * time) is let go here, before *held is overwritten. */ + if (*held) ray_sym_domain_release(*held); ray_t* tbl = splay_load_dom_impl(resolved, dom, use_mmap); - if (dom) ray_sym_domain_release(dom); /* columns hold their own refs */ + *held = dom; /* released by the caller; columns hold their own refs */ + return tbl; +} + +static ray_t* splay_load_impl(const char* dir, const char* sym_path, + bool use_mmap) { + char resolved[1024]; + ray_sym_domain_t* held = NULL; + int64_t t0 = ray_profile_now_ns(); + ray_t* tbl; + for (int attempt = 1;; attempt++) { + resolved[0] = '\0'; + tbl = splay_load_once(dir, sym_path, use_mmap, resolved, sizeof(resolved), &held); + if (tbl && !RAY_IS_ERR(tbl)) break; + int why = splay_retry(dir, resolved, attempt, t0); + if (why < 0) { tbl = splay_retry_error(why, dir, tbl); break; } + if (!why) break; + ray_error_free(tbl); + } + if (held) ray_sym_domain_release(held); return tbl; } +bool ray_splay_has_schema(const char* dir) { + char resolved[1024], schema[1100]; + int64_t t0 = ray_profile_now_ns(); + for (int attempt = 1;; attempt++) { + if (ray_splay_resolve_dir(dir, resolved, sizeof(resolved)) != RAY_OK) + return false; + int n = snprintf(schema, sizeof(schema), "%s/.d", resolved); + if (n < 0 || (size_t)n >= sizeof(schema)) return false; + struct stat st; + if (stat(schema, &st) == 0) return S_ISREG(st.st_mode); + if (splay_retry(dir, resolved, attempt, t0) != 1) return false; + } +} + ray_t* ray_splay_load(const char* dir, const char* sym_path) { return splay_load_impl(dir, sym_path, false); } +/* `dir`/ into out[cap]; false when it does not fit. */ +static bool splay_col_path(const char* dir, ray_t* tbl, int64_t c, char* out, size_t cap) { + ray_t* nstr = ray_sym_str(ray_table_col_name(tbl, c)); + if (!nstr || RAY_IS_ERR(nstr)) return false; + int n = snprintf(out, cap, "%s/%.*s", dir, (int)ray_str_len(nstr), ray_str_ptr(nstr)); + return n > 0 && (size_t)n < cap; +} + +/* Hash-index `col` and append the index to its index-less file `path`: + * built in place in the file (no copy of the column, the arrays written + * once), or where that does not apply, attached to a copy and appended. */ +static ray_err_t splay_hash_append(const char* path, ray_t* col) { + ray_err_t err = ray_col_build_hash_index(path, col, NULL); + if (err != RAY_ERR_NYI) return err; + ray_t* hi = ray_idx_hash_fn(col); + if (!hi || RAY_IS_ERR(hi)) { if (hi) ray_error_free(hi); return RAY_ERR_OOM; } + err = (hi->attrs & RAY_ATTR_HAS_INDEX) + ? ray_col_append_index(path, ray_index_payload(hi->index), hi->len, hi->type) + : RAY_ERR_IO; + ray_release(hi); + return err; +} + /* Build + persist accelerator indexes for a freshly-streamed splayed store. * The .csv.splayed writer emits raw columns; this scans each eligible numeric * column once and APPENDS a chunk-zone index region to its file (no data @@ -1087,14 +1227,7 @@ static void splay_build_index_col(const char* dir, ray_t* tbl, int64_t c, ray_t* if (n > 0 && n < (int)sizeof(path)) { ray_t* fc = ray_col_load(path); /* file-local codes */ if (fc && !RAY_IS_ERR(fc)) { - ray_t* fi = ray_idx_hash_fn(fc); /* hash over file-local */ - if (fi && !RAY_IS_ERR(fi)) { - (void)ray_col_append_index(path, - ray_index_payload(fi->index), fi->len, RAY_SYM); - ray_release(fi); - } else if (fi) { - ray_error_free(fi); - } + (void)splay_hash_append(path, fc); /* hash over file-local */ ray_release(fc); } else if (fc) { ray_error_free(fc); @@ -1149,23 +1282,12 @@ static void splay_build_index_col(const char* dir, ray_t* tbl, int64_t c, ray_t* *deferred = idx; return; } - ray_t* hi = ray_idx_hash_fn(col); - if (hi && !RAY_IS_ERR(hi) && (hi->attrs & RAY_ATTR_HAS_INDEX)) { + char hpath[1100]; + if (splay_col_path(dir, tbl, c, hpath, sizeof(hpath)) && + splay_hash_append(hpath, col) == RAY_OK) { ray_release(idx); /* zone sacrificed for the hash */ - idx = NULL; - ray_t* nstr = ray_sym_str(ray_table_col_name(tbl, c)); - if (nstr && !RAY_IS_ERR(nstr)) { - char path[1100]; - int n = snprintf(path, sizeof(path), "%s/%.*s", dir, - (int)ray_str_len(nstr), ray_str_ptr(nstr)); - if (n > 0 && n < (int)sizeof(path)) - (void)ray_col_append_index(path, - ray_index_payload(hi->index), hi->len, hi->type); - } - ray_release(hi); return; } - if (hi) { if (RAY_IS_ERR(hi)) ray_error_free(hi); else ray_release(hi); } /* Hash build failed — fall through and persist the zone. */ } @@ -1238,11 +1360,22 @@ void ray_splay_build_indexes(const char* dir, ray_t* tbl) { memset(deferred, 0, (size_t)nc * 2 * sizeof(ray_t*)); splay_index_ctx_t ctx = { .dir = dir, .tbl = tbl, .deferred = deferred, .hashed = deferred + nc }; ray_pool_dispatch_n(pool, splay_build_index_task, &ctx, (uint32_t)nc); - /* Hash builds one after another (each parallel inside), then the - * writes of all deferred columns together. */ + /* Hash builds one after another (each parallel inside), each into + * its file; where that cannot be done in place, built in memory and + * written with the zones of the other deferred columns. */ for (int64_t c = 0; c < nc; c++) { if (!deferred[c]) continue; - ray_t* hi = ray_idx_hash_fn(ray_table_get_col_idx(tbl, c)); + ray_t* col = ray_table_get_col_idx(tbl, c); + char path[1100]; + ray_err_t e = splay_col_path(dir, tbl, c, path, sizeof(path)) + ? ray_col_build_hash_index(path, col, NULL) : RAY_ERR_IO; + if (e == RAY_OK) { /* the zone is sacrificed for the hash */ + ray_release(deferred[c]); + deferred[c] = NULL; + continue; + } + if (e != RAY_ERR_NYI) continue; /* the zone, then */ + ray_t* hi = ray_idx_hash_fn(col); if (hi && !RAY_IS_ERR(hi) && (hi->attrs & RAY_ATTR_HAS_INDEX)) ctx.hashed[c] = hi; else if (hi) { if (RAY_IS_ERR(hi)) ray_error_free(hi); else ray_release(hi); } } @@ -1257,9 +1390,9 @@ ray_t* ray_read_splayed(const char* dir, const char* sym_path) { return splay_load_impl(dir, sym_path, true); } -ray_t* ray_read_splayed_dom(const char* dir, struct ray_sym_domain_s* dom) { - char resolved[1024]; - ray_err_t err = ray_splay_resolve_dir(dir, resolved, sizeof(resolved)); +static ray_t* splay_read_dom_once(const char* dir, ray_sym_domain_t* dom, + char* resolved, size_t resolved_sz) { + ray_err_t err = ray_splay_resolve_dir(dir, resolved, resolved_sz); if (err != RAY_OK) return ray_error(ray_err_code_str(err), "cannot resolve splayed generation"); ray_sym_domain_t* fresh = NULL; @@ -1274,28 +1407,63 @@ ray_t* ray_read_splayed_dom(const char* dir, struct ray_sym_domain_s* dom) { return tbl; } +ray_t* ray_read_splayed_dom(const char* dir, struct ray_sym_domain_s* dom) { + char resolved[1024]; + int64_t t0 = ray_profile_now_ns(); + for (int attempt = 1;; attempt++) { + resolved[0] = '\0'; + ray_t* tbl = splay_read_dom_once(dir, dom, resolved, sizeof(resolved)); + if (tbl && !RAY_IS_ERR(tbl)) return tbl; + int why = splay_retry(dir, resolved, attempt, t0); + if (why < 0) return splay_retry_error(why, dir, tbl); + if (!why) return tbl; + ray_error_free(tbl); + } +} + ray_err_t ray_splay_hash_column(const char* path, ray_t* zone) { if (!path) return RAY_ERR_DOMAIN; bool trace = getenv("RAY_CSV_TRACE") != NULL; /* the converters' phase trace */ int64_t t0 = trace ? ray_profile_now_ns() : 0; ray_t* col = ray_col_mmap(path); if (!col || RAY_IS_ERR(col)) { if (col) ray_error_free(col); return RAY_ERR_IO; } - 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_hash_trace_t ht; + memset(&ht, 0, sizeof(ht)); + /* The build reads the column front to back, twice, and not again: + * larger read-ahead, and its pages are the first to go under pressure + * rather than the build's own. */ + if (col->len > 0) /* from the header: madvise wants the mapping's page */ + ray_vm_advise_seq(col, 32 + (size_t)col->len * ray_sym_elem_size(col->type, col->attrs)); + /* Built over the mapping, straight into the file: the arrays are + * written once, where they end up, and the column is not copied. */ + ray_err_t err = ray_col_build_hash_index(path, col, trace ? &ht : NULL); + if (err == RAY_ERR_NYI) { + /* No in-place build here: attached in memory, then appended. The + * mapping is the column's only reference, so the attach builds on it + * rather than on a copy. */ + ray_t* r = ray_index_attach_hash(&col); + if (!RAY_IS_ERR(r) && (col->attrs & RAY_ATTR_HAS_INDEX)) { + const ray_index_t* hx = ray_index_payload(col->index); + ht.n_keys = hx->u.hash.n_keys; + ht.n_groups = hx->u.hash.n_groups; + ray_hash_mark_t tm = trace ? ray_hash_trace_mark() : (ray_hash_mark_t){0}; + err = ray_col_append_index(path, hx, col->len, col->type); + /* the region is read from the built arrays and written to the file */ + if (trace) ray_hash_trace_add(&ht, RAY_HXT_APPEND, tm, 2 * ray_index_inline_size(hx)); + } else { + if (RAY_IS_ERR(r)) ray_error_free(r); + err = RAY_ERR_IO; } - ray_release(hi); - } else if (hi) { - if (RAY_IS_ERR(hi)) ray_error_free(hi); else ray_release(hi); + } + int64_t t2 = trace ? ray_profile_now_ns() : 0; + if (trace && err == RAY_OK) { + fprintf(stderr, "splayed hash: file=%s rows=%" PRId64 " keys=%" PRId64 " groups=%" PRId64 + " mmap=%.1fms build=%.1fms write=%.1fms\n", + path, col->len, ht.n_keys, ht.n_groups, (double)(t1 - t0) / 1e6, + (double)(t2 - t1 - ht.ns[RAY_HXT_APPEND]) / 1e6, (double)ht.ns[RAY_HXT_APPEND] / 1e6); + ray_hash_trace_print(stderr, "splayed hash io", &ht, + col->len * (int64_t)ray_sym_elem_size(col->type, col->attrs)); } if (err != RAY_OK && zone) err = ray_col_append_index(path, ray_index_payload(zone), col->len, col->type); diff --git a/src/store/splay.h b/src/store/splay.h index 03813b9dd..0f89d32a2 100644 --- a/src/store/splay.h +++ b/src/store/splay.h @@ -31,8 +31,8 @@ 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. */ + * Publication keeps only the current generation; the others, and the first + * write's root columns, are removed best-effort after each successful publish. */ typedef struct { ray_fd_t lock; bool locked; @@ -53,8 +53,12 @@ ray_err_t ray_splay_write_finish(ray_splay_write_t* write, ray_err_t result, /* 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. */ +/* The returned generation may be removed by the next publish: open every file + * of a read right after resolving, and resolve again if one is missing (the + * splayed loaders and ray_splay_has_schema do). */ ray_err_t ray_splay_resolve_dir(const char* dir, char* out, size_t out_sz); +/* Does dir hold a published table (a schema in its selected generation)? */ +bool ray_splay_has_schema(const char* dir); /* Splayed table I/O. * diff --git a/src/store/stream.c b/src/store/stream.c index 884bd1456..635545979 100644 --- a/src/store/stream.c +++ b/src/store/stream.c @@ -50,17 +50,6 @@ ray_err_t ray_col_stream_open(ray_col_stream_t* w, 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; } @@ -69,6 +58,20 @@ static void ray_col_stream_drop_lut(ray_col_stream_t* w) { w->lut_id = NULL; w->lut_pos = NULL; } +/* The runtime id -> position cache, made by the first runtime-domain chunk: + * 4 MiB of ids and 2 MiB of positions, each a block one order up with its + * header (8 MB and 4 MB, 12 MB committed, the 4 MiB of ids written here). + * A writer fed chunks already encoded over its domain never needs it. Best + * effort: without it every cell probes the domain. */ +static bool ray_col_stream_lut(ray_col_stream_t* w) { + if (w->lut_id) return true; + 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_col_stream_drop_lut(w); return false; } + memset(w->lut_id, 0xff, (size_t)COL_STREAM_LUT * sizeof(int64_t)); + return true; +} + 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) { @@ -110,26 +113,39 @@ ray_err_t ray_col_stream_append(ray_col_stream_t* w, /* 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]; + const char* strings[BATCH]; size_t lengths[BATCH]; int64_t ids[BATCH]; + /* The batch's hashes, then (they are no longer read once the batch + * is interned) the positions written: one array's room on a worker's + * stack, as when the hashes were 32 bits wide. */ + union { uint64_t h64[BATCH]; uint32_t h32[BATCH]; uint32_t pos[BATCH]; } u; + /* One hash a string: all 64 bits for an import domain, which keys on + * them (ray_sym_domain_intern_batch64, which would otherwise hash + * the strings again), the low 32 for the others. */ + bool wide = ray_sym_domain_import(w->dom) != NULL; 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]); + for (int64_t i = 0; i < count; i++) strings[i] = ray_str_vec_get(col,off+i,&lengths[i]); + bool ok; + if (wide) { + for (int64_t i = 0; i < count; i++) u.h64[i] = ray_hash_bytes(strings[i],lengths[i]); + ok = ray_sym_domain_intern_batch64(w->dom,count,strings,lengths,u.h64,ids); + } else { + for (int64_t i = 0; i < count; i++) u.h32[i] = (uint32_t)ray_hash_bytes(strings[i],lengths[i]); + ok = ray_sym_domain_intern_batch(w->dom,count,strings,lengths,u.h32,ids); } - if (!ray_sym_domain_intern_batch(w->dom,count,strings,lengths,hashes,ids)) return RAY_ERR_OOM; + if (!ok) 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; + u.pos[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; + if (fwrite(u.pos,sizeof(*u.pos),(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); + const char* pool_base = bytes ? (const char*)ray_data(col->str_pool) : NULL; ray_str_t buf[1024]; for (int64_t off = 0; off < n;) { if (ray_interrupted()) return RAY_ERR_CANCEL; @@ -138,6 +154,10 @@ ray_err_t ray_col_stream_append(ray_col_stream_t* w, 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; + /* Stored with its content hash (RAY_COL_STR_HASHED): + * reuse a cached one, compute a missing one against the + * chunk's own pool, before the offset is rebased. */ + buf[i].hash32 = ray_str_t_hash32(&buf[i], pool_base); buf[i].pool_off += (uint32_t)w->pool_bytes; } if (!buf[i].len) w->had_nulls = true; @@ -150,6 +170,22 @@ ray_err_t ray_col_stream_append(ray_col_stream_t* w, 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 && ray_sym_vec_domain(col) == w->dom && + (col->attrs & RAY_SYM_W_MASK) == RAY_SYM_W32) { + /* Already encoded over the target domain at the file's width (a + * converter's own symbol decode): the cells are the positions, + * written as they are in one request. HAS_NULLS from a position 0 + * among them, as the arm below decides it (not from the chunk's + * flag); once found, the later chunks are not scanned. */ + const uint32_t* p = (const uint32_t*)ray_data(col); + for (int64_t off = 0; off < n && !w->had_nulls; off += 8192) { + int64_t end = n - off < 8192 ? n : off + 8192; + uint32_t lo = UINT32_MAX; + for (int64_t i = off; i < end; i++) lo = p[i] < lo ? p[i] : lo; + if (!lo) w->had_nulls = true; + } + if (n && fwrite(p, sizeof(uint32_t), (size_t)n, w->fp) != (size_t)n) + return RAY_ERR_IO; } 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 @@ -159,7 +195,8 @@ ray_err_t ray_col_stream_append(ray_col_stream_t* w, * 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; + bool cached = !direct && ray_sym_vec_domain(col) == ray_sym_runtime_domain() && + ray_col_stream_lut(w); const void* cd = ray_data(col); uint32_t buf[8192]; for (int64_t off = 0; off < n; ) { @@ -293,6 +330,8 @@ ray_err_t ray_col_stream_finish(ray_col_stream_t* w, bool durable) { * fast-reject against the FILE domain). */ hdr.rc = (w->type == RAY_SYM) ? (uint32_t)ray_sym_domain_count(w->dom) : 0; + /* STR: every pooled descriptor was appended with its content hash. */ + if (w->type == RAY_STR) ray_col_stamp_str_hashed(&hdr); 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 @@ -443,13 +482,21 @@ void ray_col_stream_hash_all(ray_col_stream_t* w, int64_t n, int64_t* 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; + /* built (or, OOM on the candidate list, left with their zones): a + * later call has nothing to do for them */ + for (int64_t c = 0; c < n; c++) w[c].wants_hash = false; ray_free_raw(cand); for (int64_t c = 0; c < n; c++) if (w[c].index) { ray_release(w[c].index); w[c].index = NULL; } } +void ray_col_stream_hash_one(ray_col_stream_t* w) { + if (!w->wants_hash) return; + (void)ray_splay_hash_column(w->path, w->index); /* best effort */ + w->wants_hash = false; + if (w->index) { ray_release(w->index); w->index = NULL; } +} + void ray_col_stream_abort(ray_col_stream_t* w) { ray_col_stream_drop_lut(w); stream_drop_index(w); diff --git a/src/store/stream.h b/src/store/stream.h index 28d359f65..a69400ac4 100644 --- a/src/store/stream.h +++ b/src/store/stream.h @@ -28,7 +28,9 @@ typedef struct { /* 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. */ + * first time it is met and looked up here after. Made by the first + * runtime-domain chunk: NULL while every chunk is already encoded over + * `dom` (a converter's own symbol decode) and needs no translation. */ 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 */ @@ -71,6 +73,11 @@ ray_err_t ray_col_stream_close_all(ray_col_stream_t* w, int64_t n, bool durable, * sized from the RAM budget); a single one builds with the parallel * builder. Best effort: a failed build leaves the column with its zone. */ void ray_col_stream_hash_all(ray_col_stream_t* w, int64_t n, int64_t* col_ns); +/* Build the hash index of one closed writer whose zone asked for one, right + * away and with the whole pool, while its file is still in the page cache; + * the zone is released and a later ray_col_stream_hash_all skips the + * writer. Best effort, as there. Call outside any pool dispatch. */ +void ray_col_stream_hash_one(ray_col_stream_t* w); /* Hash builds in flight at once: clamp(ram_limit / 4 / (58 B * max(rows, 1)), * 1, candidates). Pure; `candidates` >= 1 expected. */ int64_t ray_col_stream_hash_wave(int64_t ram_limit, int64_t rows, int64_t candidates); diff --git a/src/table/domain.c b/src/table/domain.c index d6139a254..6fddaf8c3 100644 --- a/src/table/domain.c +++ b/src/table/domain.c @@ -62,10 +62,12 @@ #include "mem/heap.h" #include "mem/sys.h" /* domain buffers are process-global → mmap-backed, not buddy */ #include "mem/arena.h" /* ray_arena_t / ray_arena_str — domain atom storage */ +#include "store/part.h" /* discard unused partition-owned FILE domains */ #include "store/fileio.h" /* flock + tmp/rename protocol for flush */ #include "ops/hash.h" /* ray_hash_bytes (same hash family as g_sym) */ #include "core/pool.h" /* batch intern: parallel read-only probe */ #include "sym.h" /* ray_sym_intern_prehashed (runtime fallback) */ +#include "symimp.h" /* DOM_IMPORT */ #include #include #include @@ -89,6 +91,9 @@ typedef enum { DOM_RUNTIME = 0, DOM_FILE = 1, + /* A symbol file one converter builds alone (ray_symimp_t): intern, + * count, flush and release only. */ + DOM_IMPORT = 2, } dom_kind_t; /* ---- per-domain string-atom arena ---------------------------------------- @@ -192,6 +197,8 @@ struct ray_sym_domain_s { dom_retired_t* retired; /* replaced atom arrays + old LUTs */ + struct ray_symimp_s* imp; /* DOM_IMPORT: the import dictionary */ + struct ray_sym_domain_s* next; /* cache chain */ }; @@ -340,6 +347,7 @@ static bool dom_publish_raw_snap(ray_sym_domain_t* d) { /* Free a FILE domain after the last reference dropped. Caller has * already unlinked it from the cache. */ static void dom_destroy(ray_sym_domain_t* d) { + if (d->imp) ray_symimp_free(d->imp); /* Atoms are RAY_ATTR_ARENA — never refcounted, never individually freed. * The arena bulk-frees them; we only free the pointer ARRAY here. */ ray_t** atoms = atomic_load_explicit(&d->atoms, memory_order_relaxed); @@ -583,6 +591,12 @@ static bool dom_extend_from_file_locked(ray_sym_domain_t* d, size_t st_size) { static ray_sym_domain_t* dom_open_impl(const char* path, bool create) { if (!path) return NULL; + /* A script or IPC caller may drop a parted view without running GC. + * Do not let its cache-only domain survive into a splayed read/write + * of a rebuilt root. Prune before taking g_dom_lock: releasing the + * cached SYM columns takes that lock itself. Live views keep their refs. */ + ray_parted_cache_prune(); + char* rpath = dom_resolve_path(path); if (!rpath) return NULL; @@ -685,6 +699,31 @@ 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_create_import(const char* path) { + if (!path) return NULL; + ray_sym_domain_t* d = (ray_sym_domain_t*)ray_sys_alloc(sizeof(*d)); + if (!d) return NULL; + memset(d, 0, sizeof(*d)); + d->kind = DOM_IMPORT; + d->rc = 1; + size_t pl = strlen(path); + d->path = (char*)ray_sys_alloc(pl + 1); + if (d->path) memcpy(d->path, path, pl + 1); + if (d->path) d->imp = ray_symimp_create(path, &d->count); + if (!d->imp) { ray_sys_free(d->path); ray_sys_free(d); return NULL; } + return d; +} + +bool ray_sym_domain_import_stats(ray_sym_domain_t* dom, struct ray_symimp_stats_s* out) { + if (!dom || dom->kind != DOM_IMPORT) return false; + ray_symimp_stats(dom->imp, out); + return true; +} + +struct ray_symimp_s* ray_sym_domain_import(ray_sym_domain_t* dom) { + return dom && dom->kind == DOM_IMPORT ? dom->imp : NULL; +} + ray_sym_domain_t* ray_sym_domain_new(void) { ray_sym_domain_t* d = ray_sys_alloc(sizeof(*d)); if (!d) return NULL; @@ -724,6 +763,7 @@ void ray_sym_domain_release(ray_sym_domain_t* dom) { ray_t* ray_sym_domain_str(ray_sym_domain_t* dom, int64_t pos) { if (!dom) return NULL; if (dom->kind == DOM_RUNTIME) return ray_sym_str(pos); + if (dom->kind == DOM_IMPORT) return NULL; /* Lock-free fast path: acquire the published count, then the array, then * the slot. Appends release-publish the count after the slot write; @@ -745,7 +785,7 @@ ray_t* ray_sym_domain_str(ray_sym_domain_t* dom, int64_t pos) { } bool ray_sym_domain_raw_pin(ray_sym_domain_t* dom, ray_sym_domain_raw_t* out) { - if (!dom || !out || dom->kind == DOM_RUNTIME) return false; + if (!dom || !out || dom->kind != DOM_FILE) return false; dom_raw_snap_t* snap = atomic_load_explicit(&dom->raw_snap, memory_order_acquire); if (!snap) return false; out->map = snap->map; @@ -763,6 +803,9 @@ static const int64_t g_empty_lut[1] = { -1 }; const int64_t* ray_sym_domain_runtime_lut(ray_sym_domain_t* dom) { if (!dom || dom->kind == DOM_RUNTIME) return NULL; + /* never asked for: an import's columns are read back through the + * file domain, after the import dictionary is gone */ + if (dom->kind == DOM_IMPORT) return NULL; int64_t* lut = atomic_load_explicit(&dom->runtime_lut, memory_order_acquire); if (lut) return lut; @@ -867,6 +910,7 @@ static int64_t dom_probe_locked(ray_sym_domain_t* d, uint32_t h, int64_t ray_sym_domain_find(ray_sym_domain_t* dom, const char* str, size_t len) { if (!dom || !str) return -1; if (dom->kind == DOM_RUNTIME) return ray_sym_find(str, len); + if (dom->kind == DOM_IMPORT) return -1; if (atomic_load_explicit(&dom->count, memory_order_acquire) == 0) return -1; @@ -961,6 +1005,11 @@ static int64_t dom_append_locked(ray_sym_domain_t* d, uint32_t h, int64_t ray_sym_domain_intern(ray_sym_domain_t* dom, const char* str, size_t len) { if (!dom || !str) return -1; if (dom->kind == DOM_RUNTIME) return ray_sym_intern(str, len); + if (dom->kind == DOM_IMPORT) { + uint64_t h = ray_hash_bytes(str, len); + int64_t pos = -1; + return ray_symimp_intern_batch(dom->imp, 1, &str, &len, &h, &pos) ? pos : -1; + } dom_lock(); if (!dom->buckets && !dom_build_index_locked(dom, 1)) { @@ -1158,6 +1207,19 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, const uint32_t* hashes, int64_t* out_pos) { if (!dom || n < 0) return false; if (n == 0) return true; + if (dom->kind == DOM_IMPORT) { + /* The import dictionary keys on all 64 bits of the hash, which a + * caller of this entry point has dropped: hashed again here + * (ray_sym_domain_intern_batch64 is the path that keeps them). */ + uint64_t h64[1024]; + for (int64_t o = 0; o < n; o += 1024) { + int64_t k = n - o < 1024 ? n - o : 1024; + for (int64_t i = 0; i < k; i++) + h64[i] = strs[o + i] ? ray_hash_bytes(strs[o + i], lens[o + i]) : ray_hash_bytes("", 0); + if (!ray_symimp_intern_batch(dom->imp, k, strs + o, lens + o, h64, out_pos + o)) return false; + } + return true; + } if (dom->kind == DOM_RUNTIME) { for (int64_t i = 0; i < n; i++) { int64_t id = ray_sym_intern_prehashed(hashes[i], strs[i], lens[i]); @@ -1381,6 +1443,23 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, return ok; } +bool ray_sym_domain_intern_batch64(ray_sym_domain_t* dom, int64_t n, + const char* const* strs, const size_t* lens, + const uint64_t* hashes, int64_t* out_pos) { + if (!dom || n < 0) return false; + if (dom->kind == DOM_IMPORT) + return n == 0 || ray_symimp_intern_batch(dom->imp, n, strs, lens, hashes, out_pos); + /* the other domains key on the low 32 bits; in slices of 4096, which + * still take the parallel probe */ + uint32_t h32[4096]; + for (int64_t o = 0; o < n; o += 4096) { + int64_t k = n - o < 4096 ? n - o : 4096; + for (int64_t i = 0; i < k; i++) h32[i] = (uint32_t)hashes[o + i]; + if (!ray_sym_domain_intern_batch(dom, k, strs + o, lens + o, h32, out_pos + o)) return false; + } + return true; +} + int64_t ray_sym_domain_count(ray_sym_domain_t* dom) { if (!dom) return 0; if (dom->kind == DOM_RUNTIME) return (int64_t)ray_sym_count(); @@ -1397,6 +1476,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->kind == DOM_IMPORT) return ray_symimp_sync(dom->imp, durable); if (!dom->path) return RAY_ERR_DOMAIN; dom_lock(); @@ -1547,6 +1627,116 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { return err; } +static bool dom_fseek(FILE* f, int64_t off) { +#ifdef RAY_OS_WINDOWS + return _fseeki64(f, off, SEEK_SET) == 0; +#else + return fseeko(f, (off_t)off, SEEK_SET) == 0; +#endif +} + +ray_err_t ray_sym_domain_flush_append(ray_sym_domain_t* dom, bool durable) { + if (!dom) return RAY_ERR_TYPE; + if (dom->kind == DOM_RUNTIME) return RAY_OK; + if (dom->kind == DOM_IMPORT) return ray_symimp_sync(dom->imp, durable); + if (!dom->path) return RAY_ERR_DOMAIN; + + dom_lock(); + int64_t count = atomic_load_explicit(&dom->count, memory_order_relaxed); + int64_t disk_count = dom->disk_count; + size_t disk_size = dom->disk_size; + /* Only the entries past the persisted prefix are written: materialize + * those under the lock (arena-owned, they stay valid after it). */ + for (int64_t i = disk_count; i < count; i++) { + if (!dom_atom_at_locked(dom, i)) { dom_unlock(); return RAY_ERR_OOM; } + } + ray_t** atoms = atomic_load_explicit(&dom->atoms, memory_order_relaxed); + dom_unlock(); + if (count == disk_count && !durable) return RAY_OK; + + char lock_path[1024]; + if (snprintf(lock_path, sizeof(lock_path), "%s.lk", dom->path) >= (int)sizeof(lock_path)) + return RAY_ERR_IO; + ray_fd_t lock_fd = ray_file_open(lock_path, + RAY_OPEN_READ | RAY_OPEN_WRITE | RAY_OPEN_CREATE); + if (lock_fd == RAY_FD_INVALID) return RAY_ERR_IO; + ray_err_t err = ray_file_lock_ex(lock_fd); + if (err != RAY_OK) { ray_file_close(lock_fd); return err; } + + /* The file must still be the persisted size: anything else is another + * writer. */ + struct stat st; + bool exists = stat(dom->path, &st) == 0; + if (disk_count == 0 ? (exists && st.st_size > 0) + : (!exists || (size_t)st.st_size != disk_size)) { + ray_file_unlock(lock_fd); + ray_file_close(lock_fd); + return RAY_ERR_CORRUPT; + } + FILE* f = fopen(dom->path, disk_count == 0 ? "wb+" : "rb+"); + if (!f) { ray_file_unlock(lock_fd); ray_file_close(lock_fd); return RAY_ERR_IO; } + size_t size = disk_size; + uint32_t magic = DOMAIN_STRL_MAGIC; + if (disk_count == 0) { + int64_t zero = 0; + if (fwrite(&magic, 4, 1, f) != 1 || fwrite(&zero, 8, 1, f) != 1) err = RAY_ERR_IO; + size = 12; + } else if (!dom_fseek(f, (int64_t)disk_size)) { + err = RAY_ERR_IO; + } + enum { FLUSH_BUF = 1u << 20 }; + uint8_t* wb = err == RAY_OK ? (uint8_t*)ray_sys_alloc(FLUSH_BUF) : NULL; + size_t wn = 0; + if (err == RAY_OK && !wb) err = RAY_ERR_OOM; + for (int64_t i = disk_count; err == RAY_OK && i < count; i++) { + ray_t* s = atoms[i]; + size_t slen = ray_str_len(s); + if (slen > UINT32_MAX) { err = RAY_ERR_RANGE; break; } + uint32_t len32 = (uint32_t)slen; + if (wn + 4 + slen > FLUSH_BUF) { + if (wn && fwrite(wb, 1, wn, f) != wn) { err = RAY_ERR_IO; break; } + wn = 0; + } + if (4 + slen > FLUSH_BUF) { + if (fwrite(&len32, 4, 1, f) != 1 || fwrite(ray_str_ptr(s), 1, slen, f) != slen) { + err = RAY_ERR_IO; + break; + } + } else { + memcpy(wb + wn, &len32, 4); + if (slen) memcpy(wb + wn + 4, ray_str_ptr(s), slen); + wn += 4 + slen; + } + size += 4 + slen; + } + if (err == RAY_OK && wn && fwrite(wb, 1, wn, f) != wn) err = RAY_ERR_IO; + ray_sys_free(wb); + /* the count goes in last, once the records it covers are written */ + if (err == RAY_OK && (fflush(f) != 0 || !dom_fseek(f, 4) || + fwrite(&count, 8, 1, f) != 1 || fflush(f) != 0)) + err = RAY_ERR_IO; + /* start writing the new records back now, so a later durable flush + * waits for little */ + if (err == RAY_OK && !durable) + ray_file_writeback_start(fileno(f), (int64_t)disk_size, (int64_t)(size - disk_size)); + if (fclose(f) != 0 && err == RAY_OK) err = RAY_ERR_IO; + if (err == RAY_OK && durable) { + ray_fd_t fd = ray_file_open(dom->path, RAY_OPEN_READ | RAY_OPEN_WRITE); + if (fd == RAY_FD_INVALID) err = RAY_ERR_IO; + else { err = ray_file_sync(fd); ray_file_close(fd); } + if (err == RAY_OK) err = ray_file_sync_dir(dom->path); + } + if (err == RAY_OK) { + dom_lock(); + dom->disk_count = count; + dom->disk_size = size; + dom_unlock(); + } + ray_file_unlock(lock_fd); + ray_file_close(lock_fd); + return err; +} + /* ---- RAY_SYM_AUDIT ----------------------------------------------------------- */ /* Cached at ray_sym_init (table/sym.c) from the RAY_SYM_AUDIT env var. */ diff --git a/src/table/domain.h b/src/table/domain.h index de7c8ba94..17bd76712 100644 --- a/src/table/domain.h +++ b/src/table/domain.h @@ -101,6 +101,21 @@ 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); +/* A fresh symbol file at `path` that one converter builds alone, the + * strings appended straight into the mapped file (see table/symimp.h): + * intern, intern_batch, count, flush / flush_append (append: header and + * writeback; durable: cut and sync) and release only. Not cached by path. + * NULL where unsupported or on failure; the caller then uses + * ray_sym_domain_open_or_create. */ +ray_sym_domain_t* ray_sym_domain_create_import(const char* path); +/* Such a domain's interning counts (RAY_CSV_TRACE), as ray_symimp_stats + * gives them (table/symimp.h). False for any other domain. */ +struct ray_symimp_stats_s; +bool ray_sym_domain_import_stats(ray_sym_domain_t* dom, struct ray_symimp_stats_s* out); +/* Such a domain's import dictionary (for the grouped import, + * table/symgrp.h); NULL for any other domain. */ +struct ray_symimp_s* ray_sym_domain_import(ray_sym_domain_t* dom); + /* 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. */ @@ -181,6 +196,12 @@ int64_t ray_sym_domain_intern(ray_sym_domain_t* dom, const char* str, size_t len bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, const char* const* strs, const size_t* lens, const uint32_t* hashes, int64_t* out_pos); +/* The same with hashes[i] = ray_hash_bytes of strs[i], all 64 bits: the + * import dictionary keys on them (the 32-bit entry point hashes its strings + * again for it); the other domains take their low 32 bits. */ +bool ray_sym_domain_intern_batch64(ray_sym_domain_t* dom, int64_t n, + const char* const* strs, const size_t* lens, + const uint64_t* hashes, int64_t* out_pos); /* Number of entries in the domain. */ int64_t ray_sym_domain_count(ray_sym_domain_t* dom); @@ -196,6 +217,16 @@ const char* ray_sym_domain_path(ray_sym_domain_t* dom); * own persistence). */ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable); +/* Append the entries interned since the last flush to the symfile in place + * (header count rewritten after the records), instead of rewriting the + * whole file through a tmp + rename. For a symfile one writer builds + * alone, such as a converter's staging domain, flushed as it grows so the + * last flush writes only the tail. Same `.lk` lock as + * ray_sym_domain_flush; the file must still have the persisted size. + * `durable` also syncs the file and its directory, even when nothing new + * was interned. */ +ray_err_t ray_sym_domain_flush_append(ray_sym_domain_t* dom, bool durable); + /* RAY_SYM_AUDIT=1 support (cached at ray_sym_init): when set, * ray_sym_vec_cell cross-checks every resolution and aborts with full * context on an invariant violation (unresolvable atom / position out diff --git a/src/table/symgrp.c b/src/table/symgrp.c new file mode 100644 index 000000000..aea402934 --- /dev/null +++ b/src/table/symgrp.c @@ -0,0 +1,1014 @@ +/* + * 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 "symgrp.h" +#include "symimp.h" +#include "ops/hash.h" + +#if defined(RAY_OS_LINUX) || defined(RAY_OS_MACOS) || defined(__linux__) || defined(__APPLE__) + +#include "mem/sys.h" +#include +#include +#include +#include +#include + +/* ---- append-only chunk lists -------------------------------------------- + * Items of one size in chunks that double from 16 KB to 4 MB: a small list + * stays small, a big one is made of blocks large enough to spill to a file + * past the anon watermark (mem/sys.h), and is read back in order. */ +typedef struct sg_chunk_s { + struct sg_chunk_s* next; + int64_t n, cap; + _Alignas(8) uint8_t data[]; +} sg_chunk_t; +typedef struct { sg_chunk_t *head, *tail; int64_t n; } sg_list_t; + +#define SG_CHUNK_MIN ((int64_t)16 << 10) +#define SG_CHUNK_MAX ((int64_t)4 << 20) + +static void* sg_push(sg_list_t* l, size_t isz) { + sg_chunk_t* c = l->tail; + if (!c || c->n == c->cap) { + int64_t bytes = c ? c->cap * (int64_t)isz * 2 : SG_CHUNK_MIN; + if (bytes > SG_CHUNK_MAX) bytes = SG_CHUNK_MAX; + int64_t cap = bytes / (int64_t)isz; + if (cap < 1) cap = 1; + sg_chunk_t* nc = (sg_chunk_t*)ray_sys_alloc(sizeof(sg_chunk_t) + (size_t)cap * isz); + if (!nc) return NULL; + nc->next = NULL; nc->n = 0; nc->cap = cap; + if (c) c->next = nc; else l->head = nc; + l->tail = c = nc; + } + l->n++; + return c->data + (size_t)(c->n++) * isz; +} +static void sg_list_free(sg_list_t* l) { + for (sg_chunk_t* c = l->head; c;) { sg_chunk_t* nx = c->next; ray_sys_free(c); c = nx; } + l->head = l->tail = NULL; l->n = 0; +} + +/* Bytes kept for the deferred candidates: the same lists, raw. */ +static const char* sg_keep(sg_list_t* l, const char* s, uint32_t len) { + sg_chunk_t* c = l->tail; + if (!c || c->cap - c->n < (int64_t)len) { + int64_t cap = c ? c->cap * 2 : SG_CHUNK_MIN; + if (cap > SG_CHUNK_MAX) cap = SG_CHUNK_MAX; + if (cap < (int64_t)len) cap = len; + sg_chunk_t* nc = (sg_chunk_t*)ray_sys_alloc(sizeof(sg_chunk_t) + (size_t)(cap ? cap : 1)); + if (!nc) return NULL; + nc->next = NULL; nc->n = 0; nc->cap = cap; + if (c) c->next = nc; else l->head = nc; + l->tail = c = nc; + } + char* p = (char*)c->data + c->n; + if (len) memcpy(p, s, len); + c->n += len; + return p; +} + +/* Fault injection for the suite, the import's RAY_PQ_SYM_INJECT (debug + * builds): "reload" fails a window's load after the first. */ +static bool sg_inject(const char* step) { +#if defined(DEBUG) + const char* e = getenv("RAY_PQ_SYM_INJECT"); + return e && !strcmp(e, step); +#else + (void)step; return false; +#endif +} + +/* Stable sort of 64-bit words by their high 32 bits (two 16-bit radix + * passes); tmp is n words. */ +static bool sg_sort_hi(uint64_t* a, uint64_t* tmp, int64_t n) { + if (n < 2) return true; + int64_t* cnt = (int64_t*)ray_sys_alloc(65536 * sizeof(int64_t)); + if (!cnt) return false; + for (int pass = 0; pass < 2; pass++) { + int sh = 32 + 16 * pass; + memset(cnt, 0, 65536 * sizeof(int64_t)); + for (int64_t i = 0; i < n; i++) cnt[(a[i] >> sh) & 0xffff]++; + int64_t s = 0; + for (int d = 0; d < 65536; d++) { int64_t c = cnt[d]; cnt[d] = s; s += c; } + for (int64_t i = 0; i < n; i++) tmp[cnt[(a[i] >> sh) & 0xffff]++] = a[i]; + memcpy(a, tmp, (size_t)n * sizeof(uint64_t)); + } + ray_sys_free(cnt); + return true; +} + +/* ---- the index -------------------------------------------------------- */ + +typedef struct { uint64_t h; uint32_t len, pos; } sg_ent_t; /* a log entry */ +typedef struct { uint64_t h; uint32_t len, t, local, count; } sg_own_t; /* a new string */ +/* A candidate compared after its window (or known not to match: `miss`). */ +typedef struct { int64_t t; uint64_t h; const char* s; uint32_t local, pos, len, miss; } sg_def_t; +typedef struct { int64_t t; uint32_t local, pos; } sg_ovr_t; + +/* Verdict words: kind in the top 2 bits; NEW and REF hold an owner id, OLD + * a position. */ +#define SG_KIND(w) ((uint32_t)((w) >> 62)) +#define SG_VAL(w) ((w) & ((UINT64_C(1) << 62) - 1)) +#define SG_WORD(k, v) (((uint64_t)(k) << 62) | (uint64_t)(v)) + +typedef struct { + int64_t n; /* staged local ids */ + ray_symgrp_fp_t* fp; /* [n], by hash group (stable: local id order in each) */ + int64_t* seg; /* [groups + 1] */ + uint64_t* r; /* [n] verdict words, as fp */ + uint32_t* cnt; /* FREQ: [n + 1] rows by local id */ + uint64_t* own; /* ROWS*: bit per local id of the new strings */ + uint64_t* again; /* ROWS*: of them, those a later task meets too */ + uint32_t* rank; /* ROWS*: the others before each bitmap word (positions) */ + uint32_t* arank; /* ROWS*: those met again before it (positions) */ + int64_t owned, bytes, cand; + int64_t nagain, abytes; /* ROWS: the strings met again, their records' bytes */ +} sg_task_t; + +struct ray_symgrp_s { + ray_symimp_t* imp; + ray_symgrp_order_t order; + pthread_mutex_t lock; /* sg_collide */ + sg_list_t logs[RAY_SYMGRP_MAX]; + int64_t entries; + int64_t known; /* positions below it in the logs (or 0, ""): ray_symgrp_adopt */ + /* the pass */ + int lg; /* log2 of the groups */ + int64_t ntasks, workers; + sg_task_t* tasks; + sg_list_t stage; /* the tasks' arrays (sg_stage_alloc) */ + pthread_mutex_t slock; /* stage */ + int64_t nown, pos0, off0; + uint32_t* pos_of; /* [nown] */ + uint32_t* t_of; /* [nown] */ + int64_t* off_of; /* [nown]: SHARDS, FREQ */ + int64_t aend, rend; /* ROWS*: the ends of the runs met again and of the others */ + int64_t* offb; /* [2 ntasks]: ROWS*, a task's records (the + * others, then those met again) */ + uint32_t* gslots; /* step 2's group table, sized for the largest */ + sg_ent_t* gent; + sg_own_t* gnew; + /* the window */ + uint32_t* spos; /* loaded positions, ascending */ + uint32_t* slen; /* their records' lengths */ + int64_t* soff; /* [sn + 1] into sbuf */ + char* sbuf; + int64_t sn; + sg_list_t* dl; /* [workers] deferred candidates */ + sg_list_t* db; /* [workers] their bytes */ + sg_ovr_t* ovr; /* by (t, local) */ + int64_t clo, chi; /* records sg_collide added since the last writeback */ + int64_t novr; + ray_symgrp_stats_t st; + _Atomic(int64_t) compares, cmp_bytes; +}; + +/* ROWS and ROWS_FLAT: positions by task and local id, no table by string. */ +static inline bool sg_rows(const ray_symgrp_t* g) { + return g->order == RAY_SYMGRP_ROWS || g->order == RAY_SYMGRP_ROWS_FLAT; +} + +ray_symgrp_t* ray_symgrp_new(ray_symimp_t* imp, ray_symgrp_order_t order) { + if (!imp) return NULL; + ray_symgrp_t* g = (ray_symgrp_t*)ray_sys_alloc(sizeof(*g)); + if (!g) return NULL; + memset(g, 0, sizeof(*g)); + g->imp = imp; g->order = order; + atomic_init(&g->compares, 0); atomic_init(&g->cmp_bytes, 0); + if (pthread_mutex_init(&g->lock, NULL) != 0) { ray_sys_free(g); return NULL; } + if (pthread_mutex_init(&g->slock, NULL) != 0) { pthread_mutex_destroy(&g->lock); ray_sys_free(g); return NULL; } + return g; +} + +static void sg_window_free(ray_symgrp_t* g) { + ray_sys_free(g->spos); ray_sys_free(g->slen); ray_sys_free(g->soff); ray_sys_free(g->sbuf); + g->spos = NULL; g->slen = NULL; g->soff = NULL; g->sbuf = NULL; g->sn = 0; + if (g->dl) for (int64_t w = 0; w < g->workers; w++) { sg_list_free(&g->dl[w]); sg_list_free(&g->db[w]); } +} + +void ray_symgrp_end(ray_symgrp_t* g) { + if (!g) return; + sg_window_free(g); + ray_sys_free(g->dl); ray_sys_free(g->db); g->dl = g->db = NULL; + ray_sys_free(g->ovr); g->ovr = NULL; g->novr = 0; + sg_list_free(&g->stage); /* every task's arrays */ + ray_sys_free(g->tasks); g->tasks = NULL; g->ntasks = 0; + ray_sys_free(g->pos_of); ray_sys_free(g->t_of); ray_sys_free(g->off_of); ray_sys_free(g->offb); + g->pos_of = NULL; g->t_of = NULL; g->off_of = NULL; g->offb = NULL; g->nown = 0; +} + +void ray_symgrp_free(ray_symgrp_t* g) { + if (!g) return; + ray_symgrp_end(g); + for (int i = 0; i < RAY_SYMGRP_MAX; i++) sg_list_free(&g->logs[i]); + pthread_mutex_destroy(&g->lock); pthread_mutex_destroy(&g->slock); + ray_sys_free(g); +} + +bool ray_symgrp_begin(ray_symgrp_t* g, int64_t ntasks, int groups, int64_t workers) { + ray_symgrp_end(g); + int lg = 0; + while ((1 << lg) < groups && lg < RAY_SYMGRP_LOG_BITS) lg++; + g->lg = lg; + g->ntasks = ntasks < 0 ? 0 : ntasks; + g->workers = workers < 1 ? 1 : workers; + g->clo = g->chi = 0; + g->tasks = (sg_task_t*)ray_sys_alloc((size_t)(g->ntasks ? g->ntasks : 1) * sizeof(sg_task_t)); + g->dl = (sg_list_t*)ray_sys_alloc((size_t)g->workers * sizeof(sg_list_t)); + g->db = (sg_list_t*)ray_sys_alloc((size_t)g->workers * sizeof(sg_list_t)); + if (!g->tasks || !g->dl || !g->db) { ray_symgrp_end(g); return false; } + return true; /* zero-filled (mem/sys.h) */ +} + +/* ---- the pass's staging ------------------------------------------------ + * A task's arrays (its distinct strings, their verdicts and hash group + * bounds, the ROWS bitmaps) are one block cut from chunks the pass's tasks + * share: a file of many small row groups costs bytes by its rows, not + * mappings by its row groups. A block past an eighth of a chunk is a + * mapping of its own. Zero-filled (fresh mappings, never reused in the + * pass); all freed with the pass. */ +#define SG_STAGE_CHUNK (((int64_t)1 << 20) - 256) +/* What a block of `bytes` maps (mem/sys.h: a header, whole pages). */ +static int64_t sg_mapped(int64_t bytes) { + int64_t pg = (int64_t)sysconf(_SC_PAGESIZE); + if (pg <= 0) pg = 4096; + return (bytes + 32 + pg - 1) / pg * pg; +} +static void* sg_stage_alloc(ray_symgrp_t* g, int64_t bytes) { + bytes = (bytes + 15) & ~(int64_t)15; + pthread_mutex_lock(&g->slock); + sg_list_t* l = &g->stage; + sg_chunk_t* c = l->tail; + void* p = NULL; + if (bytes > SG_STAGE_CHUNK / 8) { + /* full from the start, at the head: the tail stays the chunk cut */ + sg_chunk_t* nc = (sg_chunk_t*)ray_sys_alloc(sizeof(sg_chunk_t) + (size_t)bytes); + if (nc) { + nc->n = nc->cap = bytes; nc->next = l->head; + l->head = nc; if (!l->tail) l->tail = nc; + g->st.stage_bytes += sg_mapped((int64_t)sizeof(sg_chunk_t) + bytes); + p = nc->data; + } + } else { + if (!c || c->cap - c->n < bytes) { + sg_chunk_t* nc = (sg_chunk_t*)ray_sys_alloc(sizeof(sg_chunk_t) + (size_t)SG_STAGE_CHUNK); + if (nc) { + nc->n = 0; nc->cap = SG_STAGE_CHUNK; nc->next = NULL; + if (c) c->next = nc; else l->head = nc; + l->tail = nc; + g->st.stage_bytes += sg_mapped((int64_t)sizeof(sg_chunk_t) + SG_STAGE_CHUNK); + } + c = nc; + } + if (c) { p = c->data + c->n; c->n += bytes; } + } + pthread_mutex_unlock(&g->slock); + return p; +} + +static inline int sg_group(const ray_symgrp_t* g, uint64_t h) { + return g->lg ? (int)(h >> (64 - g->lg)) : 0; +} +static inline int sg_log(uint64_t h) { return (int)(h >> (64 - RAY_SYMGRP_LOG_BITS)); } + +bool ray_symgrp_stage(ray_symgrp_t* g, int64_t t, int64_t n, const ray_symgrp_fp_t* fp, + const uint32_t* counts) { + if (t < 0 || t >= g->ntasks || n < 0) return false; + sg_task_t* k = &g->tasks[t]; + int ng = 1 << g->lg; + bool freq = g->order == RAY_SYMGRP_FREQ, rows = sg_rows(g); + int64_t words = rows ? (n + 1 + 63) / 64 : 0; + /* one block: seg, fp, r, then cnt (FREQ) or the bitmaps and their + * ranks (ROWS*), each at a multiple of 8 */ + int64_t o_fp = (ng + 1) * 8, o_r = o_fp + n * (int64_t)sizeof(*fp), o_x = o_r + n * 8; + int64_t bytes = o_x + (freq ? ((n + 1) * 4 + 7) / 8 * 8 : 0) + words * 24; + char* b = (char*)sg_stage_alloc(g, bytes); + if (!b) return false; + k->n = n; + k->seg = (int64_t*)b; + k->fp = (ray_symgrp_fp_t*)(b + o_fp); + k->r = (uint64_t*)(b + o_r); + for (int64_t i = 0; i < n; i++) k->seg[sg_group(g, fp[i].h) + 1]++; + for (int i = 0; i < ng; i++) k->seg[i + 1] += k->seg[i]; + int64_t at[RAY_SYMGRP_MAX]; + memcpy(at, k->seg, (size_t)ng * sizeof(int64_t)); + for (int64_t i = 0; i < n; i++) k->fp[at[sg_group(g, fp[i].h)]++] = fp[i]; + if (freq) { + k->cnt = (uint32_t*)(b + o_x); + for (int64_t i = 0; i < n; i++) k->cnt[i + 1] = counts ? counts[i] : 1; + } + if (rows) { + k->own = (uint64_t*)(b + o_x); + k->again = k->own + words; + k->rank = (uint32_t*)(k->again + words); + k->arank = k->rank + words; + } + return true; +} + +static uint64_t sg_group_cap(int64_t ne, int64_t ns) { + uint64_t cap = 16; + while (cap < (uint64_t)(ne + ns) * 2) cap <<= 1; + return cap; +} + +/* ROWS*: a new string's position, from its task's base (of the strings met + * again or of the others) and the new strings of its kind before it among + * the task's local ids. */ +static inline uint32_t sg_rank_pos(const ray_symgrp_t* g, int64_t t, uint32_t local) { + const sg_task_t* k = &g->tasks[t]; + uint64_t below = (UINT64_C(1) << (local & 63)) - 1, again = k->again[local >> 6]; + if (again >> (local & 63) & 1) + return (uint32_t)(g->pos0 + k->arank[local >> 6] + (uint32_t)__builtin_popcountll(again & below)); + uint64_t word = k->own[local >> 6] & ~again & below; + return (uint32_t)(g->pos0 + k->rank[local >> 6] + (uint32_t)__builtin_popcountll(word)); +} +/* A REF's owner task and position: ROWS* keep (task, local id) in the + * word, the other orders an owner id. */ +static inline uint32_t sg_ref_task(const ray_symgrp_t* g, uint64_t v) { + return sg_rows(g) ? (uint32_t)(v >> 32) : g->t_of[v]; +} +static inline uint32_t sg_ref_pos(const ray_symgrp_t* g, uint64_t v) { + return sg_rows(g) ? sg_rank_pos(g, (int64_t)(v >> 32), (uint32_t)v) : g->pos_of[v]; +} + +/* Step 2, one hash group: its log entries (the logs it spans) in a table, + * then every task's staged strings of the group in task order. */ +static bool sg_resolve_group(ray_symgrp_t* g, int gi, sg_list_t* owners, int64_t* next_id) { + int ng = 1 << g->lg, per = RAY_SYMGRP_MAX / ng; + int64_t ne = 0, ns = 0; + for (int l = gi * per; l < (gi + 1) * per; l++) ne += g->logs[l].n; + for (int64_t t = 0; t < g->ntasks; t++) ns += g->tasks[t].seg[gi + 1] - g->tasks[t].seg[gi]; + if (!ns) return true; + uint64_t cap = sg_group_cap(ne, ns), mask = cap - 1; + /* the pass's group buffers, sized for its largest group (sg_resolve) */ + uint32_t* slots = g->gslots; sg_ent_t* ent = g->gent; sg_own_t* nw = g->gnew; + memset(slots, 0, (size_t)cap * sizeof(uint32_t)); + bool ok = true, rows = sg_rows(g), split = g->order == RAY_SYMGRP_ROWS; + int64_t e = 0; + for (int l = gi * per; ok && l < (gi + 1) * per; l++) + for (sg_chunk_t* c = g->logs[l].head; c; c = c->next) { + memcpy(ent + e, c->data, (size_t)c->n * sizeof(sg_ent_t)); + e += c->n; + } + for (int64_t i = 0; ok && i < ne; i++) { + uint64_t s = ent[i].h & mask; + while (slots[s]) s = (s + 1) & mask; + slots[s] = (uint32_t)(i + 1); + } + int64_t nn = 0; + for (int64_t t = 0; ok && t < g->ntasks; t++) { + sg_task_t* k = &g->tasks[t]; + for (int64_t i = k->seg[gi]; i < k->seg[gi + 1]; i++) { + const ray_symgrp_fp_t* f = &k->fp[i]; + uint32_t cnt = k->cnt ? k->cnt[f->local] : 1; + uint64_t s = f->h & mask, w = 0; + for (;;) { + uint32_t v = slots[s]; + if (!v) break; + if (v <= ne) { + const sg_ent_t* x = &ent[v - 1]; + if (x->h == f->h && x->len == f->len) { w = SG_WORD(RAY_SYMGRP_OLD, x->pos); break; } + } else { + sg_own_t* o = &nw[v - ne - 1]; + if (o->h == f->h && o->len == f->len) { + o->count += cnt; + /* ROWS*: the owner itself (task, local id), its + * position computed from the tasks' bitmaps */ + w = rows ? SG_WORD(RAY_SYMGRP_REF, ((uint64_t)o->t << 32) | o->local) + : SG_WORD(RAY_SYMGRP_REF, *next_id + (int64_t)(v - ne - 1)); + /* ROWS: met again by a later task, its record goes + * with the others a later window may compare with */ + sg_task_t* ot = &g->tasks[o->t]; + uint64_t bit = UINT64_C(1) << (o->local & 63); + if (split && o->t != (uint32_t)t && !(ot->again[o->local >> 6] & bit)) { + ot->again[o->local >> 6] |= bit; + ot->nagain++; ot->abytes += 4 + (int64_t)o->len; + } + break; + } + } + s = (s + 1) & mask; + } + if (w) { + k->cand += 4 + (int64_t)f->len; + if (SG_KIND(w) == RAY_SYMGRP_OLD) g->st.old++; else g->st.refs++; + } else { + nw[nn] = (sg_own_t){f->h, f->len, (uint32_t)t, f->local, cnt}; + slots[s] = (uint32_t)(ne + nn + 1); + w = SG_WORD(RAY_SYMGRP_NEW, rows ? 0 : *next_id + nn); + nn++; + k->owned++; k->bytes += 4 + (int64_t)f->len; + if (k->own) k->own[f->local >> 6] |= UINT64_C(1) << (f->local & 63); + } + k->r[i] = w; + } + } + /* SHARDS, FREQ: the new strings in the order met, for their positions */ + for (int64_t i = 0; ok && !rows && i < nn; i++) { + sg_own_t* o = (sg_own_t*)sg_push(owners, sizeof(sg_own_t)); + if (!o) ok = false; else *o = nw[i]; + } + *next_id += nn; + g->st.log_loaded += ne; + return ok; +} + +bool ray_symgrp_resolve(ray_symgrp_t* g) { + int ng = 1 << g->lg, per = RAY_SYMGRP_MAX / ng; + sg_list_t owners = {0}; + int64_t nown = 0, bytes = 0; + bool ok = true; + for (int64_t t = 0; t < g->ntasks; t++) g->st.staged += g->tasks[t].n; + /* one table for every group, sized for the largest: allocated once, + * so a group's table reuses the pages the last one warmed */ + uint64_t cap = 16; int64_t ne_max = 1, ns_max = 1; + for (int gi = 0; gi < ng; gi++) { + int64_t ne = 0, ns = 0; + for (int l = gi * per; l < (gi + 1) * per; l++) ne += g->logs[l].n; + for (int64_t t = 0; t < g->ntasks; t++) ns += g->tasks[t].seg[gi + 1] - g->tasks[t].seg[gi]; + if (sg_group_cap(ne, ns) > cap) cap = sg_group_cap(ne, ns); + if (ne > ne_max) ne_max = ne; + if (ns > ns_max) ns_max = ns; + } + g->gslots = (uint32_t*)ray_sys_alloc((size_t)cap * sizeof(uint32_t)); + g->gent = (sg_ent_t*)ray_sys_alloc((size_t)ne_max * sizeof(sg_ent_t)); + g->gnew = (sg_own_t*)ray_sys_alloc((size_t)ns_max * sizeof(sg_own_t)); + ok = g->gslots && g->gent && g->gnew; + for (int gi = 0; ok && gi < ng; gi++) ok = sg_resolve_group(g, gi, &owners, &nown); + ray_sys_free(g->gslots); ray_sys_free(g->gent); ray_sys_free(g->gnew); + g->gslots = NULL; g->gent = NULL; g->gnew = NULL; + g->st.groups += ng; + for (int64_t t = 0; t < g->ntasks; t++) bytes += g->tasks[t].bytes; + g->nown = nown; g->st.owners += nown; + if (ok && nown) ok = ray_symimp_reserve(g->imp, nown, bytes, &g->pos0, &g->off0); + if (ok && nown) g->known = g->pos0 + nown; /* indexed below, ROWS* or not */ + if (ok && nown) g->st.rec_bytes += bytes; + if (ok && sg_rows(g)) { + /* positions by task, then by local id: the strings later tasks meet + * again (ROWS) first, task by task, then the others; in each a + * task's base, then the strings of its kind before it in the task's + * bitmaps (no table by string) */ + g->offb = (int64_t*)ray_sys_alloc((size_t)(g->ntasks ? g->ntasks : 1) * 2 * sizeof(int64_t)); + ok = g->offb != NULL; + int64_t nagain = 0, abytes = 0; + for (int64_t t = 0; t < g->ntasks; t++) { nagain += g->tasks[t].nagain; abytes += g->tasks[t].abytes; } + g->st.again += nagain; g->st.again_bytes += abytes; + int64_t abase = 0, aoff = g->off0, base = nagain, off = g->off0 + abytes; + for (int64_t t = 0; ok && t < g->ntasks; t++) { + sg_task_t* k = &g->tasks[t]; + g->offb[2 * t] = off; off += k->bytes - k->abytes; + g->offb[2 * t + 1] = aoff; aoff += k->abytes; + int64_t words = (k->n + 1 + 63) / 64; + uint32_t r = (uint32_t)base, ra = (uint32_t)abase; + for (int64_t w = 0; w < words; w++) { + k->rank[w] = r; k->arank[w] = ra; + r += (uint32_t)__builtin_popcountll(k->own[w] & ~k->again[w]); + ra += (uint32_t)__builtin_popcountll(k->again[w]); + } + base += k->owned - k->nagain; abase += k->nagain; + } + g->aend = aoff; g->rend = off; + /* the new strings join the index, task by task */ + for (int64_t t = 0; ok && t < g->ntasks; t++) { + const sg_task_t* k = &g->tasks[t]; + for (int64_t i = 0; ok && i < k->n; i++) { + if (SG_KIND(k->r[i]) != RAY_SYMGRP_NEW) continue; + const ray_symgrp_fp_t* f = &k->fp[i]; + sg_ent_t* x = (sg_ent_t*)sg_push(&g->logs[sg_log(f->h)], sizeof(sg_ent_t)); + if (!x) ok = false; + else { *x = (sg_ent_t){f->h, f->len, sg_rank_pos(g, t, f->local)}; g->entries++; } + } + } + return ok; + } + if (ok) { + g->pos_of = (uint32_t*)ray_sys_alloc((size_t)(nown ? nown : 1) * sizeof(uint32_t)); + g->t_of = (uint32_t*)ray_sys_alloc((size_t)(nown ? nown : 1) * sizeof(uint32_t)); + ok = g->pos_of && g->t_of; + } + if (ok) { + g->off_of = (int64_t*)ray_sys_alloc((size_t)(nown ? nown : 1) * sizeof(int64_t)); + ok = g->off_of != NULL; + uint64_t* ord = NULL; uint64_t* tmp = NULL; uint32_t* len_of = NULL; + if (ok && g->order == RAY_SYMGRP_FREQ) { + /* most rows first, then first occurrence: three stable passes, + * least significant key first */ + ord = (uint64_t*)ray_sys_alloc((size_t)(nown ? nown : 1) * sizeof(uint64_t)); + tmp = (uint64_t*)ray_sys_alloc((size_t)(nown ? nown : 1) * sizeof(uint64_t)); + len_of = (uint32_t*)ray_sys_alloc((size_t)(nown ? nown : 1) * sizeof(uint32_t)); + uint32_t* cnt_of = (uint32_t*)ray_sys_alloc((size_t)(nown ? nown : 1) * sizeof(uint32_t)); + uint32_t* loc_of = (uint32_t*)ray_sys_alloc((size_t)(nown ? nown : 1) * sizeof(uint32_t)); + ok = ord && tmp && len_of && cnt_of && loc_of; + int64_t id = 0; + for (sg_chunk_t* c = owners.head; ok && c; c = c->next) + for (int64_t i = 0; i < c->n; i++, id++) { + const sg_own_t* o = (const sg_own_t*)c->data + i; + len_of[id] = o->len; cnt_of[id] = o->count; loc_of[id] = o->local; g->t_of[id] = o->t; + } + for (int64_t i = 0; ok && i < nown; i++) ord[i] = ((uint64_t)loc_of[i] << 32) | (uint64_t)i; + ok = ok && sg_sort_hi(ord, tmp, nown); + for (int64_t i = 0; ok && i < nown; i++) { uint32_t x = (uint32_t)ord[i]; ord[i] = ((uint64_t)g->t_of[x] << 32) | x; } + ok = ok && sg_sort_hi(ord, tmp, nown); + for (int64_t i = 0; ok && i < nown; i++) { uint32_t x = (uint32_t)ord[i]; ord[i] = ((uint64_t)(UINT32_MAX - cnt_of[x]) << 32) | x; } + ok = ok && sg_sort_hi(ord, tmp, nown); + int64_t off = g->off0; + for (int64_t i = 0; ok && i < nown; i++) { + uint32_t x = (uint32_t)ord[i]; + g->pos_of[x] = (uint32_t)(g->pos0 + i); + g->off_of[x] = off; off += 4 + (int64_t)len_of[x]; + } + ray_sys_free(cnt_of); ray_sys_free(loc_of); + } else if (ok) { /* SHARDS: the order step 2 met them in */ + int64_t id = 0, off = g->off0; + for (sg_chunk_t* c = owners.head; c; c = c->next) + for (int64_t i = 0; i < c->n; i++, id++) { + const sg_own_t* o = (const sg_own_t*)c->data + i; + g->pos_of[id] = (uint32_t)(g->pos0 + id); + g->t_of[id] = o->t; + g->off_of[id] = off; off += 4 + (int64_t)o->len; + } + } + ray_sys_free(ord); ray_sys_free(tmp); ray_sys_free(len_of); + } + /* the new strings join the index */ + int64_t id = 0; + for (sg_chunk_t* c = owners.head; ok && c; c = c->next) + for (int64_t i = 0; ok && i < c->n; i++, id++) { + const sg_own_t* o = (const sg_own_t*)c->data + i; + sg_ent_t* x = (sg_ent_t*)sg_push(&g->logs[sg_log(o->h)], sizeof(sg_ent_t)); + if (!x) ok = false; + else { *x = (sg_ent_t){o->h, o->len, g->pos_of[id]}; g->entries++; } + } + sg_list_free(&owners); + return ok; +} + +int64_t ray_symgrp_task_size(const ray_symgrp_t* g, int64_t t) { + return t >= 0 && t < g->ntasks ? g->tasks[t].n : 0; +} + +bool ray_symgrp_task(const ray_symgrp_t* g, int64_t t, ray_symgrp_res_t* res) { + if (t < 0 || t >= g->ntasks) return false; + const sg_task_t* k = &g->tasks[t]; + for (int64_t i = 0; i < k->n; i++) { + uint64_t w = k->r[i]; + uint32_t local = k->fp[i].local; + uint64_t v = SG_VAL(w); + switch (SG_KIND(w)) { + case RAY_SYMGRP_NEW: + res[local] = sg_rows(g) + ? (ray_symgrp_res_t){sg_rank_pos(g, t, local), RAY_SYMGRP_NEW, 0, + (uint32_t)(k->again[local >> 6] >> (local & 63) & 1), -1} + : (ray_symgrp_res_t){g->pos_of[v], RAY_SYMGRP_NEW, 0, 0, g->off_of[v]}; + break; + case RAY_SYMGRP_OLD: + res[local] = (ray_symgrp_res_t){(uint32_t)v, RAY_SYMGRP_OLD, 0, 0, 0}; + break; + case RAY_SYMGRP_REF: + res[local] = (ray_symgrp_res_t){sg_ref_pos(g, v), RAY_SYMGRP_REF, sg_ref_task(g, v), 0, 0}; + break; + default: + return false; + } + } + return true; +} + +int64_t ray_symgrp_task_off(const ray_symgrp_t* g, int64_t t, bool again) { + return g->offb && t >= 0 && t < g->ntasks ? g->offb[2 * t + (again ? 1 : 0)] : -1; +} + +int64_t ray_symgrp_window(const ray_symgrp_t* g, int64_t ta, int64_t budget) { + int64_t tb = ta, sum = 0; + while (tb < g->ntasks && (tb == ta || sum + g->tasks[tb].cand <= budget)) sum += g->tasks[tb++].cand; + return tb; +} + +/* Writeback of what window [ta, tb) wrote, started as the window ends: the + * whole pass's records reserved at once, the file's sync would start only + * the first window's and leave the rest dirty until the final one. ROWS*: + * the window's run of the strings met again and its run of the others, + * each contiguous; SHARDS, FREQ: the span of the window's new records; and + * the records the window's collisions added. */ +static void sg_wb(ray_symgrp_t* g, int64_t lo, int64_t hi) { + if (hi <= lo) return; + ray_symimp_writeback(g->imp, lo, hi - lo); + g->st.wb_bytes += hi - lo; +} +void ray_symgrp_writeback(ray_symgrp_t* g, int64_t ta, int64_t tb) { + if (ta < 0 || tb > g->ntasks || ta >= tb) return; + if (sg_rows(g) && g->offb) { + sg_wb(g, g->offb[2 * ta + 1], tb < g->ntasks ? g->offb[2 * tb + 1] : g->aend); + sg_wb(g, g->offb[2 * ta], tb < g->ntasks ? g->offb[2 * tb] : g->rend); + } else if (g->off_of) { + int64_t lo = INT64_MAX, hi = 0; + for (int64_t t = ta; t < tb; t++) { + const sg_task_t* k = &g->tasks[t]; + for (int64_t i = 0; i < k->n; i++) { + if (SG_KIND(k->r[i]) != RAY_SYMGRP_NEW) continue; + int64_t off = g->off_of[SG_VAL(k->r[i])], end = off + 4 + k->fp[i].len; + if (off < lo) lo = off; + if (end > hi) hi = end; + } + } + sg_wb(g, lo, hi); + } + sg_wb(g, g->clo, g->chi); + g->clo = g->chi = 0; +} + +/* Records read in position order go through spans of neighbouring records + * (gaps up to SG_SPAN_GAP read through rather than sought over), cut into + * pieces read ahead at most SG_AHEAD bytes before the record being copied: + * a window's spans asked for at once are evicted again, under memory + * pressure, before they are copied, and then fault back in a page at a + * time. */ +#define SG_SPAN_GAP ((int64_t)256 << 10) +#define SG_PIECE ((int64_t)4 << 20) +#define SG_AHEAD ((int64_t)32 << 20) +typedef struct { int64_t lo, hi; } sg_span_t; +typedef struct { + sg_span_t* p; + int64_t n, cap; + int64_t next; /* the first piece not asked for */ + int64_t done; /* the first piece not behind the reader */ + int64_t ahead; /* bytes asked for, not behind */ + int64_t lo, hi; /* the span being built (hi 0: none) */ +} sg_ra_t; + +static bool sg_ra_cut(sg_ra_t* ra) { + for (int64_t a = ra->lo; a < ra->hi; a += SG_PIECE) { + if (ra->n == ra->cap) { + int64_t nc = ra->cap ? ra->cap * 2 : 256; + sg_span_t* np = (sg_span_t*)ray_sys_realloc(ra->p, (size_t)nc * sizeof(sg_span_t)); + if (!np) return false; + ra->p = np; ra->cap = nc; + } + ra->p[ra->n++] = (sg_span_t){a, ra->hi - a > SG_PIECE ? a + SG_PIECE : ra->hi}; + } + return true; +} +/* A record [off, end), records in ascending order: joined to the span or + * starting the next. False on allocation failure. */ +static bool sg_ra_add(sg_ra_t* ra, int64_t off, int64_t end, int64_t* spans) { + if (ra->hi > 0) { + if (off >= ra->lo && off - ra->hi <= SG_SPAN_GAP) { if (end > ra->hi) ra->hi = end; return true; } + if (!sg_ra_cut(ra)) return false; + } + ra->lo = off; ra->hi = end; (*spans)++; + return true; +} +static bool sg_ra_end(sg_ra_t* ra) { + bool ok = ra->hi <= 0 || sg_ra_cut(ra); + ra->lo = ra->hi = 0; + return ok; +} +/* Before the record at `off` is read: the pieces behind it dropped from + * the count, those ahead asked for up to SG_AHEAD; `bytes` counts them. */ +static void sg_ra_at(const ray_symimp_t* imp, sg_ra_t* ra, int64_t off, int64_t* bytes) { + for (;;) { + while (ra->done < ra->next && ra->p[ra->done].hi <= off) { + ra->ahead -= ra->p[ra->done].hi - ra->p[ra->done].lo; + ra->done++; + } + if (ra->done == ra->next) + while (ra->next < ra->n && ra->p[ra->next].hi <= off) { ra->next++; ra->done++; } + if (ra->next >= ra->n || (ra->next > ra->done && ra->ahead >= SG_AHEAD)) return; + int64_t len = ra->p[ra->next].hi - ra->p[ra->next].lo; + ray_symimp_willneed(imp, ra->p[ra->next].lo, len); + ra->ahead += len; *bytes += len; + ra->next++; + } +} + +/* The import dictionary's strings the logs do not hold (those direct + * passes interned before the first grouped one) into the logs: read once, + * in file order, and hashed as the grouped passes hash them. */ +bool ray_symgrp_adopt(ray_symgrp_t* g, uint64_t hmask) { + int64_t count = ray_symimp_count(g->imp), from = g->known > 1 ? g->known : 1; + if (count <= from) { if (count > g->known) g->known = count; return true; } + sg_ra_t ra = {0}; + int64_t spans = 0, read = 0; + /* to the end of the last record's bytes, as the other spans run */ + uint32_t last = 0; + (void)ray_symimp_get(g->imp, count - 1, &last); + bool ok = sg_ra_add(&ra, ray_symimp_offset(g->imp, from), ray_symimp_offset(g->imp, count - 1) + 4 + last, &spans) && + sg_ra_end(&ra); + for (int64_t pos = from; ok && pos < count; pos++) { + sg_ra_at(g->imp, &ra, ray_symimp_offset(g->imp, pos), &read); + uint32_t len; + const char* s = ray_symimp_get(g->imp, pos, &len); + uint64_t h = ray_hash_bytes(s, len) & hmask; + sg_ent_t* x = (sg_ent_t*)sg_push(&g->logs[sg_log(h)], sizeof(sg_ent_t)); + if (!x) { ok = false; break; } + *x = (sg_ent_t){h, len, (uint32_t)pos}; + g->entries++; + } + ray_sys_free(ra.p); + if (ok) { g->st.adopted += count - from; g->known = count; } + return ok; +} + +/* Whether verdict word `w` of window [ta, ..) is a candidate whose record + * the window loads (an earlier pass's or an earlier window's), and its + * position. */ +static inline bool sg_loaded(const ray_symgrp_t* g, uint64_t w, int64_t ta, uint32_t* pos) { + if (SG_KIND(w) == RAY_SYMGRP_OLD) { *pos = (uint32_t)SG_VAL(w); return true; } + if (SG_KIND(w) == RAY_SYMGRP_REF && sg_ref_task(g, SG_VAL(w)) < ta) { *pos = sg_ref_pos(g, SG_VAL(w)); return true; } + return false; +} + +/* The records the window's candidates point at from before it: positions + * (with the candidates' lengths, which their records share) sorted; those + * the previous window loaded too are copied from it (a string common in the + * column is read from the file once), the rest are read in position order + * (sg_ra_t) and copied from the file. */ +bool ray_symgrp_load(ray_symgrp_t* g, int64_t ta, int64_t tb) { + g->st.windows++; + /* the candidates counted first: arrays by the window's staged strings + * would cost 16 bytes a string of a column of new ones */ + int64_t n = 0; + uint32_t cp; + for (int64_t t = ta; t < tb; t++) + for (int64_t i = 0; i < g->tasks[t].n; i++) n += sg_loaded(g, g->tasks[t].r[i], ta, &cp); + uint64_t* a = (uint64_t*)ray_sys_alloc((size_t)(n ? n : 1) * sizeof(uint64_t)); + uint64_t* tmp = (uint64_t*)ray_sys_alloc((size_t)(n ? n : 1) * sizeof(uint64_t)); + if (g->spos && sg_inject("reload")) { ray_sys_free(a); a = NULL; } + /* failed: the previous window's copy stays with g (sg_window_free) */ + if (!a || !tmp) { ray_sys_free(a); ray_sys_free(tmp); return false; } + uint32_t* opos = g->spos; uint32_t* olen = g->slen; int64_t* ooff = g->soff; + char* obuf = g->sbuf; int64_t on = g->sn; + g->spos = NULL; g->slen = NULL; g->soff = NULL; g->sbuf = NULL; g->sn = 0; + sg_window_free(g); + int64_t m = 0; + for (int64_t t = ta; t < tb; t++) { + const sg_task_t* k = &g->tasks[t]; + for (int64_t i = 0; i < k->n; i++) + if (sg_loaded(g, k->r[i], ta, &cp)) a[m++] = ((uint64_t)cp << 32) | k->fp[i].len; + } + bool ok = sg_sort_hi(a, tmp, m); + int64_t u = 0, bytes = 0; + for (int64_t i = 0; ok && i < m; i++) + if (!u || (a[i] >> 32) != (a[u - 1] >> 32)) { a[u++] = a[i]; bytes += (uint32_t)a[i]; } + g->spos = (uint32_t*)ray_sys_alloc((size_t)(u ? u : 1) * sizeof(uint32_t)); + g->slen = (uint32_t*)ray_sys_alloc((size_t)(u ? u : 1) * sizeof(uint32_t)); + g->soff = (int64_t*)ray_sys_alloc((size_t)(u + 1) * sizeof(int64_t)); + g->sbuf = (char*)ray_sys_alloc((size_t)(bytes ? bytes : 1)); + ok = ok && g->spos && g->slen && g->soff && g->sbuf; + /* what the previous window holds (both lists ascending), marked by a + * set top bit of the length word; the rest read span by span */ + sg_ra_t ra = {0}; + int64_t j = 0; + for (int64_t i = 0; ok && i < u; i++) { + uint32_t pos = (uint32_t)(a[i] >> 32); + while (j < on && opos[j] < pos) j++; + if (j < on && opos[j] == pos) { a[i] |= UINT64_C(1) << 31; continue; } + int64_t off = ray_symimp_offset(g->imp, pos); + ok = sg_ra_add(&ra, off, off + 4 + (uint32_t)a[i], &g->st.store_spans); + } + ok = ok && sg_ra_end(&ra); + int64_t at = 0; + j = 0; + for (int64_t i = 0; ok && i < u; i++) { + uint32_t pos = (uint32_t)(a[i] >> 32), room = (uint32_t)a[i] & 0x7fffffffu, len; + const char* s; + if ((uint32_t)a[i] >> 31) { + while (opos[j] < pos) j++; + len = olen[j]; s = obuf + ooff[j]; + g->st.store_kept++; + } else { + sg_ra_at(g->imp, &ra, ray_symimp_offset(g->imp, pos), &g->st.store_read); + s = ray_symimp_get(g->imp, pos, &len); + g->st.store_pos++; g->st.store_bytes += room; + } + g->spos[i] = pos; + g->slen[i] = len; + g->soff[i] = at; + /* the candidates' length: a record of another length is no match */ + if (len == room) memcpy(g->sbuf + at, s, len); + at += room; + } + if (ok) { g->soff[u] = at; g->sn = u; } + ray_sys_free(ra.p); + ray_sys_free(a); ray_sys_free(tmp); + ray_sys_free(opos); ray_sys_free(olen); ray_sys_free(ooff); ray_sys_free(obuf); + return ok; +} + +bool ray_symgrp_same(ray_symgrp_t* g, uint32_t pos, const char* s, uint32_t len) { + int64_t lo = 0, hi = g->sn; + while (lo < hi) { int64_t mid = (lo + hi) / 2; if (g->spos[mid] < pos) lo = mid + 1; else hi = mid; } + if (lo < g->sn && g->spos[lo] == pos) + return g->slen[lo] == len && g->soff[lo + 1] - g->soff[lo] == (int64_t)len && + (len == 0 || memcmp(g->sbuf + g->soff[lo], s, len) == 0); + uint32_t rl; + const char* r = ray_symimp_get(g->imp, pos, &rl); + return rl == len && (len == 0 || memcmp(r, s, len) == 0); +} + +static bool sg_defer(ray_symgrp_t* g, uint32_t worker, int64_t t, uint32_t local, uint64_t h, + uint32_t pos, const char* s, uint32_t len, bool miss) { + if ((int64_t)worker >= g->workers) return false; + const char* kept = sg_keep(&g->db[worker], s, len); + sg_def_t* d = (sg_def_t*)sg_push(&g->dl[worker], sizeof(sg_def_t)); + if (!kept || !d) return false; + *d = (sg_def_t){t, h, kept, local, pos, len, miss}; + return true; +} +bool ray_symgrp_defer(ray_symgrp_t* g, uint32_t worker, int64_t t, uint32_t local, uint64_t h, + uint32_t pos, const char* s, uint32_t len) { + return sg_defer(g, worker, t, local, h, pos, s, len, false); +} +bool ray_symgrp_mismatch(ray_symgrp_t* g, uint32_t worker, int64_t t, uint32_t local, uint64_t h, + const char* s, uint32_t len) { + return sg_defer(g, worker, t, local, h, 0, s, len, true); +} + +/* The exact position of a string whose candidate did not match: an earlier + * string of equal hash and length, or a new record at the file's end. The + * positions it adds follow the order it is called in, so it is called from + * one thread, in an order that does not depend on the workers + * (ray_symgrp_settle). */ +static int64_t sg_collide(ray_symgrp_t* g, uint64_t h, const char* s, uint32_t len) { + pthread_mutex_lock(&g->lock); + int64_t pos = -1; + for (sg_chunk_t* c = g->logs[sg_log(h)].head; pos < 0 && c; c = c->next) + for (int64_t i = 0; i < c->n; i++) { + const sg_ent_t* x = (const sg_ent_t*)c->data + i; + if (x->h != h || x->len != len) continue; + uint32_t rl; + const char* r = ray_symimp_get(g->imp, x->pos, &rl); + if (rl == len && (len == 0 || memcmp(r, s, len) == 0)) { pos = x->pos; break; } + } + if (pos < 0) { + int64_t p0, o0; + sg_ent_t* x = NULL; + if (ray_symimp_reserve(g->imp, 1, 4 + (int64_t)len, &p0, &o0) && + (x = (sg_ent_t*)sg_push(&g->logs[sg_log(h)], sizeof(sg_ent_t)))) { + ray_symimp_put(g->imp, p0, o0, s, len); + if (g->chi <= g->clo) g->clo = o0; + g->chi = o0 + 4 + (int64_t)len; + g->st.rec_bytes += 4 + (int64_t)len; + *x = (sg_ent_t){h, len, (uint32_t)p0}; + g->entries++; g->known = p0 + 1; + pos = p0; + } + } + g->st.collisions++; + pthread_mutex_unlock(&g->lock); + return pos; +} + +static int sg_ovr_cmp(const sg_ovr_t* a, int64_t t, uint32_t local) { + return a->t != t ? (a->t < t ? -1 : 1) : a->local != local ? (a->local < local ? -1 : 1) : 0; +} + +bool ray_symgrp_settle(ray_symgrp_t* g, int64_t** redo, int64_t* nredo) { + *redo = NULL; *nredo = 0; + ray_sys_free(g->ovr); g->ovr = NULL; g->novr = 0; + int64_t n = 0; + for (int64_t w = 0; w < g->workers; w++) n += g->dl[w].n; + if (!n) return true; + /* every candidate left to compare, by position (the known mismatches + * apart) */ + sg_def_t** all = (sg_def_t**)ray_sys_alloc((size_t)n * sizeof(sg_def_t*)); + uint64_t* a = (uint64_t*)ray_sys_alloc((size_t)n * sizeof(uint64_t)); + uint64_t* tmp = (uint64_t*)ray_sys_alloc((size_t)n * sizeof(uint64_t)); + bool ok = all && a && tmp; + int64_t k = 0, nc = 0; + for (int64_t w = 0; ok && w < g->workers; w++) + for (sg_chunk_t* c = g->dl[w].head; c; c = c->next) + for (int64_t i = 0; i < c->n; i++, k++) { + all[k] = (sg_def_t*)c->data + i; + if (!all[k]->miss) a[nc++] = ((uint64_t)all[k]->pos << 32) | (uint64_t)k; + } + g->st.deferred += nc; + ok = ok && sg_sort_hi(a, tmp, nc); + sg_ra_t ra = {0}; + int64_t spans = 0; + for (int64_t i = 0; ok && i < nc; i++) { + const sg_def_t* d = all[(uint32_t)a[i]]; + int64_t off = ray_symimp_offset(g->imp, d->pos); + ok = sg_ra_add(&ra, off, off + 4 + d->len, &spans); + } + ok = ok && sg_ra_end(&ra); + int64_t cmp = 0, cmpb = 0; + for (int64_t i = 0; ok && i < nc; i++) { + sg_def_t* d = all[(uint32_t)a[i]]; + uint32_t rl; + sg_ra_at(g->imp, &ra, ray_symimp_offset(g->imp, d->pos), &g->st.settle_read); + const char* r = ray_symimp_get(g->imp, d->pos, &rl); + cmp++; cmpb += d->len; + if (rl != d->len || (d->len && memcmp(r, d->s, d->len) != 0)) d->miss = 1; + } + atomic_fetch_add_explicit(&g->compares, cmp, memory_order_relaxed); + atomic_fetch_add_explicit(&g->cmp_bytes, cmpb, memory_order_relaxed); + ray_sys_free(ra.p); + /* The mismatches, true collisions, by (task, local id): the order their + * strings first occur in the column, whichever worker ran which task, so + * the records sg_collide adds take the same positions on any pool. Two + * stable passes, local id first. */ + int64_t nm = 0; + for (int64_t i = 0; ok && i < n; i++) + if (all[i]->miss) a[nm++] = ((uint64_t)all[i]->local << 32) | (uint64_t)i; + ok = ok && sg_sort_hi(a, tmp, nm); + for (int64_t i = 0; ok && i < nm; i++) + a[i] = ((uint64_t)(uint32_t)all[(uint32_t)a[i]]->t << 32) | (uint32_t)a[i]; + ok = ok && sg_sort_hi(a, tmp, nm); + sg_ovr_t* ovr = ok && nm ? (sg_ovr_t*)ray_sys_alloc((size_t)nm * sizeof(sg_ovr_t)) : NULL; + if (nm && !ovr) ok = false; + int64_t novr = 0; + for (int64_t i = 0; ok && i < nm; i++) { + const sg_def_t* d = all[(uint32_t)a[i]]; + int64_t p = sg_collide(g, d->h, d->s, d->len); + if (p < 0) { ok = false; break; } + ovr[novr++] = (sg_ovr_t){d->t, d->local, (uint32_t)p}; + } + ray_sys_free(all); ray_sys_free(a); ray_sys_free(tmp); + for (int64_t w = 0; w < g->workers; w++) { sg_list_free(&g->dl[w]); sg_list_free(&g->db[w]); } + if (!ok) { ray_sys_free(ovr); return false; } + g->ovr = ovr; g->novr = novr; /* by (task, local id) */ + if (novr) { + int64_t* rd = (int64_t*)ray_sys_alloc((size_t)novr * sizeof(int64_t)); + if (!rd) return false; + int64_t nr = 0; + for (int64_t i = 0; i < novr; i++) if (!nr || rd[nr - 1] != ovr[i].t) rd[nr++] = ovr[i].t; + *redo = rd; *nredo = nr; + g->st.redo += nr; + } + return true; +} + +int64_t ray_symgrp_override(const ray_symgrp_t* g, int64_t t, uint32_t local) { + int64_t lo = 0, hi = g->novr; + while (lo < hi) { int64_t mid = (lo + hi) / 2; if (sg_ovr_cmp(&g->ovr[mid], t, local) < 0) lo = mid + 1; else hi = mid; } + return lo < g->novr && sg_ovr_cmp(&g->ovr[lo], t, local) == 0 ? (int64_t)g->ovr[lo].pos : -1; +} + +void ray_symgrp_note(ray_symgrp_t* g, int64_t compares, int64_t bytes) { + atomic_fetch_add_explicit(&g->compares, compares, memory_order_relaxed); + atomic_fetch_add_explicit(&g->cmp_bytes, bytes, memory_order_relaxed); +} + +void ray_symgrp_stats(ray_symgrp_t* g, ray_symgrp_stats_t* out) { + *out = g->st; + out->compares = atomic_exchange_explicit(&g->compares, 0, memory_order_relaxed); + out->cmp_bytes = atomic_exchange_explicit(&g->cmp_bytes, 0, memory_order_relaxed); + memset(&g->st, 0, sizeof(g->st)); +} + +int64_t ray_symgrp_entries(const ray_symgrp_t* g) { return g->entries; } +ray_symgrp_order_t ray_symgrp_order(const ray_symgrp_t* g) { return g->order; } + +#else /* POSIX only, as the import dictionary */ + +ray_symgrp_t* ray_symgrp_new(struct ray_symimp_s* imp, ray_symgrp_order_t order) { (void)imp; (void)order; return NULL; } +void ray_symgrp_free(ray_symgrp_t* g) { (void)g; } +bool ray_symgrp_begin(ray_symgrp_t* g, int64_t ntasks, int groups, int64_t workers) { (void)g; (void)ntasks; (void)groups; (void)workers; return false; } +bool ray_symgrp_adopt(ray_symgrp_t* g, uint64_t hmask) { (void)g; (void)hmask; return false; } +bool ray_symgrp_stage(ray_symgrp_t* g, int64_t t, int64_t n, const ray_symgrp_fp_t* fp, const uint32_t* counts) { (void)g; (void)t; (void)n; (void)fp; (void)counts; return false; } +bool ray_symgrp_resolve(ray_symgrp_t* g) { (void)g; return false; } +int64_t ray_symgrp_task_size(const ray_symgrp_t* g, int64_t t) { (void)g; (void)t; return 0; } +bool ray_symgrp_task(const ray_symgrp_t* g, int64_t t, ray_symgrp_res_t* res) { (void)g; (void)t; (void)res; return false; } +int64_t ray_symgrp_task_off(const ray_symgrp_t* g, int64_t t, bool again) { (void)g; (void)t; (void)again; return -1; } +int64_t ray_symgrp_window(const ray_symgrp_t* g, int64_t ta, int64_t budget) { (void)g; (void)budget; return ta + 1; } +void ray_symgrp_writeback(ray_symgrp_t* g, int64_t ta, int64_t tb) { (void)g; (void)ta; (void)tb; } +bool ray_symgrp_load(ray_symgrp_t* g, int64_t ta, int64_t tb) { (void)g; (void)ta; (void)tb; return false; } +bool ray_symgrp_same(ray_symgrp_t* g, uint32_t pos, const char* s, uint32_t len) { (void)g; (void)pos; (void)s; (void)len; return false; } +bool ray_symgrp_defer(ray_symgrp_t* g, uint32_t worker, int64_t t, uint32_t local, uint64_t h, uint32_t pos, const char* s, uint32_t len) { + (void)g; (void)worker; (void)t; (void)local; (void)h; (void)pos; (void)s; (void)len; return false; +} +bool ray_symgrp_settle(ray_symgrp_t* g, int64_t** redo, int64_t* nredo) { (void)g; *redo = NULL; *nredo = 0; return false; } +int64_t ray_symgrp_override(const ray_symgrp_t* g, int64_t t, uint32_t local) { (void)g; (void)t; (void)local; return -1; } +bool ray_symgrp_mismatch(ray_symgrp_t* g, uint32_t worker, int64_t t, uint32_t local, uint64_t h, const char* s, uint32_t len) { + (void)g; (void)worker; (void)t; (void)local; (void)h; (void)s; (void)len; return false; +} +void ray_symgrp_end(ray_symgrp_t* g) { (void)g; } +void ray_symgrp_note(ray_symgrp_t* g, int64_t compares, int64_t bytes) { (void)g; (void)compares; (void)bytes; } +void ray_symgrp_stats(ray_symgrp_t* g, ray_symgrp_stats_t* out) { (void)g; *out = (ray_symgrp_stats_t){0}; } +int64_t ray_symgrp_entries(const ray_symgrp_t* g) { (void)g; return 0; } +ray_symgrp_order_t ray_symgrp_order(const ray_symgrp_t* g) { (void)g; return RAY_SYMGRP_ROWS; } + +#endif diff --git a/src/table/symgrp.h b/src/table/symgrp.h new file mode 100644 index 000000000..e544be1eb --- /dev/null +++ b/src/table/symgrp.h @@ -0,0 +1,174 @@ +/* + * 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_SYMGRP_H +#define RAY_SYMGRP_H + +/* The import dictionary's grouped mode: interning a column too big for its + * dictionary to be probed at random. + * + * A pass over one column runs in three steps, the caller (the Parquet + * import) decoding the column twice: + * + * 1. every task (a row group's chunk) deduplicates its strings exactly and + * hands its distinct ones over as (hash, length, local id) only; no + * string bytes are kept between the steps; + * 2. ray_symgrp_resolve goes through the hash groups one at a time, the + * group's index (every earlier string's hash, length and position, kept + * in append-only logs) the only table it holds, and gives each staged + * string a verdict: a new string at a position of its own, or a + * candidate for an earlier string of equal hash and length; + * 3. the tasks decode again, write the new strings' records where step 2 + * placed them and compare every candidate's bytes with its record, + * length first and then bytes to the first that differs. A candidate + * pointing at an earlier pass (or an earlier window of tasks) is + * compared with a copy of its record read beforehand in position + * order (ray_symgrp_load); one pointing at a record another task of the + * window writes is compared once the window is done (ray_symgrp_defer, + * ray_symgrp_settle). A mismatch, a true hash collision, is kept for + * the window's end too (ray_symgrp_mismatch): ray_symgrp_settle gives + * the window's mismatches, in the order their strings first occur, their + * exact positions from the logs, new ones if need be, and their tasks + * write their codes again. Two different strings never share a + * position, and the positions do not depend on the workers. + * + * Nothing reads the symbol file at random but those collisions, and the + * index is touched one group at a time. POSIX only, as the import + * dictionary itself. */ + +#include +#include +#include +#include + +struct ray_symimp_s; +typedef struct ray_symgrp_s ray_symgrp_t; + +#define RAY_SYMGRP_LOG_BITS 6 /* the index logs: 64, by the hash's top bits */ +#define RAY_SYMGRP_MAX (1 << RAY_SYMGRP_LOG_BITS) + +/* The order a pass's new strings take positions in. */ +typedef enum { + RAY_SYMGRP_ROWS = 0, /* first occurrence, the strings later tasks meet + * again first: those, task by task in their rows' + * order, then the others the same way (the + * records a later window compares with lie + * together, not spread over the pass's) */ + RAY_SYMGRP_SHARDS = 1, /* hash group, then task, then first occurrence */ + RAY_SYMGRP_FREQ = 2, /* most rows first; ties by first occurrence */ + RAY_SYMGRP_ROWS_FLAT = 3,/* first occurrence: task by task, each in its rows' order */ +} ray_symgrp_order_t; + +/* A task-distinct string as step 1 saw it; local ids count from 1 (0 is the + * null and "" row, position 0, never staged). */ +typedef struct { uint64_t h; uint32_t len, local; } ray_symgrp_fp_t; + +/* Step 2's verdict on one of a task's local ids. */ +enum { RAY_SYMGRP_NEW = 1, RAY_SYMGRP_OLD = 2, RAY_SYMGRP_REF = 3 }; +typedef struct { + uint32_t pos; /* the position; for OLD and REF until the bytes are compared */ + uint32_t kind; + uint32_t owner; /* REF: the task whose NEW string it is */ + uint32_t again; /* NEW under ROWS: a later task meets it too */ + int64_t off; /* NEW: its record's file offset (-1 under ROWS and + * ROWS_FLAT: the task's records follow one another, + * in local id order, from ray_symgrp_task_off of + * `again`) */ +} ray_symgrp_res_t; + +typedef struct { + int64_t staged, groups, log_loaded, owners, old, refs; + int64_t again, again_bytes; /* ROWS: new strings later tasks meet */ + int64_t store_pos, store_spans, store_bytes; /* records read from the file */ + int64_t store_read, settle_read; /* bytes asked of the file for them */ + int64_t store_kept, windows; /* records kept from the window before */ + int64_t stage_bytes; /* the tasks' arrays: their chunks' bytes */ + int64_t rec_bytes, wb_bytes; /* records written; bytes whose writeback the windows started */ + int64_t adopted; /* strings direct passes added, taken into the logs */ + int64_t deferred, compares, cmp_bytes, collisions, redo; +} ray_symgrp_stats_t; + +ray_symgrp_t* ray_symgrp_new(struct ray_symimp_s* imp, ray_symgrp_order_t order); +void ray_symgrp_free(ray_symgrp_t* g); +ray_symgrp_order_t ray_symgrp_order(const ray_symgrp_t* g); + +/* A pass over `ntasks` tasks in `groups` hash groups (a power of two up to + * RAY_SYMGRP_MAX); `workers` bounds the worker ids given to ray_symgrp_defer. */ +bool ray_symgrp_begin(ray_symgrp_t* g, int64_t ntasks, int groups, int64_t workers); +/* Before a pass: the import dictionary's strings added outside the grouped + * passes (by direct ones, which come first) taken into the logs, hashed as + * the stage's strings are (ray_hash_bytes, `hmask` its bits kept). */ +bool ray_symgrp_adopt(ray_symgrp_t* g, uint64_t hmask); +/* Step 1: task t's distinct strings, fp[i].local == i + 1; counts[i] the + * rows of local id i + 1 (RAY_SYMGRP_FREQ; NULL otherwise). Thread-safe + * across tasks. */ +bool ray_symgrp_stage(ray_symgrp_t* g, int64_t t, int64_t n, const ray_symgrp_fp_t* fp, + const uint32_t* counts); +/* Step 2. Reserves the new strings' records in the symbol file and appends + * them to the index logs. */ +bool ray_symgrp_resolve(ray_symgrp_t* g); +/* Step 3: task t's verdicts, res[local] for local ids 1..n (n as staged). */ +int64_t ray_symgrp_task_size(const ray_symgrp_t* g, int64_t t); +bool ray_symgrp_task(const ray_symgrp_t* g, int64_t t, ray_symgrp_res_t* res); +/* RAY_SYMGRP_ROWS, ROWS_FLAT: the file offset of task t's first new record, + * of those later tasks meet again (`again`) or of the others. */ +int64_t ray_symgrp_task_off(const ray_symgrp_t* g, int64_t t, bool again); +/* The window of tasks [ta, return value) whose candidates' records stay + * within `budget` bytes (one task at least). */ +int64_t ray_symgrp_window(const ray_symgrp_t* g, int64_t ta, int64_t budget); +/* Read the records the window's candidates need from before the window, in + * position order, into memory. */ +bool ray_symgrp_load(ray_symgrp_t* g, int64_t ta, int64_t tb); +/* Whether `s` is the string at `pos`: the loaded copy if any, else the + * record in the file (written by now). */ +bool ray_symgrp_same(ray_symgrp_t* g, uint32_t pos, const char* s, uint32_t len); +/* A candidate pointing at a record another task of the window writes: + * compared by ray_symgrp_settle. `worker` < the workers of begin. */ +bool ray_symgrp_defer(ray_symgrp_t* g, uint32_t worker, int64_t t, uint32_t local, uint64_t h, + uint32_t pos, const char* s, uint32_t len); +/* A candidate compared already that did not match: its position is given + * by ray_symgrp_settle. `worker` as for ray_symgrp_defer. */ +bool ray_symgrp_mismatch(ray_symgrp_t* g, uint32_t worker, int64_t t, uint32_t local, uint64_t h, + const char* s, uint32_t len); +/* After the window: compare the deferred candidates in position order, then + * give every mismatch (those and ray_symgrp_mismatch's), by task and local + * id, its exact position: an earlier string of equal hash and length, or a + * new record. The positions are kept for ray_symgrp_override, and the + * mismatches' tasks listed in *redo (*nredo tasks, ascending) to write their + * codes again. */ +bool ray_symgrp_settle(ray_symgrp_t* g, int64_t** redo, int64_t* nredo); +/* The position settled for (t, local) after a mismatch; -1 if none. */ +int64_t ray_symgrp_override(const ray_symgrp_t* g, int64_t t, uint32_t local); +/* After the window and its codes written again: start the writeback of the + * records it wrote (and of those its collisions added). */ +void ray_symgrp_writeback(ray_symgrp_t* g, int64_t ta, int64_t tb); +/* Step 3's own comparisons, for the counts. */ +void ray_symgrp_note(ray_symgrp_t* g, int64_t compares, int64_t bytes); +/* End of the pass: its state freed, the logs kept for the next. */ +void ray_symgrp_end(ray_symgrp_t* g); +/* Counts since the last call (which resets them). */ +void ray_symgrp_stats(ray_symgrp_t* g, ray_symgrp_stats_t* out); +/* Entries in the index logs. */ +int64_t ray_symgrp_entries(const ray_symgrp_t* g); + +#endif diff --git a/src/table/symimp.c b/src/table/symimp.c new file mode 100644 index 000000000..5c0f7f564 --- /dev/null +++ b/src/table/symimp.c @@ -0,0 +1,586 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#if defined(__linux__) +# define _GNU_SOURCE +#endif +#include "symimp.h" +#include "ops/hash.h" /* ray_hash_bytes: position 0 is "" */ + +#if defined(RAY_OS_LINUX) || defined(RAY_OS_MACOS) || defined(__linux__) || defined(__APPLE__) + +#include "core/platform.h" +#include "mem/sys.h" +#include "store/fileio.h" /* ray_file_sync_dir */ +#include +#include +#include +#include /* getenv: whether the counts are kept */ +#include +#include +#include + +#define SI_MAGIC 0x4C525453U /* "STRL", the symbol file's magic */ +#define SI_HEAD 12 /* magic + count */ +#define SI_SHARD_LOG 10 +#define SI_SHARDS (1 << SI_SHARD_LOG) /* by the 64-bit hash's top bits */ +#define SI_TAB0 1024 /* initial slots per shard */ +#define SI_OFF_LOG 20 /* offsets in chunks of 2^20 */ +#define SI_OFF_CHUNKS 4096 /* 2^32 entries at most */ +#define SI_GROW_MIN ((int64_t)1 << 20) +#define SI_GROW_MAX ((int64_t)1 << 30) + +#define SI_BATCH 8192 /* strings deduplicated together */ +_Static_assert(SI_BATCH <= 65535, "a batch's dedupe slots hold uint16 indexes"); + +/* ray_symimp_stats counters: a batch sums them locally and adds them once */ +enum { SI_ST_STRINGS, SI_ST_DEDUP, SI_ST_PROBES, SI_ST_HITS, SI_ST_ADDED, + SI_ST_SLOTS, SI_ST_FALSE, SI_ST_GROWS, SI_ST_GROWB, SI_ST_N }; + +/* An index entry is (tag << 32) | (position + 1), 0 an empty slot; the tag + * is the 64-bit hash's low 32 bits, of which the low log2(slots) give the + * home slot (and the slot again in a table twice the size). The shard comes + * from the top bits, outside the tag, so two strings of one home slot are + * told apart by 32 - log2(slots) tag bits (15 at 2^17 slots) before their + * bytes are compared; a shard taken from the tag's own top bits left 10 + * fewer. */ +static inline uint32_t si_shard_of(uint64_t h) { return (uint32_t)(h >> (64 - SI_SHARD_LOG)); } +typedef struct si_tab_s { + uint64_t mask; + struct si_tab_s* next; /* retired: the next one retired with it */ + _Atomic(uint64_t) e[]; +} si_tab_t; +typedef struct { + _Atomic(si_tab_t*) tab; + int64_t used; /* under lock */ +} si_shard_t; + +struct ray_symimp_s { + int fd; + char* path; + uint8_t* map; /* the file, mapped over `reserve` bytes */ + size_t reserve; + pthread_mutex_t alock; /* every change: positions, records, the file + * size and the shard tables */ + int64_t count; + int64_t tail; /* bytes of records + header */ + int64_t fsize; /* the file's current length */ + int64_t synced; /* bytes whose writeback was started */ + _Atomic(int64_t)* count_out; + /* A replaced shard table may still be read by a lock-free lookup that + * loaded it. Lookups register in the parity of the epoch they start + * in; a table retired in epoch e is freed once the epoch has moved + * past e + 1, which it only does when no lookup of the other parity + * is left (si_reclaim). */ + _Atomic(uint64_t) epoch; + _Atomic(int64_t) active[2]; + si_tab_t* retired[2]; /* under alock, by the parity retired in */ + uint64_t* offc[SI_OFF_CHUNKS]; /* record offset of each position */ + _Atomic(bool) reserved; /* ray_symimp_reserve used: the shard + * tables no longer cover every record. + * Set under alock before active[] is + * read there; a lookup reads it after + * registering in active[] (si_batch) */ + si_shard_t shards[SI_SHARDS]; + bool stats; /* RAY_CSV_TRACE at create: the counts below are kept */ + _Atomic(int64_t) st[SI_ST_N]; /* ray_symimp_stats, past what lookups read */ +}; + +/* The slots start empty because ray_sys_alloc memory reads zero: a fresh + * anonymous mapping or a new preallocated spill file, never a recycled + * block (the contract in mem/sys.h). Zeroing them again would be a pass + * over the whole table before the rehash writes it, and on a spill file its + * dirty pages could go to disk as zeros before the rehash dirties them + * again. */ +static si_tab_t* si_tab_new(uint64_t cap) { + si_tab_t* t = (si_tab_t*)ray_sys_alloc(sizeof(si_tab_t) + (size_t)cap * sizeof(uint64_t)); + if (!t) return NULL; + t->mask = cap - 1; + t->next = NULL; + return t; +} + +static inline uint64_t si_off(const ray_symimp_t* m, int64_t pos) { + return m->offc[pos >> SI_OFF_LOG][pos & ((1 << SI_OFF_LOG) - 1)]; +} + +static inline bool si_eq(const ray_symimp_t* m, int64_t pos, const char* s, size_t len) { + const uint8_t* r = m->map + si_off(m, pos); + uint32_t l; + memcpy(&l, r, 4); + return l == len && (len == 0 || memcmp(r + 4, s, len) == 0); +} + +/* A lookup in shard table t. st NULL: no counts; si_find is inlined, so a + * caller passing NULL as such has none of them in its probe loop. */ +RAY_INLINE int64_t si_find(const ray_symimp_t* m, const si_tab_t* t, uint32_t tag, + const char* s, size_t len, int64_t* st) { + uint64_t slot = tag & t->mask; + for (;;) { + uint64_t e = atomic_load_explicit(&t->e[slot], memory_order_acquire); + if (st) st[SI_ST_SLOTS]++; + if (!e) return -1; + if ((uint32_t)(e >> 32) == tag) { + int64_t pos = (int64_t)(uint32_t)e - 1; + if (si_eq(m, pos, s, len)) return pos; + if (st) st[SI_ST_FALSE]++; + } + slot = (slot + 1) & t->mask; + } +} + +static void si_put(si_tab_t* t, uint64_t e) { + uint64_t slot = (uint32_t)(e >> 32) & t->mask; + while (atomic_load_explicit(&t->e[slot], memory_order_relaxed)) slot = (slot + 1) & t->mask; + atomic_store_explicit(&t->e[slot], e, memory_order_release); +} + +/* The file grown to `want` bytes. The blocks are allocated, where the + * filesystem can, so a full disk fails here rather than as a fault on a + * later write through the mapping. */ +static bool si_grow(ray_symimp_t* m, int64_t want) { +#if defined(__linux__) + if (fallocate(m->fd, 0, (off_t)m->fsize, (off_t)(want - m->fsize)) == 0) return true; + if (errno != EOPNOTSUPP) return false; +#endif + return ftruncate(m->fd, (off_t)want) == 0; +} + +/* Room for `bytes` more record bytes: the next position and its offset. + * The file grows ahead of the tail (the mapping covers it already). + * Under alock. */ +static bool si_reserve(ray_symimp_t* m, size_t bytes, int64_t* pos, int64_t* off) { + if (m->count >= (int64_t)UINT32_MAX - 1) return false; + int64_t p = m->count, chunk = p >> SI_OFF_LOG; + if (!m->offc[chunk]) { + m->offc[chunk] = (uint64_t*)ray_sys_alloc(((size_t)1 << SI_OFF_LOG) * sizeof(uint64_t)); + if (!m->offc[chunk]) return false; + } + if (m->tail + (int64_t)bytes > m->fsize) { + int64_t grow = m->fsize < SI_GROW_MIN ? SI_GROW_MIN : m->fsize > SI_GROW_MAX ? SI_GROW_MAX : m->fsize; + int64_t need = m->tail + (int64_t)bytes, want = need + grow; + if ((size_t)want > m->reserve) want = (int64_t)m->reserve; + if (want < need || !si_grow(m, want)) return false; + m->fsize = want; + } + *pos = p; *off = m->tail; + m->offc[chunk][p & ((1 << SI_OFF_LOG) - 1)] = (uint64_t)m->tail; + m->tail += (int64_t)bytes; + m->count = p + 1; + atomic_store_explicit(m->count_out, p + 1, memory_order_release); + return true; +} + +/* Under alock: the string is not in the shard; append it. */ +static int64_t si_add(ray_symimp_t* m, si_shard_t* sh, uint32_t tag, const char* s, size_t len, + int64_t* st) { + si_tab_t* t = atomic_load_explicit(&sh->tab, memory_order_relaxed); + if ((uint64_t)(sh->used + 1) * 2 > t->mask + 1) { + si_tab_t* nt = si_tab_new((t->mask + 1) * 2); + if (!nt) return -1; + if (st) { st[SI_ST_GROWS]++; st[SI_ST_GROWB] += (int64_t)((t->mask + 1) * sizeof(uint64_t)); } + for (uint64_t i = 0; i <= t->mask; i++) { + uint64_t e = atomic_load_explicit(&t->e[i], memory_order_relaxed); + if (e) si_put(nt, e); + } + atomic_store_explicit(&sh->tab, nt, memory_order_seq_cst); + uint64_t ep = atomic_load_explicit(&m->epoch, memory_order_relaxed) & 1; + t->next = m->retired[ep]; m->retired[ep] = t; + t = nt; + } + int64_t pos, off; + if (!si_reserve(m, 4 + len, &pos, &off)) return -1; + uint32_t l32 = (uint32_t)len; + memcpy(m->map + off, &l32, 4); + if (len) memcpy(m->map + off + 4, s, len); + si_put(t, ((uint64_t)tag << 32) | (uint64_t)(pos + 1)); + sh->used++; + if (st) st[SI_ST_ADDED]++; + return pos; +} + +/* Under alock: take the tables no lookup can still hold and move the + * epoch on, unless a lookup of the other parity is still running. The + * caller frees what it gets back after unlocking. */ +static si_tab_t* si_reclaim(ray_symimp_t* m) { + uint64_t e = atomic_load_explicit(&m->epoch, memory_order_relaxed); + if (atomic_load_explicit(&m->active[(e + 1) & 1], memory_order_seq_cst) != 0) return NULL; + si_tab_t* done = m->retired[(e + 1) & 1]; + m->retired[(e + 1) & 1] = NULL; + atomic_store_explicit(&m->epoch, e + 1, memory_order_seq_cst); + return done; +} + +/* The lock-free lookups of a batch's first occurrences; its misses. st + * NULL: no counts (inlined into each call, so that loop has none). */ +RAY_INLINE int64_t si_lookups(const ray_symimp_t* m, int64_t n, const char* const* strs, const size_t* lens, + const uint64_t* hashes, const uint16_t* first, int64_t* out_pos, int64_t* st) { + int64_t miss = 0; + for (int64_t i = 0; i < n; i++) { + if (first[i] != i) continue; + const si_shard_t* sh = &m->shards[si_shard_of(hashes[i])]; + out_pos[i] = si_find(m, atomic_load_explicit(&sh->tab, memory_order_acquire), (uint32_t)hashes[i], + strs[i] ? strs[i] : "", strs[i] ? lens[i] : 0, st); + if (st) st[SI_ST_PROBES]++; + if (out_pos[i] < 0) miss++; + } + return miss; +} + +/* Up to SI_BATCH strings. Equal strings of the batch are looked up once + * (a column's neighbouring rows repeat), each against the batch's own + * bytes rather than a record of the file. Hits are found without a lock. + * The batch's misses are added together under alock: the lock is taken + * once per batch rather than per string, and the new strings get + * neighbouring positions, as the ordinary domain's batch commit gives + * them (a column's rows then index nearby positions, which its lookups + * over the vocabulary feel). */ +static bool si_batch(ray_symimp_t* m, int64_t n, const char* const* strs, + const size_t* lens, const uint64_t* hashes, int64_t* out_pos) { + uint16_t loc[2 * SI_BATCH]; /* batch slot -> first such string + 1 */ + uint16_t first[SI_BATCH]; + uint32_t lmask = 15; + while (lmask + 1 < (uint32_t)(2 * n)) lmask = lmask * 2 + 1; + memset(loc, 0, (size_t)(lmask + 1) * sizeof(loc[0])); + for (int64_t i = 0; i < n; i++) { + size_t len = strs[i] ? lens[i] : 0; + if (len > UINT32_MAX - 4) return false; + const char* s = strs[i] ? strs[i] : ""; + uint32_t slot = (uint32_t)hashes[i] & lmask; + for (;;) { + uint16_t j1 = loc[slot]; + if (!j1) { loc[slot] = (uint16_t)(i + 1); first[i] = (uint16_t)i; break; } + int64_t j = j1 - 1; + size_t jl = strs[j] ? lens[j] : 0; + if (hashes[j] == hashes[i] && jl == len && + (len == 0 || memcmp(strs[j], s, len) == 0)) { first[i] = (uint16_t)j; break; } + slot = (slot + 1) & lmask; + } + } + int64_t miss = 0, st[SI_ST_N] = {0}; + uint64_t e; + for (;;) { + e = atomic_load_explicit(&m->epoch, memory_order_seq_cst); + atomic_fetch_add_explicit(&m->active[e & 1], 1, memory_order_seq_cst); + if (atomic_load_explicit(&m->epoch, memory_order_seq_cst) == e) break; + atomic_fetch_sub_explicit(&m->active[e & 1], 1, memory_order_release); + } + /* Registered, then the reservation read (both seq_cst, as the + * reservation's store and its read of active[] are): either the + * reservation sees this lookup and keeps the tables, or this lookup + * sees the reservation and reads none. */ + if (atomic_load_explicit(&m->reserved, memory_order_seq_cst)) { + atomic_fetch_sub_explicit(&m->active[e & 1], 1, memory_order_release); + return false; + } + /* the counts only when kept (ray_symimp_stats, RAY_CSV_TRACE at create): + * otherwise a lookup touches none of them */ + int64_t* sp = m->stats ? st : NULL; + miss = sp ? si_lookups(m,n,strs,lens,hashes,first,out_pos,st) : si_lookups(m,n,strs,lens,hashes,first,out_pos,NULL); + atomic_fetch_sub_explicit(&m->active[e & 1], 1, memory_order_release); + if (sp) { + st[SI_ST_STRINGS] = n; + st[SI_ST_DEDUP] = n - st[SI_ST_PROBES]; + st[SI_ST_HITS] = st[SI_ST_PROBES] - miss; + } + bool ok = true; + si_tab_t* done = NULL; + if (miss) { + pthread_mutex_lock(&m->alock); + /* reserved since the lookups: no string added (the tables may be gone) */ + if (atomic_load_explicit(&m->reserved, memory_order_relaxed)) ok = false; + for (int64_t i = 0; i < n && ok; i++) { + if (first[i] != i || out_pos[i] >= 0) continue; + uint32_t tag = (uint32_t)hashes[i]; + const char* s = strs[i] ? strs[i] : ""; + size_t len = strs[i] ? lens[i] : 0; + si_shard_t* sh = &m->shards[si_shard_of(hashes[i])]; + int64_t pos = si_find(m, atomic_load_explicit(&sh->tab, memory_order_relaxed), tag, s, len, sp); + if (pos < 0) pos = si_add(m, sh, tag, s, len, sp); + if (pos < 0) ok = false; + else out_pos[i] = pos; + } + done = si_reclaim(m); + pthread_mutex_unlock(&m->alock); + } + for (int k = 0; sp && k < SI_ST_N; k++) + if (st[k]) atomic_fetch_add_explicit(&m->st[k], st[k], memory_order_relaxed); + for (si_tab_t* t = done; t;) { si_tab_t* nx = t->next; ray_sys_free(t); t = nx; } + for (int64_t i = 0; ok && i < n; i++) if (first[i] != i) out_pos[i] = out_pos[first[i]]; + return ok; +} + +bool ray_symimp_intern_batch(ray_symimp_t* m, int64_t n, const char* const* strs, + const size_t* lens, const uint64_t* hashes, + int64_t* out_pos) { + /* its index misses the reserved records (si_batch checks again, safely) */ + if (atomic_load_explicit(&m->reserved, memory_order_relaxed)) return false; + for (int64_t o = 0; o < n; o += SI_BATCH) + if (!si_batch(m, n - o < SI_BATCH ? n - o : SI_BATCH, strs + o, lens + o, hashes + o, out_pos + o)) + return false; + return true; +} + +bool ray_symimp_reserve(ray_symimp_t* m, int64_t n, int64_t bytes, int64_t* pos0, int64_t* off0) { + if (n < 0 || bytes < 0) return false; + pthread_mutex_lock(&m->alock); + bool ok = m->count + n <= (int64_t)UINT32_MAX - 1 && m->tail + bytes <= (int64_t)m->reserve; + for (int64_t c = m->count >> SI_OFF_LOG; ok && n && c <= (m->count + n - 1) >> SI_OFF_LOG; c++) + if (!m->offc[c]) { + m->offc[c] = (uint64_t*)ray_sys_alloc(((size_t)1 << SI_OFF_LOG) * sizeof(uint64_t)); + ok = m->offc[c] != NULL; + } + if (ok && m->tail + bytes > m->fsize) { + int64_t want = m->tail + bytes + SI_GROW_MIN; + if ((size_t)want > m->reserve) want = (int64_t)m->reserve; + ok = si_grow(m, want); + if (ok) m->fsize = want; + } + bool first = ok && !atomic_load_explicit(&m->reserved, memory_order_relaxed); + if (first) atomic_store_explicit(&m->reserved, true, memory_order_seq_cst); + if (first && + !atomic_load_explicit(&m->active[0], memory_order_seq_cst) && + !atomic_load_explicit(&m->active[1], memory_order_seq_cst)) { + /* From the first reservation on the shard tables are never read + * again (a lookup that registers from now on sees `reserved`, one + * registered before is counted above; adds check it under alock): + * their memory goes back now, not when the dictionary is freed, + * which leaves it to the grouped passes that follow. A lookup in + * flight keeps them to ray_symimp_free. */ + for (int i = 0; i < SI_SHARDS; i++) { + ray_sys_free(atomic_load_explicit(&m->shards[i].tab, memory_order_relaxed)); + atomic_store_explicit(&m->shards[i].tab, NULL, memory_order_relaxed); + m->shards[i].used = 0; + } + for (int k = 0; k < 2; k++) { + for (si_tab_t* t = m->retired[k]; t;) { si_tab_t* nx = t->next; ray_sys_free(t); t = nx; } + m->retired[k] = NULL; + } + } + if (ok) { + *pos0 = m->count; *off0 = m->tail; + m->count += n; m->tail += bytes; + atomic_store_explicit(m->count_out, m->count, memory_order_release); + } + pthread_mutex_unlock(&m->alock); + return ok; +} + +void ray_symimp_put(ray_symimp_t* m, int64_t pos, int64_t off, const char* s, uint32_t len) { + memcpy(m->map + off, &len, 4); + if (len) memcpy(m->map + off + 4, s, len); + m->offc[pos >> SI_OFF_LOG][pos & ((1 << SI_OFF_LOG) - 1)] = (uint64_t)off; +} + +void ray_symimp_place(ray_symimp_t* m, int64_t pos, int64_t off) { + m->offc[pos >> SI_OFF_LOG][pos & ((1 << SI_OFF_LOG) - 1)] = (uint64_t)off; +} + +bool ray_symimp_write(ray_symimp_t* m, int64_t off, const void* buf, size_t n) { + const char* p = (const char*)buf; + while (n) { + ssize_t w = pwrite(m->fd, p, n, (off_t)off); + if (w < 0 && errno == EINTR) continue; + if (w <= 0) return false; + p += w; off += w; n -= (size_t)w; + } + return true; +} + +void ray_symimp_writeback(ray_symimp_t* m, int64_t off, int64_t len) { + ray_file_writeback_start(m->fd, off, len); +} + +int64_t ray_symimp_count(const ray_symimp_t* m) { + return atomic_load_explicit(m->count_out, memory_order_acquire); +} + +int64_t ray_symimp_offset(const ray_symimp_t* m, int64_t pos) { + return (int64_t)si_off(m, pos); +} + +const char* ray_symimp_get(const ray_symimp_t* m, int64_t pos, uint32_t* len) { + const uint8_t* r = m->map + si_off(m, pos); + memcpy(len, r, 4); + return (const char*)r + 4; +} + +void ray_symimp_willneed(const ray_symimp_t* m, int64_t off, int64_t len) { + size_t pg = (size_t)sysconf(_SC_PAGESIZE); + size_t lo = (size_t)off & ~(pg - 1), hi = (size_t)(off + len); + if (hi > lo) (void)madvise(m->map + lo, hi - lo, MADV_WILLNEED); +} + +ray_symimp_t* ray_symimp_create(const char* path, _Atomic(int64_t)* count) { + if (!path || !count) return NULL; + ray_symimp_t* m = (ray_symimp_t*)ray_sys_alloc(sizeof(*m)); + if (!m) return NULL; + memset(m, 0, sizeof(*m)); + atomic_init(&m->epoch, 0); + atomic_init(&m->active[0], 0); + atomic_init(&m->active[1], 0); + atomic_init(&m->reserved, false); + for (int k = 0; k < SI_ST_N; k++) atomic_init(&m->st[k], 0); + m->stats = getenv("RAY_CSV_TRACE") != NULL; /* the converters' trace: its only reader */ + m->fd = -1; + m->count_out = count; + size_t pl = strlen(path); + m->path = (char*)ray_sys_alloc(pl + 1); + if (!m->path) goto fail; + memcpy(m->path, path, pl + 1); + m->fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666); + if (m->fd < 0) goto fail; + /* Address space for the whole file up front: it only grows by ftruncate. */ + for (m->reserve = (size_t)1 << 40; m->reserve >= ((size_t)1 << 30); m->reserve >>= 2) { + void* p = mmap(NULL, m->reserve, PROT_READ | PROT_WRITE, MAP_SHARED, m->fd, 0); + if (p != MAP_FAILED) { m->map = (uint8_t*)p; break; } + } + if (!m->map) goto fail; + if (pthread_mutex_init(&m->alock, NULL) != 0) goto fail; + for (int i = 0; i < SI_SHARDS; i++) { + si_tab_t* t = si_tab_new(SI_TAB0); + if (!t) goto fail; + atomic_init(&m->shards[i].tab, t); + } + m->tail = SI_HEAD; + if (!si_grow(m, SI_GROW_MIN)) goto fail; + m->fsize = SI_GROW_MIN; + uint32_t magic = SI_MAGIC; + memcpy(m->map, &magic, 4); + memset(m->map + 4, 0, 8); + /* position 0 is the empty string, as in every symbol file */ + { + const char* e = ""; + size_t z = 0; + uint64_t h0 = ray_hash_bytes("", 0); + int64_t p0 = -1; + if (!ray_symimp_intern_batch(m, 1, &e, &z, &h0, &p0) || p0 != 0) goto fail; + } + return m; +fail: + /* the caller falls back to the ordinary domain, which must not find + * this file half made */ + if (m->fd >= 0) unlink(m->path); + ray_symimp_free(m); + return NULL; +} + +ray_err_t ray_symimp_sync(ray_symimp_t* m, bool durable) { + if (!m) return RAY_ERR_TYPE; + pthread_mutex_lock(&m->alock); + int64_t count = m->count, tail = m->tail, from = m->synced; + memcpy(m->map + 4, &count, 8); + m->synced = tail; + ray_err_t err = RAY_OK; + if (durable) { + if (ftruncate(m->fd, (off_t)tail) != 0) err = RAY_ERR_IO; + else m->fsize = tail; + } + pthread_mutex_unlock(&m->alock); + if (err != RAY_OK) return err; + if (!durable) { + ray_file_writeback_start(m->fd, from, tail - from); + /* A lookup reads one record of the written part, anywhere in it: + * no read-around there. The tail being appended keeps the default, + * so its new pages fault in by the window. */ + size_t done_bytes = (size_t)tail & ~((size_t)sysconf(_SC_PAGESIZE) - 1); + if (done_bytes) madvise(m->map, done_bytes, MADV_RANDOM); + return RAY_OK; + } + if (msync(m->map, (size_t)tail, MS_SYNC) != 0 || fsync(m->fd) != 0) return RAY_ERR_IO; + return ray_file_sync_dir(m->path); +} + +void ray_symimp_stats(ray_symimp_t* m, ray_symimp_stats_t* out) { + memset(out, 0, sizeof(*out)); + if (!m) return; + int64_t v[SI_ST_N]; + for (int k = 0; k < SI_ST_N; k++) v[k] = atomic_exchange_explicit(&m->st[k], 0, memory_order_relaxed); + out->strings = v[SI_ST_STRINGS]; out->dedup = v[SI_ST_DEDUP]; + out->probes = v[SI_ST_PROBES]; out->hits = v[SI_ST_HITS]; out->added = v[SI_ST_ADDED]; + out->slots = v[SI_ST_SLOTS]; out->false_tags = v[SI_ST_FALSE]; + out->grows = v[SI_ST_GROWS]; out->grow_bytes = v[SI_ST_GROWB]; + pthread_mutex_lock(&m->alock); + out->count = m->count; + out->rec_bytes = m->tail; + for (int i = 0; i < SI_SHARDS; i++) { + const si_tab_t* t = atomic_load_explicit(&m->shards[i].tab, memory_order_relaxed); + if (t) out->tab_bytes += (int64_t)(sizeof(si_tab_t) + (t->mask + 1) * sizeof(uint64_t)); + } + for (int c = 0; c < SI_OFF_CHUNKS; c++) + if (m->offc[c]) out->off_bytes += (int64_t)(((size_t)1 << SI_OFF_LOG) * sizeof(uint64_t)); + pthread_mutex_unlock(&m->alock); +} + +int64_t ray_symimp_index_bytes(ray_symimp_t* m) { + int64_t bytes = 0; + pthread_mutex_lock(&m->alock); + for (int i = 0; i < SI_SHARDS; i++) { + const si_tab_t* t = atomic_load_explicit(&m->shards[i].tab, memory_order_relaxed); + if (t) bytes += (int64_t)(sizeof(si_tab_t) + (t->mask + 1) * sizeof(uint64_t)); + } + pthread_mutex_unlock(&m->alock); + return bytes; +} + +void ray_symimp_free(ray_symimp_t* m) { + if (!m) return; + for (int i = 0; i < SI_SHARDS; i++) { + si_shard_t* sh = &m->shards[i]; + ray_sys_free(atomic_load_explicit(&sh->tab, memory_order_relaxed)); + } + for (int k = 0; k < 2; k++) + for (si_tab_t* t = m->retired[k]; t;) { si_tab_t* nx = t->next; ray_sys_free(t); t = nx; } + for (int c = 0; c < SI_OFF_CHUNKS; c++) ray_sys_free(m->offc[c]); + if (m->map) munmap(m->map, m->reserve); + if (m->fd >= 0) close(m->fd); + ray_sys_free(m->path); + ray_sys_free(m); +} + +#else /* no import dictionary: callers keep the ordinary domain */ + +ray_symimp_t* ray_symimp_create(const char* path, _Atomic(int64_t)* count) { (void)path; (void)count; return NULL; } +bool ray_symimp_intern_batch(ray_symimp_t* m, int64_t n, const char* const* strs, + const size_t* lens, const uint64_t* hashes, int64_t* out_pos) { + (void)m; (void)n; (void)strs; (void)lens; (void)hashes; (void)out_pos; return false; +} +ray_err_t ray_symimp_sync(ray_symimp_t* m, bool durable) { (void)m; (void)durable; return RAY_ERR_IO; } +void ray_symimp_free(ray_symimp_t* m) { (void)m; } +int64_t ray_symimp_index_bytes(ray_symimp_t* m) { (void)m; return 0; } +void ray_symimp_stats(ray_symimp_t* m, ray_symimp_stats_t* out) { (void)m; *out = (ray_symimp_stats_t){0}; } +bool ray_symimp_reserve(ray_symimp_t* m, int64_t n, int64_t bytes, int64_t* pos0, int64_t* off0) { + (void)m; (void)n; (void)bytes; (void)pos0; (void)off0; return false; +} +void ray_symimp_put(ray_symimp_t* m, int64_t pos, int64_t off, const char* s, uint32_t len) { + (void)m; (void)pos; (void)off; (void)s; (void)len; +} +void ray_symimp_place(ray_symimp_t* m, int64_t pos, int64_t off) { (void)m; (void)pos; (void)off; } +bool ray_symimp_write(ray_symimp_t* m, int64_t off, const void* buf, size_t n) { (void)m; (void)off; (void)buf; (void)n; return false; } +void ray_symimp_writeback(ray_symimp_t* m, int64_t off, int64_t len) { (void)m; (void)off; (void)len; } +int64_t ray_symimp_count(const ray_symimp_t* m) { (void)m; return 0; } +int64_t ray_symimp_offset(const ray_symimp_t* m, int64_t pos) { (void)m; (void)pos; return -1; } +const char* ray_symimp_get(const ray_symimp_t* m, int64_t pos, uint32_t* len) { (void)m; (void)pos; *len = 0; return NULL; } +void ray_symimp_willneed(const ray_symimp_t* m, int64_t off, int64_t len) { (void)m; (void)off; (void)len; } + +#endif diff --git a/src/table/symimp.h b/src/table/symimp.h new file mode 100644 index 000000000..7ca7b2d74 --- /dev/null +++ b/src/table/symimp.h @@ -0,0 +1,114 @@ +/* + * 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_SYMIMP_H +#define RAY_SYMIMP_H + +/* The import dictionary: a symbol file one converter builds alone. + * + * Interned strings are appended straight into the mapped file as its STRL + * records ([u32 len | bytes], position i = i-th record), so the file is the + * dictionary's storage: nothing is copied out at the end and its pages are + * the page cache's to write back and evict. In memory there are only the + * record offsets and a hash index split into shards; a hit is found + * without a lock, and new strings are added under one. Position 0 is "". POSIX only: + * ray_symimp_create returns NULL elsewhere, and on any failure to set up, + * and the caller keeps the ordinary domain. */ + +#include +#include +#include +#include +#include + +typedef struct ray_symimp_s ray_symimp_t; + +/* Create (truncating) the symbol file at `path`. `count` receives the + * number of entries as they are added. */ +ray_symimp_t* ray_symimp_create(const char* path, _Atomic(int64_t)* count); +/* Position of each string, adding the new ones; thread-safe. hashes[i] is + * ray_hash_bytes of strs[i], all 64 bits (shard, home slot and tag come + * from separate bits). False on allocation or file growth failure. */ +bool ray_symimp_intern_batch(ray_symimp_t* m, int64_t n, const char* const* strs, + const size_t* lens, const uint64_t* hashes, + int64_t* out_pos); +/* Write the header count and start writing back what was added since the + * last call; `durable` cuts the file to its records and syncs it. */ +ray_err_t ray_symimp_sync(ray_symimp_t* m, bool durable); +void ray_symimp_free(ray_symimp_t* m); + +/* What the interning did, for the converters' RAY_CSV_TRACE: the counts + * since the last call (which resets them), then the sizes now. The counts + * are kept only for a dictionary created under RAY_CSV_TRACE, their only + * reader (zero otherwise: the lookups then touch none of them); the sizes + * always. */ +typedef struct ray_symimp_stats_s { + int64_t strings; /* strings interned */ + int64_t dedup; /* of them repeats inside their batch */ + int64_t probes; /* lock-free lookups: each batch's distinct strings */ + int64_t hits; /* of them found */ + int64_t added; /* strings appended (the other misses were added + * by another batch in the meantime) */ + int64_t slots; /* index slots read by every lookup */ + int64_t false_tags; /* of them with the hash but another string */ + int64_t grows; /* shard tables doubled */ + int64_t grow_bytes; /* bytes of the tables rehashed into new ones */ + int64_t count; /* entries */ + int64_t rec_bytes; /* the file's records and header */ + int64_t tab_bytes; /* the shard tables */ + int64_t off_bytes; /* the record offsets */ +} ray_symimp_stats_t; +void ray_symimp_stats(ray_symimp_t* m, ray_symimp_stats_t* out); +/* The shard tables' bytes now: none from the first ray_symimp_reserve on + * (freed then, as nothing reads them after it, unless a lookup was in + * flight: kept to ray_symimp_free). */ +int64_t ray_symimp_index_bytes(ray_symimp_t* m); + +/* Records placed by the caller (table/symgrp.h, the grouped import), which + * keeps its own index: positions [*pos0, *pos0 + n) and `bytes` bytes of + * records from file offset *off0, the file grown (and its blocks allocated) + * to hold them. The records are then written with ray_symimp_put, from any + * thread, each range by one writer. From the first reserve on, + * ray_symimp_intern_batch fails and no string is added (a call in flight + * may still return what it found): its shard tables miss these records (and + * are freed then, unless a lookup is in flight). */ +bool ray_symimp_reserve(ray_symimp_t* m, int64_t n, int64_t bytes, int64_t* pos0, int64_t* off0); +void ray_symimp_put(ray_symimp_t* m, int64_t pos, int64_t off, const char* s, uint32_t len); +/* Or written by the caller with ray_symimp_write (pwrite: no page of the + * mapping is faulted in for it), its offset noted with ray_symimp_place. */ +void ray_symimp_place(ray_symimp_t* m, int64_t pos, int64_t off); +bool ray_symimp_write(ray_symimp_t* m, int64_t off, const void* buf, size_t n); +/* Start writing back file bytes [off, off + len): records the caller has + * written, ray_symimp_sync covering everything reserved at once. */ +void ray_symimp_writeback(ray_symimp_t* m, int64_t off, int64_t len); +/* Record `pos` of the file, written: its bytes (in the mapping) and length, + * and the offset of its length prefix. */ +const char* ray_symimp_get(const ray_symimp_t* m, int64_t pos, uint32_t* len); +int64_t ray_symimp_offset(const ray_symimp_t* m, int64_t pos); +/* Entries (positions) the file holds, the records written of all but those + * reserved and not yet put. */ +int64_t ray_symimp_count(const ray_symimp_t* m); +/* Ask for file bytes [off, off + len) to be read ahead (MADV_WILLNEED). */ +void ray_symimp_willneed(const ray_symimp_t* m, int64_t off, int64_t len); + +#endif diff --git a/test/main.c b/test/main.c index eebf6160e..fb49f13be 100644 --- a/test/main.c +++ b/test/main.c @@ -158,6 +158,7 @@ extern const test_entry_t repl_entries[]; extern const test_entry_t rowsel_entries[]; extern const test_entry_t runtime_entries[]; extern const test_entry_t sel_entries[]; +extern const test_entry_t select_merge_entries[]; extern const test_entry_t sort_entries[]; extern const test_entry_t splay_entries[]; extern const test_entry_t store_entries[]; @@ -203,7 +204,7 @@ static const test_entry_t* const compiled_groups[] = { pipe_entries, platform_entries, pool_entries, progress_entries, public_api_entries, - repl_entries, rowsel_entries, runtime_entries, sel_entries, + repl_entries, rowsel_entries, runtime_entries, sel_entries, select_merge_entries, sort_entries, splay_entries, store_entries, stress_eval_entries, stress_matrix_entries, diff --git a/test/rfl/agg/keyless_pool_accum.rfl b/test/rfl/agg/keyless_pool_accum.rfl index 5194ca657..e825211c5 100644 --- a/test/rfl/agg/keyless_pool_accum.rfl +++ b/test/rfl/agg/keyless_pool_accum.rfl @@ -47,3 +47,13 @@ (== (at (at B 'a7) 0) (max n)) -- true (== (at (at B 'a10) 0) (avg f)) -- true (< (abs (- (at (at B 'a13) 0) (stddev a))) 1e-9) -- true +;; float partials belong to fixed chunks of the rows, folded in chunk order, +;; not to whichever worker claimed the rows: sums whose partials overflow +;; (p) or cancel (c) give one answer on every call, here and in the vector +;; reductions +(set PB (table [p c] (list (take [1.7976931348623157e308 -1.7976931348623157e308 3.2] 131073) (take [1e16 1.0 -1e16] 131073)))) +(set PBF (fn [] (ser (list (sum (at PB 'p)) (sum (at PB 'c)) (avg (at PB 'p)) (var (+ (at PB 'c) 0.0)) (select {from: PB s: (sum p)}) (select {from: PB s: (sum p) a: (avg p)}) (select {from: PB s: (sum c) v: (var c) mx: (max p)}) (select {from: PB s: (sum p) a: (avg c) where: (> c 0)}))))) +(set PB0 (PBF)) +(set PBN 0) +(times 8 (if (all (== PB0 (PBF))) (set PBN (+ PBN 1)))) +PBN -- 8 diff --git a/test/rfl/collection/collection_branch_cov.rfl b/test/rfl/collection/collection_branch_cov.rfl index 24708f789..eb4f98f8c 100644 --- a/test/rfl/collection/collection_branch_cov.rfl +++ b/test/rfl/collection/collection_branch_cov.rfl @@ -311,14 +311,17 @@ (in "xy" (list "x" "z")) -- [true false] ;; Empty collection val (line 925-927) -(in (as 'I64 (list)) [1 2 3]) -- (list) +(in (as 'I64 (list)) [1 2 3]) -- [] +(type (in (as 'I64 (list)) [1 2 3])) -- 'B8 ;; Typed vec val vs typed vec: hashset path (lines 933-950) (in [1 2 3] [2 3 4]) -- [false true true] -;; Non-scalar results from in (lines 978-997): STR vec in STR atom -;; Each char-check returns a bool vec → results are non-scalar → LIST collect -(in (list "ab" "cd") "abcd") -- (list [true true] [true true]) +;; Non-scalar results from in: nested lists answer a bool vec each, so +;; the results are collected as a LIST. (A string element is one whole +;; value and answers a single bool.) +(in (list (list 1 2) (list 3)) [1]) -- (list [true false] [false]) +(in (list "ab" "cd") "abcd") -- [false false] ;; val_null in vec with nulls → true (line 1007) (in 0Nl (concat [0Nl 1 2] [])) -- true diff --git a/test/rfl/collection/collection_coverage.rfl b/test/rfl/collection/collection_coverage.rfl index 667012058..a8fd073d6 100644 --- a/test/rfl/collection/collection_coverage.rfl +++ b/test/rfl/collection/collection_coverage.rfl @@ -230,8 +230,17 @@ ;; ══════════════════════════════════════ ;; 24. in — empty collection val (line 848) ;; ══════════════════════════════════════ -(in [] [1 2 3]) -- (list) +(type (in [] [1 2 3])) -- 'B8 (count (in [] [1 2 3])) -- 0 +;; An empty left operand answers B8 like every other shape, so `where` +;; over it is empty instead of raising (#785). +(type (in (take [1 2] 0) [1 2 3])) -- 'B8 +(type (in (take (guid 2) 0) (guid 2))) -- 'B8 +(type (in (take [a b] 0) [a c])) -- 'B8 +(type (in (take ["a"] 0) ["a" "b"])) -- 'B8 +(type (not-in (take [1 2] 0) [1 2 3])) -- 'B8 +(where (in (take [1 2] 0) [1 2 3])) -- [] +(count (where (in (take [1 2] 0) [1 2 3]))) -- 0 ;; ══════════════════════════════════════ ;; 25. find — vec with nulls (lines 1662-1664) diff --git a/test/rfl/collection/in.rfl b/test/rfl/collection/in.rfl index 9f25838cf..93bfdd91c 100644 --- a/test/rfl/collection/in.rfl +++ b/test/rfl/collection/in.rfl @@ -53,10 +53,8 @@ (in 'a' (list "iu" "asd" 'a')) -- [true] (in "asd" (list "iu" "asd")) -- [false false false] (in "asd" (list 'd' "asd")) -- [false false true] -(in (list "asd") (list "iu" "asd")) -- (list [false false false]) -;;(list true); -(in (list "asd" "iu") "asd") -- (list [true true true] [false false]) -;;(list false false); +(in (list "asd") (list "iu" "asd")) -- [true] +(in (list "asd" "iu") "asd") -- [true false] (set l (guid 2)) (in l l) -- [true true] (set l (guid 2)) (in (first l) l) -- true (set l (guid 2)) (in l (first l)) -- [true false] @@ -83,7 +81,8 @@ ;; Test with equal lengths (in [1h 2h 3h] [3h 2h 1h]) -- [true true true] ;; Test with empty arrays -(in (list) [1h 2h]) -- (list) +(in (list) [1h 2h]) -- [] +(type (in (list) [1h 2h])) -- 'B8 ;; ========== TEXT (SYM/STR) NULL SEMANTICS (#593) ========== ;; `in` admits the typed verdict-LUT kernel unless BOTH sides carry a null: @@ -184,8 +183,10 @@ (in [2000.01.01D00:00:00.000000000 0Np] [2000.01.01]) -- [false false] (in [00:00:00.001] [2000.01.01D00:00:00.000000001]) -- [false] -;; same with nulls on both sides: only null equals null -(in [2000.01.01 0Nd] [0Ni 0i]) -- [false true] +;; same with nulls on both sides: a date null is not an int null, as a +;; date is never an int (rayforce 1 answered the same) +(in [2000.01.01 0Nd] [0Ni 0i]) -- [false false] +(in [2000.01.01 0Nd] [0Nd]) -- [false true] ;; same-type temporal still matches, with or without nulls (in [2000.01.01 0Nd 2000.01.03] [2000.01.03]) -- [false false true] @@ -217,3 +218,145 @@ ;; a large set of narrow ints against a narrow column (sum (in (as 'I32 (til 1000)) (as 'I32 (* 3 (til 100))))) -- 100 (sum (in (as 'I16 (til 1000)) (as 'I16 (* 3 (til 100))))) -- 100 + +;; ========== STRING COLUMNS ========== +;; A string element of a collection is one whole value. Against a list of +;; strings or a string atom each element answered per character — a list of +;; per-character vectors that `where` refused — and inside a query the +;; executor refused any string column with nyi. A lone string atom on the +;; left still answers per character, as above. +(in ["p" "qq"] (list "qq" "zz")) -- [false true] +(in ["p" "qq"] "qq") -- [false true] +(in ["p" "qq" ""] (list "qq" 1 'zz)) -- [false true false] +(not-in ["p" "qq"] (list "qq" "zz")) -- [true false] +(in (list "ab" "c") "c") -- [false true] +(in (list "ab" 1) (list "ab" 1)) -- [true true] +(in (list (list "ab") "c") "c") -- (list [false] true) +;; a bool answer first and a vector answer later still collect as a list — +;; each later answer was read as a bool, so a vector stood in by its length +(in (list "c" ["x" "x"]) "c") -- (list true [false false]) +(not-in (list "c" ["x" "x"]) "c") -- (list false [true true]) +(in (list "zz" (list "c")) "c") -- (list false [true]) +(in (list 1 (list 1 2)) 1) -- (list true [true false]) +(in (list 1 2 (list 3 1)) [1]) -- (list true false [false true]) +(in "ab" (list "a" "b" "c")) -- [true true] + +(set TS (table [s n] (list ["p" "qq" "zz" ""] [1 2 3 4]))) +(at (select {from: TS where: (in s ["qq" "zz"])}) 'n) -- [2 3] +(at (select {from: TS where: (in s (list "qq" "zz"))}) 'n) -- [2 3] +(at (select {from: TS where: (in s "qq")}) 'n) -- [2] +;; the empty string is the string null: it matches nothing, even itself, +;; and not-in leaves it out too, as for every other column type +(at (select {from: TS where: (not-in s ["qq" "zz"])}) 'n) -- [1] +(at (select {from: TS where: (in s ["qq" ""])}) 'n) -- [2] +(at (select {from: TS where: (in s (take ["a"] 0))}) 'n) -- [] +;; a string atom against the column is one verdict for every row +(count (select {from: TS where: (in "qq" s)})) -- 4 +(count (select {from: TS where: (in "xx" s)})) -- 0 +(at (select {from: TS by: (in s ["qq"]) c: (count n)}) 'c) -- [3 1] +;; a projection answers one verdict per row too, and does not drag the +;; projections beside it into per-character answers +(at (select {c: (in s (list "qq" "zz")) from: TS}) 'c) -- [false true true false] +(at (select {c: (not-in s (list "qq")) from: TS}) 'c) -- [true false true false] +(at (select {c: (in s "qq") d: (in s (list "x")) from: TS}) 'c) -- [false true false false] +(at (select {c: (in s (list "qq")) from: TS where: (> n 1)}) 'c) -- [true false false] +(at (update {c: (in s (list "qq")) from: TS}) 'c) -- [false true false false] +;; A projection the compiler declines still sorts by a column it does not +;; output — the key is carried for the sort (it raised nyi) ... +(at (select {c: (in s (list "qq")) from: TS desc: n}) 'c) -- [false false true false] +(at (select {c: (in s (list "qq")) from: TS asc: n take: 2}) 'c) -- [false true] +(at (select {c: (in s (list "qq")) from: TS where: (> n 1) desc: n}) 'c) -- [false false true] +(at (select {c: (reverse n) from: TS desc: n}) 'c) -- [1 2 3 4] +(key (select {c: (in s (list "qq")) from: TS desc: [s n]})) -- ['c] +;; ... and a by: aggregate over such an argument is evaluated per group (it +;; raised "failed to compile aggregation argument") +(set TG (table [s g n] (list ["p" "qq" "zz" "" "qq"] [1 1 2 2 2] [1 2 3 4 5]))) +(at (select {c: (sum (in s (list "qq"))) from: TG by: g}) 'c) -- [1 1] +(at (select {c: (sum (in s (list "qq"))) m: (max n) from: TG by: g}) 'm) -- [2 5] +(at (select {c: (count (in s (list "qq" "zz"))) from: TG by: g where: (> n 1)}) 'c) -- [1 3] + +;; Known bugs found alongside, not fixed here: +;; (at (select {c: (sum (in s (list "qq"))) from: TG by: (> n 2)}) 'c) -- [1 1] ;; xfail BUG: an aggregate evaluated per group needs one column group key; a computed or multi-column key errors "could not resolve scalar group key symbol" (also (sum (reverse n))) +;; Name resolution inside a query (planned binder work), not `in` itself: +;; (at (select {c: (in 's (list 's)) from: TS}) 'c) -- [true] ;; xfail BUG: a quoted symbol that names a column reads the column, here and in (== y 'y) or {c: 'y} +;; (do (set in concat) (at (select {c: (in s "!") from: TS}) 'c)) -- ["p!" "qq!" "zz!" "!"] ;; xfail BUG: select still compiles a rebound `in` as membership + +;; ========== NULLS OF DIFFERENT TYPES ========== +;; Two nulls are equal where two values of their types can be: the same +;; type, or both numeric (0Nl and 0Ni, as 1 and 1i). A symbol null, the +;; empty string, an integer null, a date null and the untyped null are +;; different values, as 'a, "a", 1 and a date are — rayforce 1 answered so. +;; Every null used to equal every other one, and distinct collapsed them. +(in [' 'a] "") -- [false false] +(in [0Nl 1] "") -- [false false] +(in ['a '] [""]) -- [false false] +(in [0Nl 1] [""]) -- [false false] +(in (list 0Nl ') (list "")) -- [false false] +(in (list null 1) [0Nl]) -- [false false] +(in "" ['a ']) -- false +(in 0Nd [0Nl]) -- false +;; within a type, and across numeric widths, null still matches null +(in [' 'a] [']) -- [true false] +(in [0Nl 1] [0Nl]) -- [true false] +(in [0Nl 1] [0Ni]) -- [true false] +(in [0Nl] [0Nf]) -- [true] +(in ' ['a ']) -- true +(in ["" "a"] [""]) -- [true false] +(count (distinct (list ' "" 0Nl null))) -- 4 +(count (distinct (list 0Nl 0Ni ' '))) -- 2 +(count (except (list ' "" 0Nl) (list ""))) -- 2 +(count (sect (list ' "" 0Nl) (list 0Ni))) -- 1 +;; find follows the same rule +(find ['a '] "") -- 0Nl +(find ["a" ""] ') -- 0Nl +(find [2024.01.01 0Nd] 0Nl) -- 0Nl +(find [2024.01.01 0Nd] 0Nd) -- 1 +(find [1 0Nl] 0Ni) -- 1 +(find ['a '] ') -- 1 + +;; ... nested under another verb too: a string cell bound for one row is +;; one value, so (in cell set) is one verdict wherever it sits +(at (select {c: (not (in s (list "qq"))) from: TS}) 'c) -- [true false true true] +(at (select {c: (and (in s (list "qq")) (> n 1)) from: TS}) 'c) -- [false true false false] +(at (select {c: (if (in s (list "qq")) 1 0) from: TS}) 'c) -- [0 1 0 0] +(at (select {c: ((fn [x] (in x (list "qq"))) s) from: TS}) 'c) -- [false true false false] +(at (select {c: (in s (list "qq" 'zz 1)) from: TS}) 'c) -- [false true false false] +;; a set the compiler cannot take as a constant (an element computed at run +;; time) is evaluated row by row, and each string cell still answers once +(at (select {c: (not (in s (list "qq" (concat "z" "z")))) from: TS}) 'c) -- [true false false true] +(at (select {c: (if (in s (list (concat "q" "q"))) 1 0) from: TS}) 'c) -- [0 1 0 0] +;; the mark that makes a cell one value lasts for its row only: a cell the +;; projection hands back inside a list or a dict is a plain string after +(set TQ (table [s n] (list ["qq" "ab"] [1 2]))) +(set RQ (select {c: (list s) from: TQ})) +(in (first (first (at RQ 'c))) "q") -- [true true] +(set RQ2 (select {c: (dict [k] (list s)) from: TQ})) +(in (at (first (at RQ2 'c)) 'k) (list "q")) -- [true true] +;; a lone string literal in a query still answers per character, per row +(at (select {c: (in "ab" (list "a" "b")) from: TS take: 1}) 'c) -- (list [true true]) +;; a set held in a global list is read by the evaluator, not taken for a column +(set SETL (list "qq" "zz")) +(at (select {from: TS where: (in s SETL)}) 'n) -- [2 3] +(at (select {c: (in s SETL) from: TS}) 'c) -- [false true true false] +(set SETY (list 'qq 'zz)) +(set TYS (table [y n] (list ['p 'qq 'zz] [1 2 3]))) +(at (select {from: TYS where: (in y SETY)}) 'n) -- [2 3] +;; a LIST column's cell may be a vector: no verdict per row, a clean error +(set TLS (table [l n] (list (list ["a" "b"] "a" ["c"]) [1 2 3]))) +(select {from: TLS where: (in l ["a"])}) !- nyi + +;; a column of another type against a string set matches no row, as bare +(set TY (table [y n] (list ['p 'qq] [1 2]))) +(in ['p 'qq] ["qq"]) -- [false false] +(count (select {from: TY where: (in y ["qq"])})) -- 0 +(count (select {from: TY where: (not-in y ["qq"])})) -- 2 +(count (select {from: TY where: (in n ["qq"])})) -- 0 + +;; a mapped (splayed) string column answers the same +(.sys.exec "rm -rf rf_in_str") -- 0 +(.db.splayed.set "rf_in_str/" TS) +(set TM (.db.splayed.get "rf_in_str/")) +(at (select {from: TM where: (in s ["qq" "zz"])}) 'n) -- [2 3] +(at (select {from: TM where: (in s (list "zz"))}) 'n) -- [3] +(set TM 0) +(.sys.exec "rm -rf rf_in_str") -- 0 diff --git a/test/rfl/group/sparse_count_stride.rfl b/test/rfl/group/sparse_count_stride.rfl new file mode 100644 index 000000000..01094e18d --- /dev/null +++ b/test/rfl/group/sparse_count_stride.rfl @@ -0,0 +1,33 @@ +;; Issue #740: the sparse-dynamic count fill and merge must use the same +;; padded worker stride. The key span exceeds the legacy dense-array floor +;; (262144), and >262144 rows enable the parallel fill. The computed SUM +;; with an armed count emit filter keeps this query on the legacy ladder. +;; Small-domain COUNT queries use other paths and cannot cover this code. +;; +;; Include symbol 0, irregular counts, and four boosted groups so the top-5 +;; cutoff has no ties. Compare all output columns with a full grouping, +;; sorted and truncated only after materialization (no count emit filter). + +(set i740 (til 300000)) +(set d740 (as 'SYM (concat [""] (as 'STR (+ 1000000 (til 270000)))))) +(set k740 (* (% (* i740 i740) 270001) (as 'I64 (!= 0 (% i740 17))))) +(set boost740 (concat (concat (take [1] 100) (take [4] 200)) (concat (take [9] 300) (take [16] 400)))) +(set t740 (table [s v] (list (at d740 (concat k740 boost740)) (% (* (til 301000) 13) 97)))) + +(set full740 (select {from: t740 by: s c: (count v) s2: (sum (* v 2))})) +(sum (at full740 'c)) -- 301000 +(== (sum (at full740 's2)) (* 2 (sum (at t740 'v)))) -- true +(set expected740 (take (xdesc full740 'c) 5)) +(at expected740 'c) -- [17649 403 303 203 103] +(set top740 (select {from: t740 by: s c: (count v) s2: (sum (* v 2)) desc: c take: 5})) +(count top740) -- 5 +(all (== (at top740 's) (at expected740 's))) -- true +(all (== (at top740 'c) (at expected740 'c))) -- true +(all (== (at top740 's2) (at expected740 's2))) -- true + +;; A HAVING count threshold uses the same fill without a top-N limit. +(set having740 (select {from: (select {from: t740 by: s c: (count v) s2: (sum (* v 2))}) where: (> c 100) desc: c})) +(count having740) -- 5 +(all (== (at having740 's) (at expected740 's))) -- true +(all (== (at having740 'c) (at expected740 'c))) -- true +(all (== (at having740 's2) (at expected740 's2))) -- true diff --git a/test/rfl/integration/error.rfl b/test/rfl/integration/error.rfl index dd221e251..4107bc2d2 100644 --- a/test/rfl/integration/error.rfl +++ b/test/rfl/integration/error.rfl @@ -6,3 +6,13 @@ (try (raise "error") (fn [e] 99)) -- 99 ;; ========== NESTED TRY ========== (try (try (raise "inner") (fn [e] (raise "outer"))) (fn [e] 42)) -- 42 +;; ========== TRY INSIDE A FUNCTION ========== +;; A runtime error hands the handler 0 inside a function as at the top +;; level. The compiled path handed it the error object itself, which is +;; not refcounted: a handler returning it rethrew it, and none freed it. +(try (+ 1 'a) (fn [e] e)) -- 0 +((fn [x] (try (+ x 'a) (fn [e] e))) 1) -- 0 +((fn [x] (try (+ x 'a) (fn [e] (type e)))) 1) -- 'i64 +((fn [x] (try (raise x) (fn [e] (+ e 1)))) 1) -- 2 +((fn [x] (try (try (raise x) (fn [e] (raise (+ e 10)))) (fn [e] e))) 1) -- 11 +((fn [x] (try (+ x 'a) 7)) 1) -- 7 diff --git a/test/rfl/join/asof_clause_fallback.rfl b/test/rfl/join/asof_clause_fallback.rfl index a2ada23ed..2702c7f64 100644 --- a/test/rfl/join/asof_clause_fallback.rfl +++ b/test/rfl/join/asof_clause_fallback.rfl @@ -83,16 +83,20 @@ ;; ════════════════════════════════════════════════════════════════════════════ ;; §C asc: — sort is whole-rowset → MUST fall back (delta 0), MUST NOT stream. -;; `(select {asc:… from: PARTED})` is itself unmaterialisable in the eager -;; path (a PRE-EXISTING lazy-sort-over-parted limitation), so the flat -;; fallback surfaces that error LOUDLY rather than silently streaming a -;; per-day-sorted (wrong) result. A loud error ≫ a silent wrong answer. -;; Before the fix this would instead STREAM (delta > 0) and return a value. +;; The flat fallback sorts the whole parted quote table (it used to fail +;; with `type` there: the flat sort read parted columns as plain ones) and +;; equals the flat oracle. Before the fix this would instead STREAM +;; (delta > 0), sorting each day on its own. ;; ════════════════════════════════════════════════════════════════════════════ +(set ORac (asof-join [Sym Time] Tall (select {asc: Bid from: Qall}))) (set Bac (at (.sys.mem) 'asof-perpart-runs)) -(asof-join [Sym Time] (select {Sym: Sym Time: Time Price: Price from: Pt}) (select {asc: Bid from: Pq})) !- type +(set RSac (asof-join [Sym Time] (select {Sym: Sym Time: Time Price: Price from: Pt}) (select {asc: Bid from: Pq}))) (set Aac (at (.sys.mem) 'asof-perpart-runs)) (- Aac Bac) -- 0 +(count RSac) -- (count ORac) +(at RSac 'Bid) -- (at ORac 'Bid) +(at RSac 'Price) -- (at ORac 'Price) +(at RSac 'Bid) -- (as 'F64 [100.0]) ;; ════════════════════════════════════════════════════════════════════════════ ;; §D where: — row-preserving → STILL STREAMS (delta > 0), and stays correct. diff --git a/test/rfl/join/null_key_equality.rfl b/test/rfl/join/null_key_equality.rfl index 67db307b7..40ad69cb1 100644 --- a/test/rfl/join/null_key_equality.rfl +++ b/test/rfl/join/null_key_equality.rfl @@ -12,11 +12,9 @@ ;; * left-join filled a null payload for a left row whose null key DID have a ;; match on the right, instead of returning that match. ;; -;; null == null is the rule the rest of the runtime already applies to key -;; columns: `distinct` keeps exactly one null (test/rfl/null/distinct.rfl), -;; group-by folds nulls into a single group, and `in`/atom_eq answer true for -;; two nulls (collection.c). As-of join is the ONE documented exception and is -;; unchanged -- pinned at the bottom. +;; null == null, between key types a join compares at all (pinned below). +;; As-of join is the ONE documented exception and is unchanged -- pinned at +;; the bottom. ;; ── The reported reproduction ───────────────────────────────────────────── ;; A left-join miss produces a null V; anti-joining the result against ITSELF @@ -86,6 +84,20 @@ (at (anti-join [k] NKPROBE NKBIG) 'p) -- [3] (count (anti-join [k] NKBIG NKBIG)) -- 0 +;; ── Two nulls pair where two values of their key types are compared. A +;; join reads every key that is not a string or a guid as a raw integer, +;; so a timestamp 5 meets an integer 5 — and their nulls meet too: a join +;; must not match the values yet refuse the nulls. Numeric nulls of +;; different widths pair as well. ─────────────────────────────────────── +(set NKY (table [k y] (list [0Nl 5] [10 20]))) +(set NKT (table [k a] (list (as 'TIMESTAMP [0 5]) [1 2]))) +(at (left-join [k] NKT NKY) 'y) -- [0Nl 20] +(set NKT2 (table [k a] (list [2024.01.01D00:00:00.000000000 0Np] [1 2]))) +(at (left-join [k] NKT2 NKY) 'y) -- [0Nl 10] +(set NKI (table [k y] (list [0Ni 7i] [30 40]))) +(set NKL2 (table [k a] (list [0Nl 7] [1 2]))) +(at (left-join [k] NKL2 NKI) 'y) -- [30 40] + ;; ── As-of join is the documented exception and is NOT changed. Its merge ;; walk skips null-keyed right rows and lets null-keyed left rows fall ;; through to the left-outer null fill; it never routes through @@ -93,3 +105,6 @@ (set NKAT (table [S Time Price] (list (as 'SYM ["" "b"]) [10:00:01.000 10:00:01.000] (as 'F64 [1.0 2.0])))) (set NKAQ (table [S Time Bid] (list (as 'SYM ["" "b"]) [10:00:00.000 10:00:00.000] (as 'F64 [99.0 88.0])))) (at (asof-join [S Time] NKAT NKAQ) 'Bid) -- (as 'F64 [0Nf 88.0]) + +;; Known bug found alongside, not fixed here (rayforce 1 answered [0 40 10 20 30]): +;; (at (left-join [k] (table [k x] (list (list [9] 'b "s" 7 'a) [1 2 3 4 5])) (table [k y] (list (list [9] "s" 7 'a 'b) [0 10 20 30 40]))) 'y) -- [0 40 10 20 30] ;; xfail BUG: a LIST key column is compared and hashed by cell pointer, not value, so rows pair wrongly diff --git a/test/rfl/lang/closure_locals.rfl b/test/rfl/lang/closure_locals.rfl new file mode 100644 index 000000000..2bb53430d --- /dev/null +++ b/test/rfl/lang/closure_locals.rfl @@ -0,0 +1,507 @@ +;; closure_locals.rfl — a compiled closure resolves names as the tree walker +;; does. Its captures are locals of its body (bound before the body runs), so +;; a `let` of a captured name rebinds it for that call, a capture named like a +;; builtin is the callee, `self` is the closure itself, and a caller's local +;; of the same name never stands in for a capture. A closure compiles on its +;; second call, so every shape is called twice. + +;; a let of a captured name writes the capture's slot +(set mk (fn [c] (fn [] (times 3 (let c (+ c 1))) c))) +(set m1 (mk 0)) +(m1) -- 3 +(m1) -- 3 +(set mk2 (fn [c] (fn [flag] (if flag (let c 5) 0) c))) +(set m2 (mk2 7)) +(m2 false) -- 7 +(m2 false) -- 7 +(m2 true) -- 5 +(m2 false) -- 7 +(set mkw (fn [c] (fn [] (let n 0) (while (and (< c 3) (< n 1000)) (let c (+ c 1)) (let n (+ n 1))) (list c n)))) +(set mw (mkw 0)) +(mw) -- [3 3] +(mw) -- [3 3] + +;; a capture named like a builtin is the callee +(set mkc (fn [count] (fn [x] (count x)))) +(set cc (mkc (fn [v] 42))) +(cc [1 2 3]) -- 42 +(cc [1 2 3]) -- 42 +(set mkf (fn [first] (fn [xs] (first xs)))) +(set ff (mkf last)) +(ff [1 2 3]) -- 3 +(ff [1 2 3]) -- 3 +;; so is a parameter or a let of that name, in any compiled lambda +(set pc (fn [count x] (count x))) +(pc (fn [v] 42) [1 2 3]) -- 42 +(pc (fn [v] 42) [1 2 3]) -- 42 +(set lc (fn [x] (let count (fn [v] 7)) (count x))) +(lc [1 2]) -- 7 +(lc [1 2]) -- 7 + +;; self inside a closure is the closure, not its maker +(set mkwalk (fn [k] (fn [node] (if (== (type node) 'LIST) (sum (map self node)) (* node k))))) +(set wk (mkwalk 10)) +(wk (list 1 (list 2 3) 4)) -- 100 +(wk (list 1 (list 2 3) 4)) -- 100 +;; and a bare self is the running lambda in any compiled body +(set walk (fn [node] (if (== (type node) 'LIST) (sum (map self node)) (* node 10)))) +(walk (list 1 (list 2 3) 4)) -- 100 +(walk (list 1 (list 2 3) 4)) -- 100 + +;; a caller's local of the same name does not reach into the closure's windows +(set g3 ((fn [c] (fn [] (map (fn [z] (+ z c)) [1 2]))) 10)) +(do (let c 99) (g3)) -- [11 12] +(do (let c 99) (g3)) -- [11 12] +(set T (table [x] (list [1 2 3 4 5 6]))) +(set q3 ((fn [c] (fn [] (count (select {from: T where: (> x c)})))) 4)) +(do (let c 0) (q3)) -- 2 +(do (let c 0) (q3)) -- 2 + +;; more captures than a frame has slots: the closure stays on the tree walker +;; and still sees every capture, never a global of the same name +(set a299 -1) +(set src (raze (concat (concat (enlist "(fn [] ") (map (fn [i] (concat (concat "(let a" (format "%" i)) (concat (concat " " (format "%" i)) ") "))) (til 300))) (enlist "(fn [] (+ a0 a299)))")))) +(set big (eval (parse src))) +(set bc (big)) +(bc) -- 299 +(bc) -- 299 + +;; return ends the body on the first (interpreted) call as on the compiled one +(set mkr (fn [a] (fn [x] (return (+ a x)) 0))) +(set fr (mkr 1)) +(fr 1) -- 2 +(fr 1) -- 2 +;; a return inside try is not an error the handler sees +(set mkt (fn [a] (fn [x] (try (return (+ a x)) (fn [e] 'caught)) 0))) +(set ft (mkt 1)) +(ft 1) -- 2 +(ft 1) -- 2 +;; a return inside a special form the compiler hands to the tree walker +(set fa (fn [x] (and (return 7) x) 0)) +(fa 1) -- 7 +(fa 1) -- 7 +;; outside any lambda, return is its value +(return 5) -- 5 + +;; every call of a closure runs the same compiled body: a let inside do +;; writes the function's slot on the first call as on the next +(set mkd (fn [k] (fn [] (let r 0) (do (let r k)) r))) +(set d1 (mkd 5)) +(list (d1) (d1) (d1)) -- [5 5 5] +(set mkq (fn [k] (fn [n] (let r 0) (do (let r k)) (if (== n 0) r (+ r (self (- n 1))))))) +(set rr (mkq 10)) +(list (rr 2) (rr 2) (rr 2)) -- [30 30 30] +;; a let of a builtin name that did not run leaves the builtin +(set fc (fn [flag xs] (if flag (let count (fn [v] 42)) 0) (count xs))) +(fc false [1 2 3]) -- 3 +(fc true [1 2 3]) -- 42 +(fc false [1 2 3]) -- 3 +;; a parameter shadows a capture of its name +(set sh ((fn [c] (fn [c] (* c 2))) 100)) +(list (sh 1) (sh 1) (sh 1)) -- [2 2 2] +;; only the captures a body mentions take slots, so recursion depth does not +;; shrink with the bindings in scope +(set mk10 (fn [a b c d e f g h i j] (fn [n] (if (== n 0) j (+ 1 (self (- n 1))))))) +(set f10 (mk10 1 2 3 4 5 6 7 8 9 10)) +(f10 100) -- 110 +(set src50 (raze (list "(fn [" (raze (map (fn [i] (format "a% " i)) (til 50))) "] (fn [n] (if (== n 0) a49 (+ 1 (self (- n 1))))))"))) +(set mk50 (eval (parse src50))) +(set f50 (eval (parse (raze (list "(mk50 " (raze (map (fn [i] (format "% " i)) (til 50))) ")"))))) +(f50 100) -- 149 +;; a lazy value is materialized when captured, so the closure can run twice +(set c1 ((fn [v] (fn [] (at v 0))) (asc [3 1 2]))) +(list (c1) (c1)) -- [1 1] +;; closures made from one literal share its bytecode: a second one adds only +;; its own object and captures, not a private compiled body +(set mkb (fn [k] (fn [v] (let a (+ v k)) (let b (* a 2)) (- b 1)))) +(set b1 (mkb 1)) +(set b2 (mkb 2)) +(list (b1 1) (b2 1)) -- [3 5] +(< (- (.mem.objsize (list b1 b2)) (.mem.objsize b1)) 600) -- true +;; a lazy value captured by interpreted code is materialized as well +(set c2 (do (let v (asc [3 1 2])) (fn [] (at v 0)))) +(list (c2) (c2)) -- [1 1] + +;; a capture whose let did not run is unbound inside the closure: the global +;; of that name, or a name error, never a silent zero +(set scale 10) +(set fsc (fn [xs flag] (if flag (let scale 2)) (map (fn [v] (* v scale)) xs))) +(fsc [1 2 3] false) -- [10 20 30] +(fsc [1 2 3] true) -- [2 4 6] +(fsc [1 2 3] false) -- [10 20 30] +(set fq (fn [flag] (if flag (let q 2)) ((fn [] q)))) +(fq false) !- name +(fq true) -- 2 +;; eval and resolve inside a compiled body see its locals and captures +(set mke (fn [y] (fn [] (eval (parse "y"))))) +((mke 7)) -- 7 +(set y 100) +((mke 7)) -- 7 +(set fres (fn [a] (resolve 'a))) +(fres 3) -- 3 +;; closures capture lexically: a caller's locals are not the body's, whether +;; the maker runs compiled or interpreted +(set yl 1) +(set mkl1 (fn [] (fn [] yl))) +((do (let yl 5) (mkl1))) -- 1 +(set mkl2 (fn [] (if false (set 1 2)) (fn [] yl))) +((do (let yl 5) (mkl2))) -- 1 +;; a lazy value reaching a literal's window from a compiled frame is +;; materialized when captured (the literal falls back to the tree walker) +(set c3 ((fn [v] (fn [] (if false (set 1 2)) (at v 0))) (asc [3 1 2]))) +(list (c3) (c3)) -- [1 1] +;; a literal nested far deeper than the template compiler follows still works +(set base (parse "(fn [] k)")) +(set wrap (fn [inner] (concat (take base 2) (enlist inner)))) +(set build (fn [n] (let a (parse "k")) (times n (let a (wrap a))) a)) +(nil? ((eval (concat (take (parse "(fn [k] 0)") 2) (enlist (build 2000)))) 7)) -- false +;; closures made by interpreted code share a template per literal and capture +;; set too: two capture sets from one literal each keep their own values, and +;; a second closure from the same literal adds no private bytecode +(set mkd (fn [flag k] (if false (set 1 2)) (if flag (let extra 1)) (fn [] (list k (try extra 'none))))) +(set dd1 (mkd true 1)) +(set dd2 (mkd false 2)) +(list (dd1) (dd2) (dd1) (dd2)) -- (list [1 1] (list 2 'none) [1 1] (list 2 'none)) +(set mk3 (fn [k] (if false (set 1 2)) (fn [] (+ k 1)))) +(set ee1 (mk3 1)) +(set ee2 (mk3 2)) +(list (ee1) (ee2)) -- [2 3] +;; (made in one expression, so both carry the same source info) +(do (set ee3 (mk3 3)) (set ee4 (mk3 4)) (ee3) (ee4) (< (- (.mem.objsize (list ee3 ee4)) (.mem.objsize ee3)) 500)) -- true +;; the shared template belongs to one literal: literals built for eval from +;; the same parsed pieces, sharing their parameter, first and last nodes but +;; differing in between, each get their own +(set pfn (parse "(fn [x] (+ 0 0) (+ x 0))")) +(set mkev (fn [k] (eval (concat (take pfn 3) (list (parse (concat "(set gev " (concat (format "%" k) ")"))) (at pfn 3)))))) +(list ((mkev 1) 5) gev ((mkev 2) 5) gev ((mkev 1) 5) gev) -- [5 1 5 2 5 1] + +;; eval's window opens after its arguments: a return, a let or a call in an +;; argument belongs to the frame, and the window is gone when the frame is +(set pw 100) +(set rdw (fn [] pw)) +(set gw (fn [pw] (eval (if (> pw 0) (return 5) (quote pw))))) +(list (gw 1) pw (rdw)) -- [5 100 100] +(set pw 200) +(list pw (rdw)) -- [200 200] +(set fw2 (fn [x] (eval (do (let x 10) 0)) x)) +(fw2 1) -- 10 +(set xw 100) +(set rxw (fn [] xw)) +(set fw3 (fn [x] (eval (rxw)))) +(fw3 1) -- 100 +;; the window binds the frame's locals for the evaluated text only: a named +;; function that text calls sees the global, as it does when called directly +(set pe 100) +(set rde (fn [] pe)) +(set rde2 (fn [x] (+ x pe))) +((fn [pe] (eval (quote (rde)))) 1) -- 100 +((fn [pe] (eval (parse "(rde)"))) 1) -- 100 +((fn [pe] (eval (quote (map rde2 [1 2])))) 1) -- [101 102] +((fn [pe] (eval (quote (list pe (rde))))) 1) -- [1 100] +;; ... an interpreted lambda that text calls as well +(set rdi (fn [] (if false (set 1 2)) pe)) +((fn [pe] (eval (quote (rdi)))) 1) -- 100 +;; ... while a lambda written in the text captures it +((fn [pe] (eval (quote ((fn [] pe))))) 1) -- 1 +;; ... nor when a named function compiles on that first call: the builtins it +;; bakes are the globals, not the window's locals of those names +(set rdce (fn [x] (count x))) +((fn [count] (eval (quote (rdce [1 2 3])))) sum) -- 3 +(rdce [1 2 3]) -- 3 +;; ... however deep: a window ends the text's scope, so text a callee hands +;; to the tree walker (eval, resolve, a query, a fn literal) never reaches a +;; window further down, whether or not the callee has locals of its own +(set pn 100) +(set Tn (table [x] (list [1 2 3]))) +(set bn0 (fn [] (eval (quote (+ pn 0))))) +((fn [pn] (eval (quote (bn0)))) 1) -- 100 +(set bn1 (fn [q] (eval (quote (+ q pn))))) +((fn [pn] (eval (quote (bn1 0)))) 1) -- 100 +(set bn2 (fn [q] (resolve 'pn))) +((fn [pn] (eval (quote (bn2 0)))) 1) -- 100 +(set bnq (fn [] (at (select {r: (+ x pn) from: Tn}) 'r))) +((fn [pn] (eval (quote (bnq)))) 1) -- [101 102 103] +(set bnf (fn [] (fn [] (if false (set 1 2)) pn))) +((fn [pn] (eval (quote ((bnf))))) 1) -- 100 +;; ... through every load a callee's body makes: a name past 256 constants, +;; and a let slot read before its let ran +(set bnw (fn [] 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 pn)) +((fn [pn] (eval (quote (bnw)))) 1) -- 100 +(set bnl (fn [x] (if (> x 5) (let pn 0) 0) pn)) +((fn [pn] (eval (quote (bnl 1)))) 1) -- 100 +;; ... and through a helper a query in the text inlines, while the query +;; text itself sees the window +(set hpn (fn [v] (+ v pn))) +(at ((fn [pn] (eval (quote (select {r: (hpn x) from: Tn})))) 1) 'r) -- [101 102 103] +(at ((fn [pn] (eval (quote (update {r: (hpn x) from: Tn})))) 1) 'r) -- [101 102 103] +(set hpc (fn [v] (if (> v 0) (+ v pn) 0))) +(at ((fn [pn] (eval (quote (select {r: (hpc x) from: Tn})))) 1) 'r) -- [101 102 103] +(at ((fn [pn] (eval (quote (select {r: (+ x pn) from: Tn})))) 1) 'r) -- [2 3 4] +(set inn (fn [v] (+ v 100))) +(set hpi (fn [v] (inn v))) +(at ((fn [inn] (eval (quote (select {r: (hpi x) from: Tn})))) (fn [v] 0)) 'r) -- [101 102 103] +;; ... and (quote x) where quote is a parameter, a capture, a let or a nested +;; parameter is a call: x is captured +(set incq (fn [v] (+ v 1))) +(set mkq1 (fn [quote x] (fn [] (quote x)))) +((mkq1 incq 41)) -- 42 +(set mkq2 (fn [q x] (fn [] (let quote q) (quote x)))) +((mkq2 incq 41)) -- 42 +(set mkq3 (fn [x] (fn [quote] (quote x)))) +((mkq3 41) incq) -- 42 +(set mkq4 (fn [quote x] (if false (set 1 2)) (fn [] (quote x)))) +((mkq4 incq 41)) -- 42 +((fn [x] ((fn [] (quote x)))) 41) -- 'x +;; quoted text names nothing a closure captures for, but eval reaches it all +(((fn [kq] (fn [] (eval (quote (+ kq 0))))) 7)) -- 7 +(((fn [kq] (fn [] (list (quote kq) (eval (quote (+ kq 1)))))) 7)) -- (list 'kq 8) +;; ... and many such calls leave the scope stack as it was +(times 200 (gw 1)) +(do (let aw 1) aw) -- 1 +;; a closure body resolves the names it does not capture when it runs, so a +;; global rebound between two closures from one literal is seen by the second +(set gb sum) +(set rb []) +(times 2 (do (set kb (fn [x] (gb x))) (set rb (concat rb (kb [1 2 3]))) (set gb count))) +rb -- [6 3] +(set gb count) +(set mkb2 (fn [] (if false (set 1 2)) (fn [x] (gb x)))) +(set cb1 (do (let gb sum) (mkb2))) +(set cb2 (mkb2)) +(list (cb1 [1 2 3]) (cb2 [1 2 3]) ((mkb2) [1 2 3])) -- [3 3 3] +(set gb sum) +(set mkb3 (fn [] (fn [x] (gb x)))) +(set cb3 (mkb3)) +(set gb count) +(set cb4 (mkb3)) +(list (cb3 [1 2 3]) (cb4 [1 2 3])) -- [3 3] +;; a lambda with no captures bakes the builtins it names on its first call, +;; not when the literal is evaluated: a rebinding in between is seen +(set g6 sum) +(set f6 (fn [x] (g6 x))) +(set g6 count) +(f6 [1 2 3]) -- 3 +;; ... through a dict too, whether the dict or its entry is rebound +(set D6 (dict ['f] (list sum))) +(set r6 []) +(times 2 (do (set r6 (concat r6 ((fn [x] (D6.f x)) [1 2 3]))) (set D6 (dict ['f] (list count))))) +r6 -- [6 3] +(set D6 (dict ['f] (list sum))) +(set r6 []) +(times 2 (do (set r6 (concat r6 ((fn [x] (D6.f x)) [1 2 3]))) (set D6.f count))) +r6 -- [6 3] +(set h6 (fn [x] (D6.f x))) +(set D6.f sum) +(h6 [1 2 3]) -- 6 +;; lambdas of one literal with nothing captured share the bytecode compiled +;; at the first one's first call while the builtins it baked are unchanged +(set qlit (list)) +(times 2 (set qlit (concat qlit (enlist (fn [x] (let a (+ x 1)) (let b (* a 2)) (- b 1)))))) +(list ((first qlit) 1) ((last qlit) 1)) -- [3 3] +(< (- (.mem.objsize qlit) (.mem.objsize (first qlit))) 600) -- true +;; a closure of the same literal is not a definition: it resolves its builtins +;; when it runs, never through the bytecode a definition of that text baked +(set litD (parse "(fn [x] (gD x))")) +(set gD sum) +(set fD (eval litD)) +(fD [1 2 3]) -- 6 +(set gD count) +(set cD ((fn [y] (eval litD)) 0)) +(cD [1 2 3]) -- 3 +;; and keeps them from then on, as a named function always has +(set D6.f count) +(h6 [1 2 3]) -- 6 +(set g6 sum) +(f6 [1 2 3]) -- 3 +;; a closure body names a builtin it resolves when it runs: rebound to a +;; lambda, or to a builtin of another arity, the call follows the new value +(set g7 count) +(set mk7 (fn [k] (fn [x] (g7 x)))) +(set c7 (mk7 0)) +(c7 [1 2]) -- 2 +(set g7 (fn [v] 42)) +(c7 [1 2]) -- 42 +(set g7 (fn [v] (if false (set 1 2)) 43)) +(c7 [1 2]) -- 43 +(set g7 enlist) +(c7 [1 2]) -- (enlist [1 2]) +(set g8 +) +(set mk8 (fn [k] (fn [x y] (g8 x y)))) +(set c8 (mk8 0)) +(c8 1 2) -- 3 +(set g8 (fn [a b] (* a b))) +(c8 3 4) -- 12 +(set g8 list) +(c8 3 4) -- [3 4] +;; a closure body finds the global it names however the global table moves: +;; deleting an earlier global shifts the later ones, a deleted name is a name +;; error, a new binding of it is found again, and a caller's local of that +;; name, outside any compiled frame, stands in as it does on the tree walker +(set gm1 count) +(set gm2 sum) +(set mkm (fn [k] (fn [x] (gm2 x)))) +(set cm9 (mkm 0)) +(cm9 [1 2 3]) -- 6 +(del gm1) +(cm9 [1 2 3]) -- 6 +(del gm2) +(cm9 [1 2 3]) !- name +(set gm2 count) +(cm9 [1 2 3]) -- 3 +(set gm2 sum) +(cm9 [1 2 3]) -- 6 +(do (let gm2 (fn [v] 99)) (cm9 [1 2 3])) -- 99 +(cm9 [1 2 3]) -- 6 +;; ... and a call whose callee kind changes between calls takes the general +;; call: a unary builtin, a variadic one, a lambda; data is not callable +(set gk1 count) +(set mkk (fn [k] (fn [x] (gk1 x)))) +(set ck9 (mkk 0)) +(list (ck9 [1 2]) (do (set gk1 enlist) (ck9 [1 2])) (do (set gk1 (fn [v] 7)) (ck9 [1 2]))) -- (list 2 (enlist [1 2]) 7) +(set gk1 [10 20 30]) +(ck9 1) !- type +(set gk2 +) +(set mkk2 (fn [k] (fn [x y] (gk2 x y)))) +(set ck29 (mkk2 0)) +(list (ck29 1 2) (do (set gk2 -) (ck29 1 2)) (do (set gk2 list) (ck29 1 2)) (do (set gk2 (fn [a b] 5)) (ck29 1 2))) -- (list 3 -1 [1 2] 5) +(set gk3 list) +(set mkk3 (fn [k] (fn [x y z] (gk3 x y z)))) +(set ck39 (mkk3 0)) +(list (ck39 1 2 3) (do (set gk3 (fn [a b c] (+ a (+ b c)))) (ck39 1 2 3))) -- (list [1 2 3] 6) +;; ... ser takes the generic null there too, as on the tree walker +(set mks (fn [k] (fn [x] (ser x)))) +(== (type ((mks 0) null)) 'NULL) -- false +;; ... between any two calls: a caller's let rebound in the same frame, a global +;; set and set back +(set gc1 sum) +(set mkgc (fn [k] (fn [x] (gc1 x)))) +(set cgc (mkgc 0)) +(set rgc (fn [] (if false (set 1 2)) (let gc1 sum) (let a (cgc [1 2 3])) (let gc1 count) (list a (cgc [1 2 3])))) +(rgc) -- [6 3] +(list (cgc [1 2 3]) (do (set gc1 count) (cgc [1 2 3])) (do (set gc1 sum) (cgc [1 2 3]))) -- [6 3 6] +(set rgc2 (fn [] (if false (set 1 2)) (let a (cgc [1 2 3])) (do (let gc1 count) (cgc [1 2 3])))) +(rgc2) -- 3 +;; a literal built around a large constant is not kept alive by the table +(set baseL (parse "(fn [x] 0)")) +(set bigL (fn [i] (eval (concat (take baseL 2) (enlist (concat (parse "(+ x)") (enlist (+ i (til 100000))))))))) +(set heapL (fn [] (at (.sys.mem) 'bytes-allocated))) +(set bsL (map bigL (til 4))) +(set bsL 0) +(set h0L (do (.sys.gc) (heapL))) +(set bsL (map bigL (til 300))) +(set bsL 0) +(.sys.gc) +(< (- (heapL) h0L) 4000000) -- true +;; ... literals each just under the per-literal bound share one budget +(set bigM (fn [i] (eval (concat (take baseL 2) (enlist (concat (parse "(+ x)") (enlist (+ i (til 7000))))))))) +(set bsL (map bigM (til 4))) +(set bsL 0) +(set h0L (do (.sys.gc) (heapL))) +(set bsL (map bigM (til 300))) +(set bsL 0) +(.sys.gc) +(< (- (heapL) h0L) 4000000) -- true +;; ... and a long string counts by its bytes +(set bigS (fn [i] (eval (concat (take baseL 2) (enlist (concat (parse "(+ (count x))") (enlist (format "%" (+ i (til 20000)))))))))) +(set bsL (map bigS (til 4))) +(set bsL 0) +(set h0L (do (.sys.gc) (heapL))) +(set bsL (map bigS (til 300))) +(set bsL 0) +(.sys.gc) +(< (- (heapL) h0L) 4000000) -- true +;; ... and so do a table, a lambda with its captures, a slice's parent and a +;; string vector's characters, spliced into the text as constants +(set spliceL (fn [c] (eval (concat (take baseL 2) (enlist (concat (parse "(+ (count x))") (enlist (concat (parse "(count)") (enlist c))))))))) +(set mkTb (fn [i] (spliceL (table [a] (list (+ i (til 50000))))))) +(set mkLm (fn [i] (let c (+ i (til 50000))) (spliceL (list (fn [] c))))) +(set mkSl (fn [i] (spliceL (take (dict (take ['a 'b] (+ i 50000)) (til (+ i 50000))) [0 2])))) +(set SVl (as 'STR (map (fn [i] (format "a long string, number %, padded out to a length well past the inline size" i)) (til 1500)))) +(set mkSv (fn [i] (spliceL (concat SVl (as 'STR (list (format "%" i))))))) +(set heldL (fn [mk] (set bsL (map mk (til 4))) (set bsL 0) (.sys.gc) (let h (heapL)) (set bsL (map mk (til 300))) (set bsL 0) (.sys.gc) (- (heapL) h))) +(< (heldL mkTb) 2000000) -- true +(< (heldL mkLm) 2000000) -- true +(< (heldL mkSl) 2000000) -- true +(< (heldL mkSv) 2000000) -- true +;; the count stops at the bound, so its work is bounded too: a table whose +;; cells share one list, or hold a list shared 2^30 times over, costs the +;; literal's first call next to nothing +(set dagL (fn [n] (let L (list 1)) (times n (let L (list L L))) L)) +(set fdag (spliceL (table [a] (list (list (dagL 30)))))) +(< (timeit (fdag 1)) 1000) -- true +(set cellL (map (fn [i] (if (== 0 (% i 2)) i (format "%" i))) (til 2000))) +(set fcell (spliceL (table [c] (list (map (fn [i] cellL) (til 20000)))))) +(< (timeit (fcell 1)) 1000) -- true +;; a body nested past the compiler's depth guard (2048 levels) is left to the +;; tree walker instead of recursing further down the C stack. a chain of +;; nested if's shows which engine ran: the compiled body runs it as jumps and +;; returns the parameter, the tree walker recurses per level and stops at its +;; depth limit (512). 2500 is past the guard yet within the bytecode jump +;; range, so the shape pins the guard; the depths stay well within what +;; every platform's sanitizer build builds and releases +(set wrapI (fn [inner] (concat (take (parse "(if true 0)") 2) (enlist inner)))) +(set buildI (fn [n] (let a (parse "x")) (times n (let a (wrapI a))) a)) +(set mkI (fn [n] (eval (concat (take (parse "(fn [x] 0)") 2) (enlist (buildI n)))))) +((mkI 600) 1) -- 1 +((mkI 1500) 1) -- 1 +((mkI 2500) 1) !- limit +;; a closure body nested past the capture walk's guard (1024 levels) keeps its +;; captures: it compiles with every capture bound, never with a captured name +;; resolved as a global (the global kd here); past the compiler's own guard +;; it is left to the tree walker, which stops at its depth limit +(set wrapK (fn [inner] (concat (take (parse "(if true 0)") 2) (enlist inner)))) +(set buildK (fn [n] (let a (parse "(+ kd x)")) (times n (let a (wrapK a))) a)) +(set mkK (fn [n] (eval (concat (take (parse "(fn [kd] 0)") 2) (enlist (concat (take (parse "(fn [x] 0)") 2) (enlist (buildK n)))))))) +(set kd 5000) +(((mkK 600) 100) 1) -- 101 +(((mkK 1100) 100) 1) -- 101 +(((mkK 2000) 100) 1) -- 101 +(((mkK 2500) 100) 1) !- limit +;; closures made from one literal match by capture set in either order +(set mkd2 (fn [flag k] (if false (set 1 2)) (if flag (let extra2 1)) (fn [] (list k (try extra2 'none))))) +(set dd3 (mkd2 false 2)) +(set dd4 (mkd2 true 1)) +(list (dd3) (dd4) (dd3) (dd4)) -- (list (list 2 'none) [1 1] (list 2 'none) [1 1]) +;; a closure body resolves builtins when it runs, through the VM's general +;; call: elementwise arithmetic, aggregates and concat keep their semantics +(set mkar (fn [k] (fn [v] (* v k)))) +(set far (mkar 2)) +(list (far [1 2 3]) (far 4)) -- (list [2 4 6] 8) +(set mkav (fn [k] (fn [v] (- v (avg v))))) +((mkav 0) [1 2 3 4]) -- [-1.5 -0.5 0.5 1.5] +(set mkcc (fn [k] (fn [v] (concat v k)))) +((mkcc 'z) ['a 'b]) -- ['a 'b 'z] +(set mkmx (fn [k] (fn [v] (+ (max v) k)))) +((mkmx 1) [3 9 2]) -- 10 +;; ... and the generic null rule for a unary builtin: only nil?, type and ser +;; take the null, any other raises a type error, as on the tree walker +(set mkn (fn [k] (fn [v] (count v)))) +((mkn 0) null) !- type +((mkn 0) null) !- type +(set mkn2 (fn [k] (fn [v] (list (nil? v) (type v))))) +((mkn2 0) null) -- (list true 'null) +(set dn (dict ['a 'b] (list 1 null))) +(set mkn3 (fn [k] (fn [key0] (first (at dn key0))))) +((mkn3 0) 'b) !- type +((mkn3 0) 'a) -- 1 +;; a top-level helper keeps elementwise arithmetic on a column +(set hn2 (fn [v] 1 (* v 2))) +(hn2 [1 2 3]) -- [2 4 6] +(set Tar (table [x k] (list [1 2 3 4] [1 1 2 2]))) +(at (update {v: (+ (sum (hn2 (+ x 1))) (count (distinct x))) by: k from: Tar}) 'v) -- [12 12 20 20] +;; quote set globally to a function: (quote x) in a closure body is a call +;; through it, so x is captured, whoever made the closure and however often +;; it is called (the builtin binding is restored after) +(set qsave quote) +(set quote (fn [x] (* x 100))) +(quote 2) -- 200 +(set mkqg (fn [x] (fn [] (quote x)))) +((mkqg 3)) -- 300 +(set mkqgi (fn [x] (if false (set 1 2)) (fn [] (quote x)))) +((mkqgi 3)) -- 300 +(set cqg (mkqg 4)) +(list (cqg) (cqg)) -- [400 400] +(set mkqg2 (fn [x y] (fn [] (+ y (quote x))))) +((mkqg2 3 1)) -- 301 +(set quote qsave) +(quote x) -- 'x diff --git a/test/rfl/mem/closure_flags_release.rfl b/test/rfl/mem/closure_flags_release.rfl new file mode 100644 index 000000000..20ebd74d8 --- /dev/null +++ b/test/rfl/mem/closure_flags_release.rfl @@ -0,0 +1,16 @@ +;; closure_flags_release.rfl — a lambda made inside a query owns a vector of +;; capture row flags beside its closure; releasing the lambda must release it. +;; +;; Same method as the other probes in this directory: warm up, then two equal +;; windows of calls; the second must not move `bytes-allocated` by more than a +;; few KB. The conditional on the cell makes the projection row by row, so +;; each call makes one such lambda per row (400 rows), and the lambda +;; captures `w`, a local that derives from the row, so it carries a flag +;; vector; one leaked vector per lambda is far over the bound. +(set T (table [v] (list (as 'STR (map (fn [i] (format "%" i)) (til 400)))))) +(set h (fn [v] (let w v) (if (nil? v) "" ((fn [a] (concat a w)) v)))) +(set heapb (fn [] (at (.sys.mem) 'bytes-allocated))) +(set probe (fn [f warm reps] (do (map f (til warm)) (map f (til reps)) (set h0 (heapb)) (map f (til reps)) (< (- (heapb) h0) 4096)))) +(probe (fn [i] (count (select {r: (h v) from: T}))) 5 40) -- true +;; the result is still the row-wise join +(at (select {r: (h v) from: T take: 2}) 'r) -- ["00" "11"] diff --git a/test/rfl/mem/query_input_release.rfl b/test/rfl/mem/query_input_release.rfl index 80d4c0c0c..fe80e7772 100644 --- a/test/rfl/mem/query_input_release.rfl +++ b/test/rfl/mem/query_input_release.rfl @@ -17,6 +17,78 @@ (set heapb (fn [] (at (.sys.mem) 'bytes-allocated))) (set probe (fn [f warm reps] (do (map f (til warm)) (map f (til reps)) (set h0 (heapb)) (map f (til reps)) (< (- (heapb) h0) 4096)))) +;; Peak memory of selects over a parted table, measured first in this file: +;; the peak counter starts with the file, so nothing larger run before hides +;; a query's own peak. A grouped select with no outputs, or a sort without +;; by:, reads the columns its clauses name and gathers the others at the rows +;; it keeps; whatever the number of groups or rows kept, its peak stays +;; below what flattening the table costs (the table, then its rows again for +;; the result). +;; 22 columns, 8 partitions of 5000 rows: Bmw bytes flattened. +(.sys.exec "rm -rf /tmp/rfl_ckmw") +(set Nmw 5000) +(set mkmw (fn [p] (table (concat ['k 'lo] (as 'SYMBOL (map (fn [j] (format "c%" j)) (til 20)))) (concat (list (+ (* p Nmw) (til Nmw)) (% (til Nmw) 10)) (map (fn [j] (as 'I32 (+ j (til Nmw)))) (til 20)))))) +(map (fn [p] (do (.db.splayed.set (format "/tmp/rfl_ckmw/2024.01.0%/t/" (+ p 1)) (mkmw p)) 0)) (til 8)) +(set Pmw (.db.parted.get "/tmp/rfl_ckmw/" 't)) +(set Bmw (* (* 8 Nmw) 96)) +;; a sort without by: taking 3 rows reads the key and those 3 rows only +(set pk0 (at (.sys.mem) 'peak-bytes)) +(at (select {from: Pmw desc: k take: 3}) 'k) -- [39999 39998 39997] +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true +;; the same with outputs that leave the sort key out +(set pk0 (at (.sys.mem) 'peak-bytes)) +(at (select {k: k c3: c3 from: Pmw desc: c5 take: 3}) 'k) -- [4999 9999 14999] +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true +;; 10 groups: well under a flatten +(set pk0 (at (.sys.mem) 'peak-bytes)) +(count (select {by: lo from: Pmw})) -- 10 +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true +;; the same keyed by a by-dict of a builtin call +(set pk0 (at (.sys.mem) 'peak-bytes)) +(count (select {by: {kk: (+ lo 1)} from: Pmw})) -- 10 +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true +;; a key the planner cannot lower flattens only the columns the select reads +(set pk0 (at (.sys.mem) 'peak-bytes)) +(count (select {c: (count k) by: (reverse lo) from: Pmw})) -- 10 +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true +;; as a by-dict value too +(set pk0 (at (.sys.mem) 'peak-bytes)) +(count (select {c: (count k) by: {kk: (reverse lo)} from: Pmw})) -- 10 +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true +;; every key unique: the result is the whole table, and little more +(set pk0 (at (.sys.mem) 'peak-bytes)) +(count (select {by: k from: Pmw})) -- 40000 +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ (* 3 Bmw) 2)) -- true +(select {by: k from: Pmw desc: k take: 3}) -- (select {by: k from: (select {from: Pmw where: (>= k 0)}) desc: k take: 3}) +(.sys.exec "rm -rf /tmp/rfl_ckmw") +;; A wide string column the select never reads costs nothing near its +;; flattened size (14 MB here when the whole table was flattened). +(.sys.exec "rm -rf /tmp/rfl_ckwide") +(set Wck (concat "wide-unused-string-column-value-over-twelve-bytes-" (as 'STR (% (til 10000) 1000)))) +(set Kck (% (til 10000) 10)) +(map (fn [d] (do (.db.splayed.set (format "/tmp/rfl_ckwide/2024.01.0%/t/" d) (table [k w] (list Kck Wck))) 0)) [1 2 3 4 5 6 7 8]) +(set Wck 0) +(set Kck 0) +(set Pw (.db.parted.get "/tmp/rfl_ckwide/" 't)) +(set pk0 (at (.sys.mem) 'peak-bytes)) +(set Rw (select {by: k from: Pw})) +(< (- (at (.sys.mem) 'peak-bytes) pk0) 1000000) -- true +(count Rw) -- 10 +(at Rw 'w) -- (concat "wide-unused-string-column-value-over-twelve-bytes-" (as 'STR (til 10))) +(.sys.exec "rm -rf /tmp/rfl_ckwide") +;; A where: before a computed key filters only the columns the clauses +;; read, also when it reads a config dict: 22 columns, 60000 rows (Bfw +;; bytes), nearly every row kept; filtering every column costs Bfw again. +(set Nfw 60000) +(set FWq (table (as 'SYMBOL (map (fn [j] (format "c%" j)) (til 22))) (map (fn [j] (+ j (til Nfw))) (til 22)))) +(set Bfw (* (* 22 Nfw) 8)) +(set cfgq {lim: 100}) +(set pk0 (at (.sys.mem) 'peak-bytes)) +(count (select {n: (count c0) by: {g: (% c0 7)} from: FWq where: (> c1 (at cfgq 'lim))})) -- 7 +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bfw 2)) -- true +(set FWq 0) + + ;; partitioned + ordered, trailing frame (the shape of the report) (probe (fn [p] (count (window {from: (mk p) part: [instrument] order: [rid] frame: 2 funcs: {prev: (first v) n: (count v)}}))) 5 60) -- true ;; no part/order: the whole table is one partition @@ -33,6 +105,110 @@ (probe (fn [p] (count (select {from: (mk p) where: (> rid 3) asc: v}))) 5 60) -- true (probe (fn [p] (count (select {from: (mk p) by: instrument s: (sum v) asc: s}))) 5 60) -- true (probe (fn [p] (count (select {from: (mk p) by: instrument s: (sum v) desc: s take: 3}))) 5 60) -- true +;; a grouped select with a where: and no outputs: the fused filter keeps a +;; reference to its selection for the count(distinct) scatter, released at +;; the end of the select, which the no-output branch returns before. One +;; selection per call, empty result included. +(set TW (table [x y] (list (% (til 100) 7) (til 100)))) +(probe (fn [p] (count (select {by: x from: TW where: (> y 38)}))) 5 1000) -- true +(probe (fn [p] (count (select {by: (* x 2) from: TW where: (> y 38)}))) 5 1000) -- true +(probe (fn [p] (count (select {by: x from: TW where: (> y 1000)}))) 5 1000) -- true +;; a by-dict or a quoted key symbol is rewritten into an owned symbol vector, +;; released at the end of the select, which the no-output branch and the +;; eval-level grouping return before. One vector per call. +(set TB (table [x y z s] (list (% (til 100) 7) (til 100) (% (til 100) 3) (as 'STR (% (til 100) 7))))) +(probe (fn [p] (count (select {by: {k: x} from: TB}))) 5 1000) -- true +(probe (fn [p] (count (select {by: 'x from: TB}))) 5 1000) -- true +(probe (fn [p] (count (select {by: 'x from: TB where: (> y 38)}))) 5 1000) -- true +(probe (fn [p] (count (select {by: {a: x b: z} from: TB}))) 5 1000) -- true +(probe (fn [p] (count (select {v: y by: {k: s} from: TB}))) 5 1000) -- true +;; the same selection on the error returns of a grouped select with a where: +;; (a rejected aggregate, a bad take:, a failing post-pass, a failing +;; count(distinct) scatter). Each call is caught by try; the growth of a +;; bare caught raise is subtracted, so only the select's own is measured. +(set grow (fn [f warm reps] (do (map f (til warm)) (map f (til reps)) (set h0 (heapb)) (map f (til reps)) (- (heapb) h0)))) +(set probe_caught (fn [f warm reps] (< (- (grow f warm reps) (grow (fn [p] (try (raise p) (fn [e] 0))) warm reps)) 4096))) +(set V100 (% (til 100) 5)) +(probe_caught (fn [p] (try (select {t: (top y 0) by: x from: TB where: (> y 38)}) (fn [e] 0))) 5 1000) -- true +(probe_caught (fn [p] (try (select {s: (sum y) by: x from: TB where: (> y 38) take: "a"}) (fn [e] 0))) 5 1000) -- true +(probe_caught (fn [p] (try (select {r: (+ (sum y) [1 2 3]) by: x from: TB where: (> y 38)}) (fn [e] 0))) 5 1000) -- true +(probe_caught (fn [p] (try (select {d: (count (distinct z)) by: V100 from: TB where: (> y 38)}) (fn [e] 0))) 5 1000) -- true +;; the owned by: symbol vector on the error returns of a by-dict or a quoted +;; key: ray_select_impl releases it, whichever exit the select took +(probe_caught (fn [p] (try (select {t: (top y 0) by: {k: x} from: TB}) (fn [e] 0))) 5 1000) -- true +(probe_caught (fn [p] (try (select {s: (sum y) by: {k: x} from: TB take: "a"}) (fn [e] 0))) 5 1000) -- true +(probe_caught (fn [p] (try (select {r: (+ (sum y) [1 2 3]) by: {k: x} from: TB}) (fn [e] 0))) 5 1000) -- true +(probe_caught (fn [p] (try (select {t: (top y 0) by: 'x from: TB}) (fn [e] 0))) 5 1000) -- true +;; a key the compiler rejects leaves its error on the graph, and freeing the +;; graph released it as a value, which an error is not: a by-dict value, a +;; by-dict value with no column, an eval-level computed key +(probe_caught (fn [p] (try (select {by: {k: (+ x 'a)} from: TB}) (fn [e] 0))) 5 1000) -- true +(probe_caught (fn [p] (try (select {by: {k: (+ 1 'a)} from: TB}) (fn [e] 0))) 5 1000) -- true +(probe_caught (fn [p] (try (select {c: (count (distinct y)) by: (+ x 'a) from: TB}) (fn [e] 0))) 5 1000) -- true +;; a where: that keeps every row hands back the input itself, with a +;; reference the no-output and eval-level groupings never dropped: the +;; whole input table per call, a nested select's result included +(set mkw (fn [] (table [x y z s] (list (% (til 1000) 7) (til 1000) (% (til 1000) 3) (as 'STR (% (til 1000) 5)))))) +(probe (fn [p] (count (select {by: x from: (mkw) where: (>= y 0)}))) 5 60) -- true +(probe (fn [p] (count (select {by: (* x 2) from: (mkw) where: (>= y 0) desc: x take: 2}))) 5 60) -- true +(probe (fn [p] (count (select {by: [x z] from: (mkw) where: (>= y 0)}))) 5 60) -- true +(probe (fn [p] (count (select {by: s from: (mkw) where: (>= y 0)}))) 5 60) -- true +(probe (fn [p] (count (select {by: {k: x} from: (select {from: (mkw) where: (> y 38)}) where: (> y 0)}))) 5 60) -- true +;; a table kept in a global is not held past the selects over it +(set Tkw (mkw)) +(set h0 (heapb)) +(map (fn [p] (count (select {by: x from: Tkw where: (>= y 0)}))) (til 10)) +(set Tkw 0) +(< (- (heapb) h0) -10000) -- true +;; try frees the error it catches, and the trace its unwind recorded: a +;; raise, a runtime error, a rethrow, a fallback value, in a function +(probe (fn [p] (try (raise p) (fn [e] 0))) 5 1000) -- true +(probe (fn [p] (try (+ p 'a) (fn [e] 0))) 5 1000) -- true +(probe (fn [p] (try (try (raise p) (fn [e] (raise e))) (fn [e] 0))) 5 1000) -- true +(probe (fn [p] (try (+ p 'a) 0)) 5 1000) -- true +;; and at the top level, where try is evaluated rather than compiled. A +;; handler written as a literal is a new literal in each statement, which +;; the closure template cache keeps (up to 256 of them, a bounded cost per +;; statement): a statement is run 1000 and then 4000 times, and the two +;; must cost the same. +(times 100 (try (raise 5) (fn [e] 0))) +(set h0 (heapb)) +(times 1000 (try (raise 5) (fn [e] 0))) +(set d1 (- (heapb) h0)) +(set h0 (heapb)) +(times 4000 (try (raise 5) (fn [e] 0))) +(< (- (- (heapb) h0) d1) 1024) -- true +(set h0 (heapb)) +(times 1000 (try (+ 1 'a) 0)) +(set d1 (- (heapb) h0)) +(set h0 (heapb)) +(times 4000 (try (+ 1 'a) 0)) +(< (- (- (heapb) h0) d1) 1024) -- true +(set h0 (heapb)) +(times 1000 (try (try (raise 5) (fn [e] (raise e))) (fn [e] 0))) +(set d1 (- (heapb) h0)) +(set h0 (heapb)) +(times 4000 (try (try (raise 5) (fn [e] (raise e))) (fn [e] 0))) +(< (- (- (heapb) h0) d1) 1024) -- true +;; an error raised inside nested calls leaves a trace of their frames, which +;; the top-level try clears with the error. Measured within one statement: +;; the runner clears the trace between statements. +(set fe1 (fn [x] (+ x 'a))) +(set fe2 (fn [x] (fe1 x))) +(times 100 (try (fe2 1) (fn [e] 0))) +(do (set h0 (heapb)) (times 1000 (try (fe2 1) (fn [e] 0))) (< (- (heapb) h0) 4096)) -- true +;; an operand error the asof-join planner meets is freed before it falls back +(set qtr (table [Sym Time Bid] (list [x x x] [10:00:00.000 10:00:02.000 10:00:04.000] [99.0 100.5 101.5]))) +(probe_caught (fn [p] (try (asof-join [Sym Time] (select {from: nosuchtbl}) qtr) (fn [e] 0))) 5 1000) -- true +;; a sort without by: over a parted table: no growth per call (it failed, +;; and each failure left 64 B behind) +(.sys.exec "rm -rf /tmp/rfl_ckmemps") +(.db.splayed.set "/tmp/rfl_ckmemps/2024.01.01/t/" (table [x y] (list [3 1 4] [30 10 40]))) +(.db.splayed.set "/tmp/rfl_ckmemps/2024.01.02/t/" (table [x y] (list [2 3 1 5] [20 31 11 50]))) +(set Pps (.db.parted.get "/tmp/rfl_ckmemps/" 't)) +(probe_caught (fn [p] (try (count (select {from: Pps desc: x})) (fn [e] 0))) 5 300) -- true +(probe_caught (fn [p] (try (count (select {from: Pps desc: x take: 2})) (fn [e] 0))) 5 300) -- true +(.sys.exec "rm -rf /tmp/rfl_ckmemps") ;; the same table reused across calls must not be released twice: the ;; result is still right after many calls (set T (mk 1)) @@ -40,3 +216,16 @@ (count T) -- 786 (count (window {from: T part: [instrument] order: [rid] funcs: {n: (count v)}})) -- 786 (== (sum (at (window {from: T part: [instrument] order: [rid] frame: 'running funcs: {s: (sum v)}}) 's)) (sum (at (window {from: T part: [instrument] order: [rid] frame: 'running funcs: {s: (sum v)}}) 's))) -- true +;; #757: the count-distinct rewrite ran its where: as a filter node and kept +;; the result, which is the input table itself with a reference of its own, +;; releasing it only on error. A lone (count (distinct x)) under a where: +;; and a by: kept one extra reference on its table per call, so the table +;; was never freed and the next insert into it copied every column. +(probe (fn [p] (count (select {from: (mk p) where: (> rid 3) by: instrument n: (count (distinct v))}))) 5 60) -- true +(probe (fn [p] (count (select {from: (mk p) where: (> rid 3) by: [instrument rid] n: (count (distinct v))}))) 5 60) -- true +(probe (fn [p] (count (select {from: (mk p) where: (> rid 3) by: instrument n: (count (distinct v)) desc: n take: 3}))) 5 60) -- true +;; the same table reused across calls is not released twice +(set T2 (mk 2)) +(map (fn [p] (select {from: T2 where: (> rid 3) by: instrument n: (count (distinct v))})) (til 50)) +(count T2) -- 786 +(sum (at (select {from: T2 where: (> rid 3) by: instrument n: (count (distinct v))}) 'n)) -- 784 diff --git a/test/rfl/ops/exec_coverage.rfl b/test/rfl/ops/exec_coverage.rfl index a3bdea9dd..b766a778f 100644 --- a/test/rfl/ops/exec_coverage.rfl +++ b/test/rfl/ops/exec_coverage.rfl @@ -348,12 +348,11 @@ (count (select {from: (select {from: TT where: (< a 0)}) where: (not-in a [1 2 3])})) -- 0 ;; ==================================================================== -;; OP_IN — RAY_STR error path — exec.c:675-676. -;; Either side being RAY_STR returns ray_error("nyi"). We assert it -;; produces an `nyi`-tagged error rather than running the kernel. +;; OP_IN — RAY_STR column. The typed kernel refuses string cells; the +;; executor answers them through the general membership path instead. ;; ==================================================================== (set TStrCol (table [s] (list ["alpha" "beta" "gamma"]))) -(select {from: TStrCol where: (in s ["alpha"])}) !- nyi +(at (select {from: TStrCol where: (in s ["alpha"])}) 's) -- ["alpha"] ;; ==================================================================== ;; OP_IN — sym-vs-non-sym type mismatch — exec.c:691-693 sets diff --git a/test/rfl/query/concat_alias_scope.rfl b/test/rfl/query/concat_alias_scope.rfl new file mode 100644 index 000000000..fdb41a0fb --- /dev/null +++ b/test/rfl/query/concat_alias_scope.rfl @@ -0,0 +1,48 @@ +(set T (table [x k s t] (list [1 2 3 4 5] [0 0 1 1 2] ['a 'b 'c 'd 'e] (list "p" "q" "r" "s" "t")))) +(set suffix "!") +(set sfxg (fn [v] (concat v suffix))) +;; Aliases supply actual arguments without capturing the helper's free names. +(at (select {a: t suffix: (upper s) e: (reverse x) v: (sfxg a) from: T}) 'v) -- ["p!" "q!" "r!" "s!" "t!"] +(at (select {suffix: (first s) a: (first t) v: (sfxg a) by: k from: T asc: k}) 'v) -- ["p!" "r!" "t!"] +;; A missing global remains an error even when an alias has that name. +(set ha (fn [v] (concat v aa))) +(select {aa: (upper s) e: (reverse x) v: (ha s) from: T}) !- name +(set hb (fn [v] (+ v bb))) +(select {bb: (* x 10) e: (reverse x) v: (hb x) from: T}) !- name +;; A nested helper resolves its own free name, not its caller's formal. +(set label 'G) +(set inner (fn [v] (concat v label))) +(set outer (fn [v label] (inner v))) +(at (select {v: (outer s 'L) e: (reverse x) from: T}) 'v) -- ['aG 'bG 'cG 'dG 'eG] +;; Collection helpers keep the same whole-column semantics as inline concat. +(set sv ['p 'q 'r 's 't]) +(set hsv (fn [v] (concat v sv))) +(at (select {v: (hsv s) from: T}) 'v) -- ['a 'b 'c 'd 'e 'p 'q 'r 's 't] +(at (select {v: (hsv s) e: (enlist 7) from: T}) 'v) -- ['a 'b 'c 'd 'e 'p 'q 'r 's 't] +(set two (fn [a b] (concat a b))) +(set L3 ['u 'v 'w]) +(at (select {v: (two s L3) from: T}) 'v) -- ['a 'b 'c 'd 'e 'u 'v 'w] +(at (select {n: (count (two s L3)) by: k from: T asc: k}) 'n) -- [5 5 4] +(update {v: (two s L3) from: T}) !- length +;; A quoted suffix in a helper is not a reference to the source column x. +(set hq (fn [v] (concat v 'x))) +(at (update {v: (hq s) from: T}) 'v) -- ['ax 'bx 'cx 'dx 'ex] +(at (select {from: T where: (in (hq s) ['ax 'cx])}) 'x) -- [1 3] +(at (select {n: (+ (count (hq s)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] +(set hqs (fn [v] (concat v 's))) +(at (select {v: (hqs s) from: T}) 'v) -- ['as 'bs 'cs 'ds 'es] +(at (update {v: (hqs s) from: T}) 'v) -- ['as 'bs 'cs 'ds 'es] +;; Text casts inherit the row dependency of their input even without DAG lowering. +(at (select {v: (concat (as 'SYM x) "!") from: T}) 'v) -- ['1! '2! '3! '4! '5!] +(at (update {v: (concat (as 'SYM x) "!") from: T}) 'v) -- ['1! '2! '3! '4! '5!] +(at (select {n: (+ (count (concat (as 'SYM x) "!")) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] +(at (select {n: (count (hsv s)) by: k from: T asc: k}) 'n) -- [7 7 6] +(at (select {n: (+ (count (hsv s)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [9 9 7] +;; A replaced source column remains visible to a helper's free reference; +;; the helper's actual argument still sees the output alias. +(set TS (table [s suffix] (list ['a 'b] ['x 'y]))) +(at (select {suffix: (upper s) v: (sfxg s) from: TS}) 'v) -- ['ax 'by] +(at (select {suffix: (upper s) v: (sfxg s) e: (reverse s) from: TS}) 'v) -- ['ax 'by] +(at (select {suffix: (upper s) v: (sfxg suffix) e: (reverse s) from: TS}) 'v) -- ['Ax 'By] +(at (select {suffix: (upper s) v: (sfxg s) e: (reverse s) from: TS where: (== s 'b)}) 'v) -- ['by] +(at (select {__query_source_0: s suffix: (upper s) v: (sfxg s) e: (reverse s) from: TS}) 'v) -- ['ax 'by] diff --git a/test/rfl/query/concat_collections.rfl b/test/rfl/query/concat_collections.rfl new file mode 100644 index 000000000..7bae19522 --- /dev/null +++ b/test/rfl/query/concat_collections.rfl @@ -0,0 +1,29 @@ +;; Literal/bound collection concatenation must not become string concatenation. +(set T (table [x] (list [1 2 3]))) +(at (select {v: (concat [2] [1]) from: T}) 'v) -- [2 1] +(at (select {from: T where: (in x (concat [2] [1]))}) 'x) -- [1 2] +(at (select {from: T where: (not-in x (concat [2] [1]))}) 'x) -- [3] +(set A [2]) +(set B [1]) +(at (select {v: (concat A B) from: T}) 'v) -- [2 1] +(at (select {v: (concat [2] (concat [1] [3])) from: T}) 'v) -- [2 1 3] +(at (select {v: (concat [0Nl] [1]) from: T}) 'v) -- [0Nl 1] +(at (select {v: (concat [2.0] [1.0]) from: T}) 'v) -- [2.0 1.0] +(at (select {v: (concat ['a] ['b]) from: T}) 'v) -- ['a 'b] +(at (select {v: (concat ["a"] ["b"]) from: T}) 'v) -- ["a" "b"] + +;; Numeric columns concatenate once, not independently for each row. +(at (select {v: (concat x [4]) from: T}) 'v) -- [1 2 3 4] +(at (select {v: (concat [0] x) from: T}) 'v) -- [0 1 2 3] +(at (select {v: (concat x x) from: T}) 'v) -- [1 2 3 1 2 3] +(at (select {n: (count (concat x [4])) from: T}) 'n) -- [4] +(at (select {from: T where: (in x (concat x [4]))}) 'x) -- [1 2 3] + +;; Existing row-wise string concatenation, including forced query fallback. +(set S (table [s ts] (list ['a 'b] [2024.01.01D00:00:00.000000000 2024.01.01D00:00:00.000000001]))) +(at (select {v: (concat s "!") from: S}) 'v) -- ['a! 'b!] +(at (select {v: (concat "[" s "]") from: S}) 'v) -- (as 'SYM (list "[a]" "[b]")) +(at (select {v: (concat [2] [1]) other: (+ ts 1) from: S}) 'v) -- [2 1] +(set SS (table [s ts] (list (as 'STR (list "a" "b")) (at S 'ts)))) +(at (select {v: (concat s "!") other: (+ ts 1) from: SS}) 'v) -- ["a!" "b!"] +(at (select {v: (concat "a" "b") other: (+ ts 1) from: SS}) 'v) -- ["ab" "ab"] diff --git a/test/rfl/query/concat_fallback_followup.rfl b/test/rfl/query/concat_fallback_followup.rfl new file mode 100644 index 000000000..e0ed8664e --- /dev/null +++ b/test/rfl/query/concat_fallback_followup.rfl @@ -0,0 +1,25 @@ +(set T (table [x k s] (list [1 2 3 4 5] [0 0 1 1 2] ['a 'b 'c 'd 'e]))) +(set L ['u 'v]) +;; Fallback count keeps its position beside a native aggregate. +(key (select {c: (count L) m: (sum x) by: k from: T})) -- ['k 'c 'm] +(key (select {m: (sum x) c: (count L) by: k from: T})) -- ['k 'm 'c] +(at (select {c: (count L) m: (sum x) by: k from: T asc: k}) 'c) -- [2 2 2] +;; Multi-key/top-N count must count the constant collection, not group rows. +(at (select {c: (count L) by: [k s] take: 2 from: T}) 'c) -- [2 2] +;; An in-place update's fallback WHERE binds the query's source columns. +(update {x: 0 from: 'T where: (in (concat (as 'SYM x) "!") ['1! '3!])}) +(at T 'x) -- [0 2 0 4 5] +;; Uncompiled column-derived text operands are whole columns in a projection, +;; exactly as they are in update, where and by. +(set T3 (table [x s ss] (list [1 2 3] ['a 'b 'c] (list "p" "q" "r")))) +(at (select {v: (concat ss (reverse ss)) from: T3}) 'v) -- ["pr" "qq" "rp"] +(at (select {v: (concat ss (asc ss)) from: T3}) 'v) -- ["pp" "qq" "rr"] +(at (select {v: (concat s (as 'STR x)) from: T3}) 'v) -- ["a1" "b2" "c3"] +(at (select {v: (concat s (at s [2 1 0])) from: T3}) 'v) -- ['ac 'bb 'ca] +(at (select {v: (concat s (at s 0)) from: T3}) 'v) -- ['aa 'ba 'ca] +(at (update {v: (concat ss (reverse ss)) from: T3}) 'v) -- ["pr" "qq" "rp"] +(at (update {v: (concat s (as 'STR x)) from: T3}) 'v) -- ["a1" "b2" "c3"] +(at (update {v: (concat s (at s [2 1 0])) from: T3}) 'v) -- ['ac 'bb 'ca] +(at (select {from: T3 where: (in (concat s (reverse s)) ['ac 'ca])}) 'x) -- [1 3] +(set G3 (table [k s] (list [0 0 1 1 2] ['a 'b 'c 'd 'e]))) +(at (select {v: (first (concat s (reverse s))) by: k from: G3 asc: k}) 'v) -- ['ab 'cd 'ee] diff --git a/test/rfl/query/concat_helper_consistency.rfl b/test/rfl/query/concat_helper_consistency.rfl new file mode 100644 index 000000000..689b66987 --- /dev/null +++ b/test/rfl/query/concat_helper_consistency.rfl @@ -0,0 +1,219 @@ +(set T (table [x k s] (list [1 2 3 4 5] [0 0 1 1 2] ['a 'b 'c 'd 'e]))) +(set T3 (table [x s t] (list [1 2 3] ['a 'b 'c] (list "p" "q" "r")))) +(set TS (table [k s suffix] (list [0 0 1] ['a 'b 'c] ['x 'y 'z]))) +;; An opaque helper around row text must not send the planner into endless +;; expansion, and a pure helper around a whole-column verb is that verb. +(set hrv (fn [v] (reverse v))) +(at (select {n: (first (hrv (concat s "!"))) from: T}) 'n) -- ['e!] +(at (select {n: (first (hrv (concat s "!"))) e: (reverse x) from: T}) 'n) -- ['e! 'e! 'e! 'e! 'e!] +(at (select {v: (hrv s) from: T}) 'v) -- ['e 'd 'c 'b 'a] +(at (select {v: (hrv s) e: (reverse x) from: T}) 'v) -- ['e 'd 'c 'b 'a] +(set mrv (fn [v] 1 (reverse v))) +(count (select {n: (first (mrv (concat s "!"))) from: T})) -- 1 +;; A grouped output named like its key keeps both columns, the key first. +(key (select {k: (first x) n: (count (distinct x)) by: k from: T asc: k})) -- ['k 'k 'n] +(value (select {k: (first x) n: (count (distinct x)) by: k from: T asc: k})) -- (list [0 1 2] [1 3 5] [2 2 1]) +(key (select {g: (first x) n: (count (distinct x)) by: {g: k} from: T})) -- ['g 'g 'n] +;; Grouped fallback outputs follow the requested order, as planned outputs do. +(key (select {n: (+ (count s) (count (distinct x))) m: (sum x) by: k from: T})) -- ['k 'n 'm] +(key (select {m: (sum x) n: (+ (count s) (count (distinct x))) by: k from: T})) -- ['k 'm 'n] +(key (select {n: (+ (count s) (count (distinct x))) m: (sum x) by: k from: T desc: m take: 2})) -- ['k 'n 'm] +(key (select {n: (sum x) m: (count s) by: k from: T})) -- ['k 'n 'm] +;; Helpers built from pure builtins outside the planner's tables are inlined. +(set hss (fn [v] (concat (substr v 0 1) 'z))) +(at (select {n: (+ (count (hss s)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] +(at (select {v: (hss s) e: (reverse x) from: T}) 'v) -- ['az 'bz 'cz 'dz 'ez] +(set hxb (fn [v] (xbar 2 v))) +(at (select {v: (hxb x) e: (reverse x) from: T}) 'v) -- [2 2 0 0 0] +(set hw (fn [v] (within v [2 4]))) +(at (select {from: T where: (hw x)}) 'x) -- [2 3 4] +;; Effects never move: an effectful argument runs once per row, and an +;; effectful body is called once per row rather than inlined. +(set calls 0) +(set eff (fn [v] (set calls (+ calls 1)) v)) +(set ign (fn [a b] a)) +(at (select {v: (ign s (eff s)) from: T}) 'v) -- ['a 'b 'c 'd 'e] +calls -- 5 +(set ticks 0) +(set tick (fn [v] (do (set ticks (+ ticks 1)) v))) +(at (select {v: (tick s) e: (reverse x) from: T}) 'v) -- ['a 'b 'c 'd 'e] +ticks -- 5 +;; A global an inlined helper reads is read when it runs: an effectful helper +;; in the same expression that sets it between groups, rows or operands is +;; seen, grouped or not, aggregating or row-wise +(set TG (table [x k] (list (til 20) (% (til 20) 7)))) +(set G 0) +(set bump (fn [v] (set G (+ G 100)) 0)) +(set hg (fn [v] (+ (sum v) G))) +(set hgr (fn [v] (+ v G))) +(at (update {r: (+ (bump x) (hg x)) by: k from: TG}) 'r) -- [121 224 327 430 533 636 719 121 224 327 430 533 636 719 121 224 327 430 533 636] +G -- 700 +(set G 0) +(at (update {r: (+ (bump x) (hgr x)) by: k from: TG}) 'r) -- [100 201 302 403 504 605 706 107 208 309 410 511 612 713 114 215 316 417 518 619] +(set G 0) +(at (update {r: (+ (bump x) (hg x)) from: TG}) 'r) -- (take 290 20) +(set G 0) +(at (update {r: (+ (bump x) (hg x)) from: TG where: (> x 17)}) 'r) -- [0N 0N 0N 0N 0N 0N 0N 0N 0N 0N 0N 0N 0N 0N 0N 0N 0N 0N 290 290] +(set G 0) +(at (select {r: (+ (bump x) (hg x)) by: k from: TG}) 'r) -- [221 324 427 530 633 736 819] +(set bumpk (fn [v] (set G (first v)) 0)) +(at (update {r: (+ (bumpk k) (hg x)) by: k from: TG}) 'r) -- [21 25 29 33 37 41 25 21 25 29 33 37 41 25 21 25 29 33 37 41] +;; ... in a grouped select's output over another output, and in a projection +;; evaluated row by row +(set G 0) +(at (select {s: (sum x) r: (+ (bump s) (hgr s)) by: k from: TG}) 'r) -- [121 224 327 430 533 636 719] +(set G 0) +(at (select {s: (sum x) r: (+ (hgr s) (bump s)) by: k from: TG}) 'r) -- [21 124 227 330 433 536 619] +(set G 0) +(at (select {a: (* x 2) r: (+ (bump a) (hgr x)) from: TG}) 'r) -- (+ (til 20) (* 100 (+ 1 (til 20)))) +(set G 0) +(at (select {r: (+ (bump x) (hgr x)) e: (reverse x) from: TG}) 'r) -- (+ (til 20) (* 100 (+ 1 (til 20)))) +;; ... and so is an effect the expression reaches through a let in a loop, a +;; let after a raise, or a function value a builtin calls +(set pidG (fn [x] x)) +(set G 0) +(set bumpL (fn [v] (let g pidG) (times 2 (do (g v) (let g (fn [y] (bump y))))) 0)) +(at (update {r: (+ (bumpL x) (hg x)) by: k from: TG}) 'r) -- [121 224 327 430 533 636 719 121 224 327 430 533 636 719 121 224 327 430 533 636] +(set G 0) +(set bumpT (fn [v] (let g (fn [y] (bump y))) (try (do (raise "x") (let g pidG)) (fn [e] 0)) (g v) 0)) +(at (update {r: (+ (bumpT x) (hg x)) by: k from: TG}) 'r) -- [121 224 327 430 533 636 719 121 224 327 430 533 636 719 121 224 327 430 533 636] +(set G 0) +(set DG (dict ['b] (list bump))) +(at (update {r: (+ (first (map DG.b (enlist x))) (hg x)) by: k from: TG}) 'r) -- [121 224 327 430 533 636 719 121 224 327 430 533 636 719 121 224 327 430 533 636] +(set G 0) +(at (update {r: (+ (first (map (at DG 'b) (enlist x))) (hg x)) by: k from: TG}) 'r) -- [121 224 327 430 533 636 719 121 224 327 430 533 636 719 121 224 327 430 533 636] +(set G 0) +(set TGf (update {f: (list bump) from: (table [a] (list [1]))})) +(at (update {r: (+ (first (map (first (at TGf 'f)) (enlist x))) (hg x)) by: k from: TG}) 'r) -- [121 224 327 430 533 636 719 121 224 327 430 533 636 719 121 224 327 430 533 636] +(set G 0) +(set bump2G (fn [a v] (set G (+ G 100)) 0)) +(set DG2 (dict ['g] (list bump2G))) +(at (update {r: (+ (fold-left (at DG2 'g) 0 (enlist x)) (hg x)) by: k from: TG}) 'r) -- [121 224 327 430 533 636 719 121 224 327 430 533 636 719 121 224 327 430 533 636] +(set G 0) +(set DGh (dict ['h] (list bump))) +(at (update {r: (+ (try (raise "x") (at DGh 'h)) (hg x)) by: k from: TG}) 'r) -- [121 224 327 430 533 636 719 121 224 327 430 533 636 719 121 224 327 430 533 636] +(set G 0) +(set DGm (dict ['g] (list bump))) +(at (update {r: (+ (first (first (map (fn [f] (f (at DGm 'g) (enlist x))) (list map)))) (hg x)) by: k from: TG}) 'r) -- [121 224 327 430 533 636 719 121 224 327 430 533 636 719 121 224 327 430 533 636] +;; ... and a pure expression, inlined once for every group, reads it as well +(set G 1000) +(at (update {r: (hg x) by: k from: TG}) 'r) -- [1021 1024 1027 1030 1033 1036 1019 1021 1024 1027 1030 1033 1036 1019 1021 1024 1027 1030 1033 1036] +;; A helper's parameter spelled like a special form is called, on the planned +;; path and when the helper is expanded; so is a caller's local of that name +(set TQ (table [v] (list [1 2 3]))) +(set hq (fn [quote x] (quote x))) +(at (select {r: (hq neg v) from: TQ}) 'r) -- [-1 -2 -3] +(set hiff (fn [if x] (if x))) +(at (select {r: (hiff neg v) from: TQ}) 'r) -- [-1 -2 -3] +(at ((fn [quote] (select {r: (quote v) from: TQ})) neg) 'r) -- [-1 -2 -3] +;; a helper's free name is the global, not a caller's local of that name +(set hrv (fn [v] (reverse v))) +(set hrv2 (fn [v] 1 (reverse v))) +(at ((fn [reverse] (select {r: (hrv v) e: (reverse v) from: TQ})) neg) 'r) -- (at ((fn [reverse] (select {r: (hrv2 v) from: TQ})) neg) 'r) +;; A quoted symbol inside a helper body is the symbol on every path, even +;; when a column has that spelling and whatever operator consumes it. +(set hqt (fn [v] (concat v 't))) +(at (select {v: (hqt s) from: T3}) 'v) -- ['at 'bt 'ct] +(at (select {v: (hqt s) e: (reverse x) from: T3}) 'v) -- ['at 'bt 'ct] +(at (update {v: (hqt s) from: T3}) 'v) -- ['at 'bt 'ct] +(at (select {from: T3 where: (in (hqt s) ['at 'ct])}) 'x) -- [1 3] +(set hut (fn [v] (concat v (upper 't)))) +(at (select {v: (hut s) from: T3}) 'v) -- ['aT 'bT 'cT] +(at (select {v: (hut s) e: (reverse x) from: T3}) 'v) -- ['aT 'bT 'cT] +(set heq (fn [v] (== v 'a))) +(at (select {v: (heq s) e: (reverse x) from: T3}) 'v) -- [true false false] +(set hqt2 (fn [v] ((fn [w] (concat w 't)) v))) +(at (select {v: (hqt2 s) e: (reverse x) from: T3}) 'v) -- ['at 'bt 'ct] +;; A lambda written inline in the query keeps the query's column rule for +;; literals, on the planned path and in every fallback. +(at (select {v: ((fn [v] (concat v 's)) s) from: T}) 'v) -- ['aa 'bb 'cc 'dd 'ee] +(at (select {v: ((fn [v] (concat v 's)) s) e: (reverse x) from: T}) 'v) -- ['aa 'bb 'cc 'dd 'ee] +(at (update {v: ((fn [v] (concat v 's)) s) from: T}) 'v) -- ['aa 'bb 'cc 'dd 'ee] +(at (select {v: ((fn [v] (concat v (upper 't))) s) from: T3}) 'v) -- ["aP" "bQ" "cR"] +(at (select {v: ((fn [v] (concat v (upper 't))) s) e: (reverse x) from: T3}) 'v) -- ["aP" "bQ" "cR"] +(at (select {o: ((fn [x] 'x) 999) e: (reverse x) from: T}) 'o) -- [1 2 3 4 5] +;; A nested helper's free name is its global on the planned path too. +(set label 'G) +(set inner (fn [v] (concat v label))) +(set outer (fn [v label] (inner v))) +(at (select {v: (outer s 'L) from: T}) 'v) -- ['aG 'bG 'cG 'dG 'eG] +(at (update {v: (outer s 'L) from: T}) 'v) -- ['aG 'bG 'cG 'dG 'eG] +(at (select {from: T where: (in (outer s 'L) ['aG 'xG])}) 'x) -- [1] +;; A grouped derived output: an alias that replaces a source column does not +;; capture a helper's free name; without a global the name is an error. +(set suffix "!") +(set sfxg (fn [v] (concat v suffix))) +(at (select {suffix: (first s) a: (first s) v: (sfxg a) by: k from: TS asc: k}) 'v) -- ['a! 'c!] +(set hng (fn [v] (concat v nosuch))) +(select {a: (first s) v: (hng a) by: k from: TS}) !- name +;; A whole-column projection expands helpers inside its operands. +(set sfx (fn [v] (concat v "!"))) +(at (select {v: (concat s (first (sfx s))) from: T}) 'v) -- ['aa! 'ba! 'ca! 'da! 'ea!] + +;; ── a text cell reduced from a column is a cell of the rows ─────────────── +;; `(first s)` per group is one value derived from the group's rows: concat +;; joins it with a literal as it joins the cell itself, and an empty symbol +;; cell is empty text, not a null literal. Grouped select and grouped update +;; agree with the ungrouped projection. +(set TC (table [x s] (list [1 2 3 4] (as 'SYMBOL ["a" "" "c" "d"])))) +(at (select {r: (concat s 'zz) from: TC}) 'r) -- [azz zz czz dzz] +(at (select {r: (concat (first s) 'zz) by: x from: TC}) 'r) -- [azz zz czz dzz] +(at (select {r: (concat (last s) 'zz) by: x from: TC}) 'r) -- [azz zz czz dzz] +(at (select {r: (concat 'zz (first s)) by: x from: TC}) 'r) -- [zza zz zzc zzd] +(at (select {r: (concat (max s) 'zz) by: x from: TC}) 'r) -- [azz zz czz dzz] +(at (select {r: (concat (first s) 'zz) by: x from: (select {from: TC where: (> x 1)})}) 'r) -- [zz czz dzz] +(at (update {r: (concat (first s) 'zz) by: x from: TC}) 'r) -- [azz zz czz dzz] +;; a STR column behaves the same way +(set TS (table [x s] (list [1 2 3 4] ["a" "" "c" "d"]))) +(at (select {r: (concat (first s) "zz") by: x from: TS}) 'r) -- ["azz" "zz" "czz" "dzz"] +(at (update {r: (concat (first s) "zz") by: x from: TS}) 'r) -- ["azz" "zz" "czz" "dzz"] +;; a count is a number: it keeps collection semantics +(count (select {r: (concat (count s) 'zz) from: TC})) -- 2 +;; a STR cell reduced from a STR column keeps STR output, ungrouped as grouped +(at (select {r: (concat (first s) "zz") from: TS}) 'r) -- ["azz"] +;; the cell flags cover every operand position, and a query concat joins up +;; to 255 operands in one step: with 65 operands a null literal at position +;; 64 still nulls the row (a 64-bit mask shifted by 64 is undefined; on x86 +;; it read position 0's flag), a cell at position 64 is still a cell (an +;; empty cell is empty text, the rows where: keeps included), and a STR cell +;; there still makes the result STR +(at (select {r: (concat (first s) 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z ') from: TC}) 'r) -- [null] +(at (select {r: (concat 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z (first s)) from: TC}) 'r) -- [zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzza] +(at (select {r: (concat 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z (first s)) from: (select {from: TC where: (== x 2)})}) 'r) -- [zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz] +(at (select {r: (concat 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z (first s)) from: TS}) 'r) -- ["zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzza"] +(at (select {r: (concat s 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'q) from: TC}) 'r) -- [azzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzq zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzq czzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzq dzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzq] +;; the same shape inside a lambda written in query text (tree walker) and in a +;; named helper (bytecode) +(at (select {r: ((fn [v] (concat (first v) 'zz)) s) by: x from: TC}) 'r) -- [azz zz czz dzz] +(set hfirst (fn [v] (concat (first v) 'zz))) +(at (select {r: (hfirst s) by: x from: TC}) 'r) -- [azz zz czz dzz] +;; and when the helper cannot be inlined (two statements), so the reduction +;; runs on the VM, on the tree walker (a lambda written in query text), and +;; through a builtin held in a local (the VM's general call) +(set hfirst2 (fn [v] 1 (concat (first v) 'zz))) +(at (select {r: (hfirst2 s) by: x from: TC}) 'r) -- [azz zz czz dzz] +(at (select {r: ((fn [v] 1 (concat (first v) 'zz)) s) by: x from: TC}) 'r) -- [azz zz czz dzz] +(set hfirst3 (fn [v] 1 (let f first) (concat (f v) 'zz))) +(at (select {r: (hfirst3 s) by: x from: TC}) 'r) -- [azz zz czz dzz] +;; a binary builtin through that general call keeps its result's row +;; provenance, so a second concat over it still joins text row by row +(set hcl3 (fn [v] 1 (let f concat) (f (f v 'a) 'b))) +(at (select {r: (hcl3 s) from: T}) 'r) -- ['aab 'bab 'cab 'dab 'eab] +(at (update {r: (hcl3 s) from: T}) 'r) -- ['aab 'bab 'cab 'dab 'eab] +;; ... as does a closure body's resolved concat +(set mkcl3 (fn [k] (fn [v] (concat (concat v k) 'b)))) +(set ccl3 (mkcl3 'a)) +(at (select {r: (ccl3 s) from: T}) 'r) -- ['aab 'bab 'cab 'dab 'eab] +;; a local an eval rebound has unknown provenance: a row-wise builtin over it +;; does not make it row data, in a closure body as in a named helper +(set mkcl4 (fn [k] (fn [v] (let w 0) (eval (quote (let w v))) (concat (as 'SYM w) k)))) +(set ccl4 (mkcl4 'z)) +(set hcl4 (fn [v] (let w 0) (eval (quote (let w v))) (concat (as 'SYM w) 'z))) +(at (select {r: (ccl4 s) from: T}) 'r) -- (at (select {r: (hcl4 s) from: T}) 'r) +(at (select {r: (ccl4 s) from: T}) 'r) -- (list ['a 'z] ['b 'z] ['c 'z] ['d 'z] ['e 'z]) +;; a row-flagged column captured after many unflagged bindings keeps its flag +(set TF1 (table [s] (list (as 'SYMBOL ["a" "b" "a" "c"])))) +(set hflag1 (fn [v] (let u1 1) ((fn [a] (concat a 'x)) v))) +(at (select {r: (hflag1 s) from: TF1}) 'r) -- [ax bx ax cx] +(set hflag21 (fn [v] (let u1 1) (let u2 1) (let u3 1) (let u4 1) (let u5 1) (let u6 1) (let u7 1) (let u8 1) (let u9 1) (let u10 1) (let u11 1) (let u12 1) (let u13 1) (let u14 1) (let u15 1) (let u16 1) (let u17 1) (let u18 1) (let u19 1) (let u20 1) (let u21 1) ((fn [a] (concat a 'x)) v))) +(at (select {r: (hflag21 s) from: TF1}) 'r) -- [ax bx ax cx] diff --git a/test/rfl/query/concat_operands.rfl b/test/rfl/query/concat_operands.rfl new file mode 100644 index 000000000..4eb8adfb1 --- /dev/null +++ b/test/rfl/query/concat_operands.rfl @@ -0,0 +1,67 @@ +(set T (table [x k s t] (list [1 2 3 4 5] [0 0 1 1 2] ['a 'b 'c 'd 'e] (list "p" "q" "r" "s" "t")))) +(set sfx (fn [v] (concat v "!"))) +(set sfs (fn [v] (concat v 'zz))) +;; Helper parameters inherit column semantics when inlined by the query. +(at (select {v: (sfx s) from: T}) 'v) -- ['a! 'b! 'c! 'd! 'e!] +(at (select {v: (sfs s) from: T}) 'v) -- ['azz 'bzz 'czz 'dzz 'ezz] +(at (select {n: (count (sfx s)) by: k from: T asc: k}) 'n) -- [2 2 1] +(at (update {v: (sfs s) from: T}) 'v) -- ['azz 'bzz 'czz 'dzz 'ezz] +(at (select {from: T where: (in (sfs s) ['azz 'czz])}) 'x) -- [1 3] +(count (select {n: (count x) by: (sfs s) from: T})) -- 5 +(at (select {v: (sfx t) from: T}) 'v) -- ["p!" "q!" "r!" "s!" "t!"] +(set h (fn [v] (concat ['p 'q] 'r))) +(at (select {v: (h x) from: T}) 'v) -- ['p 'q 'r] +(at (select {v: (h x) e: (enlist 7) from: T}) 'v) -- ['p 'q 'r] +;; Both update predicate routes and grouped evaluation publish their table. +(at (update {n: (+ (count (concat s 'zz)) (count (distinct x))) by: k from: T}) 'n) -- [4 4 4 4 2] +(at (update {n: (+ (count (concat s "!")) (count (distinct x))) by: k from: T}) 'n) -- [4 4 4 4 2] +(at (update {x: 0 from: T where: (> (+ (count (concat s 'zz)) (count (distinct x))) 10)}) 'x) -- [1 2 3 4 5] +(at (update {n: 0 from: T where: (> (+ (count (concat s 'zz)) (count (distinct x))) 10)}) 'x) -- [1 2 3 4 5] +;; A bound vector is a collection, in either order and for every group size. +(set L3 ['u 'v 'w]) +(at (select {n: (+ (count (concat s L3)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [7 7 5] +(at (select {n: (+ (count (concat L3 s)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [7 7 5] +(at (select {n: (+ (count (concat s (take ['a] 0))) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] +(set ES (as 'STR (list))) +(at (select {n: (+ (sum (strlen (concat t ES))) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] +(at (select {v: (concat t ES) from: T}) 'v) -- ["p" "q" "r" "s" "t"] +(at (select {v: (concat ES t) from: T}) 'v) -- ["p" "q" "r" "s" "t"] +(at (select {v: (concat s L3) from: T}) 'v) -- ['a 'b 'c 'd 'e 'u 'v 'w] +;; Computed constants stay collections on planned and forced fallback paths. +(set L ['a 'b]) +(at (select {v: (concat (upper L) 'c) from: T}) 'v) -- ['A 'B 'c] +(at (select {v: (concat (upper L) 'c) e: (enlist 7) from: T}) 'v) -- ['A 'B 'c] +;; This shadowing case reaches the per-group evaluator, not the planner. +((fn [s] (at (select {n: (+ (count (concat s 'c)) (count (distinct x))) by: k from: T asc: k}) 'n)) ['a 'b]) -- [5 5 4] +;; A third-argument column is not a scalar to broadcast on a one-row source. +(set O (table [s] (list ['a]))) +(select {v: (concat "!" "?" s) a: [1 2] from: O}) !- domain +;; Mixing an inlined helper with an unsupported aggregate also keeps its rows. +(at (select {n: (+ (count (sfx s)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] + +(at (update {n: (+ (count (sfx s)) (count (distinct x))) by: k from: T}) 'n) -- [4 4 4 4 2] +(at (select {v: (sfx s) e: (enlist 7) from: T}) 'v) -- ['a! 'b! 'c! 'd! 'e!] +;; Constant collection counts are independent of the source row count. +(at (select {n: (count (concat L 'c)) from: T}) 'n) -- [3] +(at (select {n: (count [1 2]) from: T}) 'n) -- [2] +(at (select {n: (count L) from: T}) 'n) -- [2] +(at (select {n: (count L) m: (sum x) from: T}) 'n) -- [2] +(at (select {n: (count L) from: T where: (> x 3)}) 'n) -- [2] +(at (select {n: (count L) from: T where: (> x 9)}) 'n) -- [2] +(at (select {n: (count L) by: k from: T asc: k}) 'n) -- [2 2 2] +(at (select {n: (count (concat L 'c)) by: k from: T asc: k}) 'n) -- [3 3 3] +(at (select {n: (count L) x: x from: T}) 'n) -- [2 2 2 2 2] +;; Free helper constants retain their global binding in fallback, including +;; when an earlier projection uses the same name as an alias. +(set suffix "!") +(set sfxg (fn [v] (concat v suffix))) +(at (select {n: (+ (count (sfxg s)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] +(at (select {v: (sfxg s) e: (enlist 7) from: T}) 'v) -- ['a! 'b! 'c! 'd! 'e!] +(at (select {suffix: (upper s) e: (reverse x) v: (sfxg s) from: T}) 'v) -- ['a! 'b! 'c! 'd! 'e!] +(at (update {n: (+ (count (sfxg s)) (count (distinct x))) by: k from: T}) 'n) -- [4 4 4 4 2] +(set suffix 's) +(at (select {v: (sfxg s) e: (enlist 7) from: T}) 'v) -- ['as 'bs 'cs 'ds 'es] +;; Real source columns still have the compiler's column precedence. +(set TS (table [s suffix] (list ['a 'b] ['x 'y]))) +(at (select {v: (sfxg s) from: TS}) 'v) -- ['ax 'by] +(at (select {v: (sfxg s) e: (reverse suffix) from: TS}) 'v) -- ['ax 'by] diff --git a/test/rfl/query/concat_related.rfl b/test/rfl/query/concat_related.rfl new file mode 100644 index 000000000..f85a32801 --- /dev/null +++ b/test/rfl/query/concat_related.rfl @@ -0,0 +1,37 @@ +(set A (table [x k s] (list [1 2 3 4 5] [0 0 1 2 2] ['a 'b 'c 'd 'e]))) +;; Filtered COUNT needs no stored column for its computed input. +(at (select {n: (count (upper s)) by: k from: A where: (> x 1) asc: k}) 'n) -- [1 1 2] +(at (select {n: (count (concat s "!")) by: k from: A where: (> x 1) asc: k}) 'n) -- [1 1 2] +(at (select {n: (+ (count (concat s "!")) (count (concat s "?"))) by: k from: A where: (> x 1) asc: k}) 'n) -- [2 2 4] +;; Per-group fallback retains query text concat alongside collection aggregates. +(at (select {n: (+ (count (concat s "!")) (count (concat x [9]))) by: k from: A asc: k}) 'n) -- [5 3 5] +(at (select {n: (+ (count (concat s "!")) (count (distinct x))) by: k from: A asc: k}) 'n) -- [4 2 4] +(set T (table [x] (list [1 2 3]))) +(at (select {a: (concat [1] [2]) b: (enlist 7) from: T}) 'b) -- [7 7] +(at (select {b: (enlist 7) a: (concat [1] [2]) from: T}) 'b) -- [7 7] + +;; Scalar-only fallback keeps its usual source row count. +(at (select {b: (enlist 7) from: T}) 'b) -- [7 7 7] +(at (select {a: (concat [1] [2]) b: (enlist 7) c: 5 from: T}) 'c) -- [5 5] +(at (select {c: 5 b: (enlist 7) a: (concat [1] [2]) from: T}) 'c) -- [5 5] +(set E (table [x] (list (til 0)))) +(at (select {b: (enlist 7) a: (concat [1] [2]) from: E}) 'b) -- [7 7] +(select {a: (concat [1] [2]) b: (enlist 7) c: x from: T}) !- length +;; Mixed grouped expressions also work with direct WHERE and an empty selection. +(at (select {n: (+ (count (concat s "!")) (count (distinct x))) by: k from: A where: (> x 1) asc: k}) 'n) -- [2 2 4] +(count (select {n: (+ (count (concat s "!")) (count (distinct x))) by: k from: A where: (> x 9)})) -- 0 +;; The collection concat primitive remains unchanged outside query scope. +(concat ['a] 'b) -- ['a 'b] + +;; Enlist with columns stays a per-row constructor, including quoted names. +(at (select {p: (enlist x) from: T}) 'p) -- (list [1] [2] [3]) +(at (select {p: (enlist 'x) y: x from: T}) 'p) -- (list [1] [2] [3]) +(at (select {p: (enlist x (+ x 1)) from: T}) 'p) -- (list [1 2] [2 3] [3 4]) +(at (select {p: (enlist x) y: x from: T}) 'y) -- [1 2 3] +(at (select {n: (count (enlist x)) from: T}) 'n) -- [3] +(at (select {p: (enlist 7 8) from: T}) 'p) -- (list [7 8] [7 8] [7 8]) +(count (select {p: (enlist [7 8]) from: T})) -- 3 +(set EC [7 8]) +(count (select {p: (enlist EC) from: T})) -- 3 +(set ES 7) +(at (select {p: (enlist ES) a: (concat 1 2) from: T}) 'p) -- [7 7] diff --git a/test/rfl/query/concat_review.rfl b/test/rfl/query/concat_review.rfl new file mode 100644 index 000000000..41cd44516 --- /dev/null +++ b/test/rfl/query/concat_review.rfl @@ -0,0 +1,55 @@ +(set T (table [x k] (list [1 2 3] [0 0 1]))) +(set T2 (table [x] (list [1 2]))) +;; Constant text collections keep ordinary concat semantics in both orders. +(at (select {v: (concat ['a 'b] "!") from: T2}) 'v) !- type +(at (select {v: (concat "!" ['a 'b]) from: T2}) 'v) !- type +(at (select {v: (concat ['a 'b] '!) from: T2}) 'v) -- ['a 'b '!] +(set L ['a 'b]) +(at (select {v: (concat L "!") from: T2}) 'v) !- type +;; Both typed vectors still concatenate as collections. +(at (select {v: (concat ['a] ['b]) from: T2}) 'v) -- ['a 'b] +;; A grouped aggregate evaluates collection concat on each complete group. +(at (select {n: (count (concat x [4])) by: k from: T asc: k}) 'n) -- [3 2] +(at (select {n: (sum (concat x [4])) by: k from: T asc: k}) 'n) -- [7 7] +(set S (table [s k] (list ['a 'b 'c] [0 0 1]))) +(at (select {n: (count (concat s "!")) by: k from: S asc: k}) 'n) -- [2 1] +;; Length-changing projections cannot truncate or pad other columns. +(select {v: (concat 1 2) w: x from: T}) !- domain +(select {w: x v: (concat 1 2) from: T}) !- domain +(select {v: (concat [1 2 3] [4]) w: x from: T}) !- domain +(at (select {v: (concat 1 2) from: T}) 'v) -- [1 2] +(at (select {v: (concat 1 2) w: x from: T2}) 'w) -- [1 2] + +;; Multiple hidden text aggregates must reserve every DAG aggregate slot. +(set A (table [x k s] (list [1 2 3 4 5] [0 0 1 2 2] ['a 'b 'c 'd 'e]))) +(at (select {n: (+ (count (concat s "!")) (count (concat s "?"))) by: k from: A asc: k}) 'n) -- [4 2 4] +(at (select {n: (+ (sum x) (count (concat s "?"))) by: k from: A asc: k}) 'n) -- [5 4 11] +(at (select {n: (- (max x) (count (concat s "!"))) by: k from: A asc: k}) 'n) -- [0 2 3] +(at (select {n: (+ (count (concat s "!")) (count (concat s "?"))) by: k from: (select {from: A where: (> x 1)}) asc: k}) 'n) -- [2 2 4] +;; Scalars broadcast to the collection projection's length, in either order. +(at (select {a: [1 2] b: 5 from: T}) 'b) -- [5 5] +(at (select {a: (concat 1 2) b: 5 from: T}) 'b) -- [5 5] +(at (select {b: 5 a: (concat 1 2) from: T}) 'b) -- [5 5] + +;; take: limits a rectangular projection; it cannot repair ragged columns. +(select {b: x a: [1 2] from: T take: 2}) !- domain +;; Top-N and nested count filters must agree with the planner's agg slots. +(at (select {a: (count (concat s "!")) b: (sum x) by: k from: A desc: b take: 1}) 'k) -- [2] +(at (select {from: (select {a: (count (concat s "!")) b: (count x) by: k from: A}) where: (> b 1) asc: k}) 'k) -- [0 2] + +(set B (table [x k s] (list [1 2 3 4 5] [0 0 1 2 2] ['longlong 'longlong 'c 'd 'e]))) +(at (select {a: (sum (strlen (concat s "!"))) b: (sum x) by: k from: B desc: b take: 1}) 'k) -- [2] +(at (select {a: (sum (strlen (concat s "!"))) b: (sum x) by: k from: B desc: a take: 1}) 'k) -- [0] + +;; An aggregate scalar, not just a literal, broadcasts to a collection. +(at (select {a: (concat 1 2) b: (sum x) from: T}) 'b) -- [6 6] +(at (select {b: (sum x) a: (concat 1 2) from: T}) 'b) -- [6 6] +;; A one-row input column is still a column, not a broadcast scalar. +(set O (table [x] (list [7]))) +(select {a: [1 2] b: x from: O}) !- domain +(select {b: x a: [1 2] from: O}) !- domain +(select {a: [1 2] b: (+ x 0) from: O}) !- domain +(at (select {a: [1 2] b: (sum x) from: O}) 'b) -- [7 7] +;; A deferred WHERE selection requires input-aligned collection projections. +(select {a: [1 2] b: 5 from: T where: (> x 1)}) !- length +(select {a: (concat 1 2) b: (sum x) from: T where: (> x 1)}) !- length diff --git a/test/rfl/query/concat_runtime_helpers.rfl b/test/rfl/query/concat_runtime_helpers.rfl new file mode 100644 index 000000000..042928406 --- /dev/null +++ b/test/rfl/query/concat_runtime_helpers.rfl @@ -0,0 +1,41 @@ +(set T (table [x k s] (list [1 2 3 4 5] [0 0 1 1 2] ['a 'b 'c 'd 'e]))) +;; Inlining is optional: multi-statement, captured and recursive helpers keep +;; their argument's query-column provenance when interpreted. +(set mb (fn [v] 1 (concat v 'zz))) +(count (mb ['a 'b])) -- 3 +(at (update {v: (mb s) from: T}) 'v) -- ['azz 'bzz 'czz 'dzz 'ezz] +(at (select {from: T where: (in (mb s) ['azz 'czz])}) 'x) -- [1 3] +(set make-suffix (fn [suffix] (fn [v] (concat v suffix)))) +(set captured (make-suffix 'zz)) +(at (update {v: (captured s) from: T}) 'v) -- ['azz 'bzz 'czz 'dzz 'ezz] +(set rec (fn [v n] (if (> n 0) (self v (- n 1)) (concat v 'zz)))) +(at (update {v: (rec s 3) from: T}) 'v) -- ['azz 'bzz 'czz 'dzz 'ezz] +;; Bound arguments retain collection semantics, including inside opaque calls. +(set mbtwo (fn [a b] 1 (concat a b))) +(set L ['u 'v]) +(update {v: (mbtwo s L) from: T}) !- length +;; A same-named source column must not capture a quoted helper suffix. +(set mbq (fn [v] 1 (concat v 'x))) +(at (update {v: (mbq s) from: T}) 'v) -- ['ax 'bx 'cx 'dx 'ex] +;; Named calls retain their global scope when a query alias has that name. +(set suffix "!") +(set mbg (fn [v] 1 (concat v suffix))) +(at (select {suffix: (upper s) e: (reverse x) v: (mbg s) from: T}) 'v) -- ['a! 'b! 'c! 'd! 'e!] +(at (select {suffix: (upper s) e: (reverse x) v: (mbg suffix) from: T}) 'v) -- ['A! 'B! 'C! 'D! 'E!] +(at ((fn [suffix] (update {v: (mbg s) from: T})) "?") 'v) -- ['a! 'b! 'c! 'd! 'e!] +(set calls 0) +(set effectful (fn [v] (set calls (+ calls 1)) (concat v 'zz))) +(at (update {v: (effectful s) from: T}) 'v) -- ['azz 'bzz 'czz 'dzz 'ezz] +calls -- 1 +;; Aliasing a column object through a global does not make it column-derived. +(set bound-s (at T 's)) +(update {v: (mbtwo s bound-s) from: T}) !- length +;; Errors must unwind the helper scope before the next query. +(set broken (fn [v] 1 missing-global)) +(update {v: (broken s) from: T}) !- name +(at (update {v: (concat s "!") from: T}) 'v) -- ['a! 'b! 'c! 'd! 'e!] + +;; Exceed both the inliner nesting limit and its node budget. +(set sfs (fn [v] (concat v "!"))) +(at (select {n: (+ (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (+ 0 (count (sfs s))))))))))))))))))))))))))) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] +(at (select {n: (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))) (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))))) (+ (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))) (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))))) (+ (+ (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))) (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))))) (+ (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))) (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))))))) (+ (+ (+ (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))) (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))))) (+ (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))) (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))))) (+ (+ (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))) (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))))) (+ (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))) (+ (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0)))) (+ (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))) (+ (+ (+ 0 0) (+ 0 0)) (+ (+ 0 0) (+ 0 0))))))))) (count (sfs s))) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] diff --git a/test/rfl/query/concat_scope.rfl b/test/rfl/query/concat_scope.rfl new file mode 100644 index 000000000..d8c0649cd --- /dev/null +++ b/test/rfl/query/concat_scope.rfl @@ -0,0 +1,41 @@ +(set T (table [x k s] (list [1 2 3 4 5] [0 0 1 1 2] ['a 'b 'c 'd 'e]))) +;; A query must not change collection concat inside user functions. +(set allowed (fn [] (concat ['a 'b] 'c))) +(allowed) -- ['a 'b 'c] +(at (select {from: T where: (in s (allowed))}) 's) -- ['a 'b 'c] +(at (select {from: T where: (> (count (allowed)) 2)}) 's) -- ['a 'b 'c 'd 'e] +(at (update {n: (count (allowed)) from: T}) 'n) -- [3 3 3 3 3] +(set append-c (fn [v] (concat v 'c))) +(at (select {from: T where: (in s (append-c ['a 'b]))}) 's) -- ['a 'b 'c] +;; Literal and global collections have the same meaning on both paths. +(at (select {from: T where: (in s (concat ['a 'b] 'c))}) 's) -- ['a 'b 'c] +(at (select {from: T where: (in s (concat 'a ['b 'c]))}) 's) -- ['a 'b 'c] +(set L ['a 'b]) +(at (select {from: T where: (in s (concat L 'c))}) 's) -- ['a 'b 'c] +(at (select {n: (+ (count (concat L 'c)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [5 5 4] +(at (select {n: (+ (count (concat 'c L)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [5 5 4] +(at (select {n: (+ (count (concat ['a 'b] 'c)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [5 5 4] +(at (select {n: (+ (count (concat (upper L) 'c)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [5 5 4] +(at (select {v: (concat L 'c) from: T}) 'v) -- ['a 'b 'c] +;; Lexical bindings win over a same-named source column. +((fn [s] (at (select {v: (concat s 'c) from: T}) 'v)) ['a 'b]) -- ['a 'b 'c] +;; Force per-group fallback: both argument orders must join column text. +(at (select {n: (+ (count (concat s "!")) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] +(at (select {n: (+ (count (concat "!" s)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] +(at (select {n: (+ (sum (strlen (concat "!" s))) (count (distinct x))) by: k from: T asc: k}) 'n) -- [6 6 3] +(at (select {n: (+ (sum (strlen (concat "!" (upper s)))) (count (distinct x))) by: k from: T asc: k}) 'n) -- [6 6 3] +(at (select {n: (+ (sum (strlen (concat (upper s) "!"))) (count (distinct x))) by: k from: T asc: k}) 'n) -- [6 6 3] +;; Two text columns also keep their row-wise meaning in fallback. +(at (select {n: (+ (sum (strlen (concat s s))) (count (distinct x))) by: k from: T asc: k}) 'n) -- [6 6 3] +;; STR collection semantics match ordinary concat too. +(set V ["a" "b"]) +(set strings (fn [] (concat V "c"))) +(at (select {n: (+ (count (concat V "c")) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 3] +(at (update {n: (count (strings)) from: T}) 'n) -- [2 2 2 2 2] + +;; Inlining preserves column text operations through helper parameters. +(at (select {from: T where: (> (count (append-c s)) 4)}) 's) -- ['a 'b 'c 'd 'e] +(at (select {from: T where: (> (count ((fn [v] (concat v 'c)) s)) 4)}) 's) -- ['a 'b 'c 'd 'e] +(at (select {n: (+ (count (append-c s)) (count (distinct x))) by: k from: T asc: k}) 'n) -- [4 4 2] +;; Variadic text concat may carry the column in its third argument. +(at (select {v: (concat (concat "!" "?" s) "!") from: T}) 'v) -- (as 'SYM ["!?a!" "!?b!" "!?c!" "!?d!" "!?e!"]) diff --git a/test/rfl/query/concat_sparse_topn.rfl b/test/rfl/query/concat_sparse_topn.rfl new file mode 100644 index 000000000..4d549fedb --- /dev/null +++ b/test/rfl/query/concat_sparse_topn.rfl @@ -0,0 +1,4 @@ +;; Sparse keys reach the top-N emission path; dense keys do not. +(set V (as 'SYM (list "a" "bb" "ccc" "dddd" "eeeee" "ffffff" "g"))) +(set TN (table [k y s] (list (* 1000003 (% (* (til 20000) 7919) 2000)) (% (* (til 20000) 15485863) 99991) (at V (% (* (til 20000) 31) 7))))) +(at (select {a: (max (strlen (concat s "!"))) c: (max y) by: k from: TN desc: c take: 3}) 'c) -- [99985 99979 99973] diff --git a/test/rfl/query/group_f32_key.rfl b/test/rfl/query/group_f32_key.rfl new file mode 100644 index 000000000..c1ba25e96 --- /dev/null +++ b/test/rfl/query/group_f32_key.rfl @@ -0,0 +1,30 @@ +;; #760 — an F32 group key read through the shared column reader +;; (read_col_i64) fell to that reader's one-byte default arm: the parallel +;; group hash table hashed and stored one byte of each key, so a multi-core +;; group by an F32 key over more than a morsel of rows (65 536) emitted +;; garbage keys and split or merged groups — on a plain count, on a distinct +;; count beside the key, and for a composite key with an F32 member. The +;; reader now decodes the 4-byte lane, with -0.0 canonicalised to +0.0 as the +;; F64 key readers do. +(set N 100000) +(set T (select {from: (table [p s x] (list (as 'F64 (% (til N) 10)) (take ['a 'b] N) (til N))) p: (as 'F32 p) s: s x: x})) +(set R (select {from: T by: p c: (count x) asc: p})) +(count R) -- 10 +(at R 'p) -- (as 'F64 (til 10)) +(at R 'c) -- (take [10000] 10) +(set Rd (select {from: T by: p n: (count (distinct x)) asc: p})) +(at Rd 'p) -- (as 'F64 (til 10)) +(at Rd 'n) -- (take [10000] 10) +(set Rc (select {from: T by: [p s] c: (count x) n: (count (distinct x)) asc: [p s]})) +(count Rc) -- 10 +(at Rc 'p) -- (as 'F64 (til 10)) +(at Rc 's) -- (take ['a 'b] 10) +(at Rc 'c) -- (take [10000] 10) +(at Rc 'n) -- (take [10000] 10) +(at (select {from: T by: [s p] c: (count x) asc: [s p]}) 'p) -- (as 'F64 [0 2 4 6 8 1 3 5 7 9]) +;; -0.0 and +0.0 are one group on the parallel path too, and a null key its own +(set Z (select {from: (table [z s x] (list (as 'F64 (% (til N) 4)) (take ['a 'b] N) (til N))) z: (as 'F32 (* (if (== z 1.0) -1.0 1.0) (if (< z 2.0) 0.0 z))) s: s x: x})) +(at (select {from: Z by: z c: (count x) asc: z}) 'c) -- [50000 25000 25000] +(at (select {from: Z by: [z s] c: (count x) n: (count (distinct x)) asc: [z s]}) 'n) -- [25000 25000 25000 25000] +(set Q (select {from: (table [z x] (list (as 'F64 (% (til N) 3)) (til N))) z: (as 'F32 (if (== z 0.0) 0Nf z)) x: x})) +(at (select {from: Q by: z c: (count x) asc: z}) 'c) -- [33334 33333 33333] diff --git a/test/rfl/query/group_f64_signed_zero.rfl b/test/rfl/query/group_f64_signed_zero.rfl index 235a6eb1c..f7bf90d8b 100644 --- a/test/rfl/query/group_f64_signed_zero.rfl +++ b/test/rfl/query/group_f64_signed_zero.rfl @@ -103,3 +103,28 @@ ;; folded the zeros) -- an independent oracle for the same count. (count (distinct BU)) -- 199981 (sum (at (select {n: (count v) by: {f: f} from: (table [f v] (list BU (til BN)))}) 'n)) -- 3000000 + +;; ── count(distinct) beside the group: the post-group row→group probe ────── +;; A `(count (distinct x))` beside another aggregate (and a composite key, +;; #756) is served after the grouping by a probe that maps every row back to +;; its group through the key's bits (key_read_i64). The group holds +0.0 for +;; the merged zero group; a row carrying -0.0 read raw missed it and was +;; dropped from the per-group dedup — n fell to 0 for the zero group while +;; the count beside it stayed right. The probe canonicalises the way the +;; grouping does. F64 and F32 keys, one key and a composite, with where:, +;; and the distinct count alone (a composite key that is not dense takes the +;; same probe). +(set CZ (table [p s x] (list (as 'F64 (take (list Z 1.5) 8)) (take ['a 'b 'c 'd] 8) (til 8)))) +(at (select {from: CZ by: [p s] n: (count (distinct x)) c: (count x) asc: [p s]}) 'n) -- [2 2 2 2] +(at (select {from: CZ by: [p s] n: (count (distinct x)) c: (count x) asc: [p s]}) 'c) -- [2 2 2 2] +(at (select {from: CZ by: p n: (count (distinct x)) c: (count x) asc: p}) 'n) -- [4 4] +(at (select {from: CZ by: [p s] n: (count (distinct x)) asc: [p s]}) 'n) -- [2 2 2 2] +(at (select {from: CZ where: (< x 6) by: [p s] n: (count (distinct x)) c: (count x) asc: [p s]}) 'n) -- [2 1 2 1] +;; both signs in one column: the zero group's rows all reach the dedup +(set CZ2 (table [p s x] (list (as 'F64 (take (list 0.0 Z 1.5 Z) 8)) (take ['a 'b] 8) (til 8)))) +(at (select {from: CZ2 by: [p s] n: (count (distinct x)) c: (count x) asc: [p s]}) 'n) -- [2 4 2] +(at (select {from: CZ2 by: p n: (count (distinct x)) c: (count x) asc: p}) 'n) -- [6 2] +;; F32 (the cast is a projection) +(set CZ3 (select {from: CZ p: (as 'F32 p) s: s x: x})) +(at (select {from: CZ3 by: [p s] n: (count (distinct x)) c: (count x) asc: [p s]}) 'n) -- [2 2 2 2] +(at (select {from: CZ3 by: p n: (count (distinct x)) c: (count x) asc: p}) 'n) -- [4 4] diff --git a/test/rfl/query/group_key_null_flag.rfl b/test/rfl/query/group_key_null_flag.rfl new file mode 100644 index 000000000..18cc747f4 --- /dev/null +++ b/test/rfl/query/group_key_null_flag.rfl @@ -0,0 +1,61 @@ +;; group_key_null_flag.rfl — a grouped select whose `where:` removes every +;; null key row must not flag the key column as holding nulls. +;; +;; The parallel dense grouping path (large inputs) emits the key column from +;; slot codes and inherited the source column's "may have nulls" flag; the +;; same query over the filtered table materialized first carried no flag, so +;; the two spelled one result differently on the wire (found by the nested +;; select differential fuzzer). Byte 17 of a serialized vector is its attrs. +(set T0 (table [a k p] (list [1 2 1] [1 0N 1] [10.3 5.1 8.4]))) +(set T (take T0 131073)) +(set got (select {from: T where: (== a 1) by: k total: (sum p)})) +(set want (select {from: (do (select {from: T where: (== a 1) k: k p: p})) by: k total: (sum p)})) +(count got) -- 1 +(at (ser (at got 'k)) 17) -- 0x00 +(all (== (ser got) (ser want))) -- true +;; a null key that survives the filter keeps the flag +(set got2 (select {from: T where: (> p 5.0) by: k total: (sum p)})) +(at got2 'k) -- [1 0Nl] +(at (ser (at got2 'k)) 17) -- 0x40 +(at (select {from: (take T0 300) where: (> p 5.0) by: k total: (sum p)}) 'k) -- [1 0Nl] +;; the dense strategy that writes keys from slot codes (many distinct keys +;; relative to the rows, so the slot slab outweighs the row traffic even +;; with the two workers the harness runs) applies the same rule +(set i (til 131073)) +(set TD (table [a k p] (list (% i 5) (as 'I64 (% i 60000)) (as 'F64 i)))) +(set TD (update {k: (if (== a 4) 0N k) from: TD})) +(set gotd (select {from: TD where: (< a 4) by: k total: (sum p)})) +(count gotd) -- 48000 +(at (ser (at gotd 'k)) 17) -- 0x00 +(all (== (ser gotd) (ser (select {from: (do (select {from: TD where: (< a 4) k: k p: p})) by: k total: (sum p)})))) -- true +;; and so does the composite-key path over many slots +(set i (til 1000000)) +(set TK (table [a k b p] (list (% i 5) (as 'I64 (% i 2000)) (as 'I64 (% (div i 7) 500)) (as 'F64 i)))) +(set TK (update {k: (if (== a 4) 0N k) from: TK})) +(set gotk (select {from: TK where: (< a 4) by: [k b] total: (sum p)})) +(count gotk) -- 11200 +(at (ser (at gotk 'k)) 17) -- 0x00 +;; the legacy wide-key path (an F64 key, alone or beside another key) applies +;; the same rule; a null key that survives keeps its flag there too +(set i (til 131073)) +(set TF (table [a k f p] (list (% i 5) (% i 7) (as 'F64 (% i 7)) (as 'F64 i)))) +(set TF (update {k: (if (== a 4) 0N k) f: (if (== a 4) 0Nf f) from: TF})) +(set RF (do (select {from: TF where: (< a 4)}))) +(set qf (select {from: TF where: (< a 4) by: f s: (sum p)})) +(at (ser (at qf 'f)) 17) -- 0x00 +(all (== (ser qf) (ser (select {from: RF by: f s: (sum p)})))) -- true +(set qkf (select {from: TF where: (< a 4) by: [k f] s: (sum p)})) +(at (ser (at qkf 'k)) 17) -- 0x00 +(at (ser (at qkf 'f)) 17) -- 0x00 +(set qn (select {from: TF where: (< a 5) by: f s: (sum p)})) +(count qn) -- 8 +(at (ser (at qn 'f)) 17) -- 0x40 +;; a single null key landing on the last slot of a scan block (4095 non-null +;; keys, then the null) keeps the flag; the null rows are chosen by the +;; quotient so that every residue still occurs +(set i (til 131073)) +(set TB (table [a k p] (list (% i 5) (as 'I64 (% i 4095)) (as 'F64 i)))) +(set TB (update {k: (if (== (% (div i 4095) 7) 0) 0N k) from: TB})) +(set gotb (select {from: TB by: k total: (sum p)})) +(count gotb) -- 4096 +(at (ser (at gotb 'k)) 17) -- 0x40 diff --git a/test/rfl/query/helper_bytecode_provenance.rfl b/test/rfl/query/helper_bytecode_provenance.rfl new file mode 100644 index 000000000..e7ce29bc4 --- /dev/null +++ b/test/rfl/query/helper_bytecode_provenance.rfl @@ -0,0 +1,650 @@ +(set T (table [x s] (list [1 2 3] ['a 'b 'c]))) +(set TS (table [x s suffix] (list [1 2 3] ['a 'b 'c] ['p 'q 'r]))) +;; A helper called from a query fallback runs as bytecode: return, lazy +;; arguments read twice, deep recursion and error locations behave as they +;; do outside a query. +(set h (fn [v] (return (* v 2)) 0)) +(at (select {v: (h x) from: T}) 'v) -- [2 4 6] +(at (update {v: (h x) from: T}) 'v) -- [2 4 6] +(at (select {from: T where: (in (h x) [2 6])}) 'x) -- [1 3] +(set hloop (fn [v] (let i 0) (while (< i 10) (let i (+ i 1)) (if (== i 4) (return (+ v i)))) -1)) +(at (select {v: (hloop x) from: T}) 'v) -- [5 6 7] +(set d (fn [v] 1 (+ v v))) +(at (select {r: (d (sum x)) from: T}) 'r) -- [12] +(at (update {r: (d (max x)) from: T}) 'r) -- [6 6 6] +(at (select {r: ((fn [v] 1 (if (> v 0) v 0)) (first x)) from: T}) 'r) -- [1] +(set rd (fn [n] (if (== n 0) 0 (+ 1 (self (- n 1)))))) +(at (select {v: (+ x (rd 100)) from: T}) 'v) -- [101 102 103] +(set bad (fn [v] 1 (+ v 's))) +(select {v: (bad x) from: T}) !- type +;; Row provenance follows values through locals, nested calls and results: +;; a column argument keeps text concat, a bound vector stays a collection. +(set hlet (fn [v] (let w (upper v)) (concat w "!"))) +(at (update {r: (hlet s) from: T}) 'r) -- ['A! 'B! 'C!] +(at (select {from: T where: (in (hlet s) ['A! 'C!])}) 'x) -- [1 3] +(at (select {n: (count (hlet s)) by: x from: T asc: x}) 'n) -- [1 1 1] +(set hnest (fn [a b c] 1 (concat a (concat b c)))) +(at (update {r: (hnest s "!" "?") from: T}) 'r) -- ['a!? 'b!? 'c!?] +(set sub1 (fn [v] 1 (concat v "!"))) +(set hsub (fn [v] 1 (sub1 (substr v 0 1)))) +(at (update {r: (hsub s) from: T}) 'r) -- ['a! 'b! 'c!] +(set mb (fn [v] 1 (concat v 'zz))) +(at (select {n: (+ (count (mb s)) (count (distinct x))) by: x from: T asc: x}) 'n) -- [2 2 2] +(set L ['u 'v]) +(set mbtwo (fn [a b] 1 (concat a b))) +(update {v: (mbtwo s L) from: T}) !- length +;; A free name that is a source column is the row's cell, with provenance, +;; exactly as the single-statement form the planner inlines; an output +;; alias never captures it, and a missing global stays an error. +(set hcol (fn [v] 1 (concat v s))) +(at (select {v: (hcol s) from: T}) 'v) -- ['aa 'bb 'cc] +(at (select {v: ((fn [v] (concat v s)) s) from: T}) 'v) -- ['aa 'bb 'cc] +(at (select {from: T where: (in (hcol s) ['aa 'cc])}) 'x) -- [1 3] +(set hclo (fn [v] 1 ((fn [w] (concat w s)) v))) +(at (select {v: (hclo s) from: T}) 'v) -- ['aa 'bb 'cc] +(set suffix "!") +(set mbg (fn [v] 1 (concat v suffix))) +(at (select {v: (mbg s) from: TS}) 'v) -- ['ap 'bq 'cr] +(at (select {suffix: (upper s) e: (reverse x) v: (mbg s) from: TS}) 'v) -- ['ap 'bq 'cr] +(at (select {suffix: (upper s) e: (reverse x) v: (mbg s) from: T}) 'v) -- ['a! 'b! 'c!] +(set ha (fn [v] 1 (concat v aa))) +(select {aa: (upper s) e: (reverse x) v: (ha s) from: T}) !- name +;; Outside a query nothing changes. +(mb ['a 'b]) -- ['a 'b 'zz] +(h 5) -- 10 +(hcol 'q) !- name +;; At the query level, an opaque helper given row data yields row data. +(set id (fn [v] 1 v)) +(at (select {v: (concat (id s) "!") e: (reverse x) from: T}) 'v) -- ['a! 'b! 'c!] +(at (update {v: (mb (id s)) from: T}) 'v) -- ['azz 'bzz 'czz] +(at (select {from: T where: (in (concat (id s) "!") ['a! 'c!])}) 'x) -- [1 3] +(at (select {n: (count (concat (id s) "!")) by: x from: T asc: x}) 'n) -- [1 1 1] +(at (select {v: (concat s (id L)) from: T}) 'v) -- ['a 'b 'c 'u 'v] +;; A source column shadows a global helper of the same name inside a helper +;; body, on the planned path and in fallbacks alike. +(set s (fn [v] v)) +(set hs (fn [v] 1 (s v))) +(select {v: (hs x) from: T}) !- type +(select {v: ((fn [v] (s v)) x) from: T}) !- name +(set TN (table [x q] (list [1 2 3] [4 5 6]))) +(at (select {v: (hs x) from: TN}) 'v) -- [1 2 3] +;; A lambda written inline in the query that reaches the runtime (several +;; statements, so the planner does not substitute it) is still query text: +;; its literals follow the column rule, which bytecode constants could not. +(at (select {v: ((fn [v] 1 (concat v 's)) s) e: (reverse x) from: T}) 'v) -- ['aa 'bb 'cc] +(at (update {v: ((fn [v] 1 (concat v 's)) s) from: T}) 'v) -- ['aa 'bb 'cc] +(at (select {o: ((fn [v] 1 'x) s) e: (reverse x) from: T}) 'o) -- [1 2 3] +;; A free source column keeps its provenance on every read, not only the +;; first, through concat and through a row-wise builtin. +(set h2 (fn [v] 1 (concat (concat s v) s))) +(at (select {v: (h2 s) from: T}) 'v) -- ['aaa 'bbb 'ccc] +(at (update {v: (h2 s) from: T}) 'v) -- ['aaa 'bbb 'ccc] +(at (select {from: T where: (in (h2 s) ['aaa 'ccc])}) 'x) -- [1 3] +(set h3 (fn [v] 1 (concat (upper s) s))) +(at (update {v: (h3 x) from: T}) 'v) -- ['Aa 'Bb 'Cc] +(at (select {n: (count (h3 x)) by: x from: T asc: x}) 'n) -- [1 1 1] +;; Per group, a free source column is the group's rows, like a parameter. +(set h4 (fn [v] 1 (count s))) +(at (select {n: (first (h4 x)) by: x from: T asc: x}) 'n) -- [1 1 1] +(at (update {n: (first (h4 x)) by: x from: T}) 'n) -- [1 1 1] +;; An opaque helper can be the group key: it is evaluated once over the +;; table and grouped as a hidden column named after its column argument. +(key (select {n: (count x) by: (mb s) from: T})) -- ['s 'n] +(at (select {n: (count x) by: (mb s) from: T asc: s}) 's) -- ['azz 'bzz 'czz] +(at (select {n: (sum x) by: (hlet s) from: T desc: n}) 'n) -- [3 2 1] +(at (select {n: (sum x) by: (hlet s) from: T where: (> x 1) asc: s}) 's) -- ['B! 'C!] +(count (select {n: (count x) by: (mb s) from: T desc: n take: 2})) -- 2 +;; Without row data among the operands, concat inside any function keeps +;; collection semantics, whatever called it. +(set cc (fn [acc y] (concat acc y))) +(at (select {v: (fold cc ['p 'q 'r]) from: T}) 'v) -- (list ['p 'q 'r] ['p 'q 'r] ['p 'q 'r]) +(set two (fn [] 1 (concat 'a 'b))) +(at (update {n: (+ x (count (two))) from: T}) 'n) -- [3 4 5] +(set gx (fn [a] (concat a 'x))) +(at (update {v: (map gx s) from: T}) 'v) -- (list ['a 'x] ['b 'x] ['c 'x]) +;; Only deterministic, effect-free builtins are inlined: a random input is +;; computed once, an effectful argument runs once per row, a raise raises. +(set gg (fn [g] (== g g))) +(at (select {v: (gg (first (guid 1))) e: x from: T}) 'v) -- [true true true] +(set dup (fn [g] (count (distinct (concat g g))))) +(at (select {v: (dup (guid 3)) e: (reverse x) from: T}) 'v) -- [3 3 3] +(set CNT 0) +(set eff (fn [v] (set CNT (+ CNT 1)) v)) +(set ign (fn [a b] a)) +(at (select {v: (ign s (map eff ['p])) from: T}) 'v) -- ['a 'b 'c] +CNT -- 3 +(select {v: (ign s (raise 'boom)) from: T}) !- domain +;; A caller's locals never reach a helper, grouped or not; a nested query +;; inside a helper leaves the enclosing group's rows in place. +(set TY (table [k x y s] (list [0 0 1 1 2] [1 2 3 4 5] [10 20 30 40 50] ['a 'b 'c 'd 'e]))) +(set cs (fn [v] 1 (count s))) +(set fs (fn [v] 1 (first s))) +((fn [t] (let s 'LOCAL) (at (select {r: (fs x) by: k from: t asc: k}) 'r)) TY) -- ['a 'c 'e] +((fn [t] (let s (til 7)) (at (select {r: (cs x) by: k from: t asc: k}) 'r)) TY) -- [2 2 1] +(set nq (fn [v] 1 (let q (select {r: (cs x) by: k from: TY})) (count s))) +(at (select {n: (nq x) by: k from: TY asc: k}) 'n) -- [2 2 1] +;; Reordering a column keeps its rows, in a helper as in the query. +(set rv (fn [v] 1 (concat v (reverse v)))) +(at (update {v: (rv s) from: TY}) 'v) -- ['ae 'bd 'cc 'db 'ea] +;; A bound vector returned by a helper is not row data. +(set L3 ['p 'q 'r]) +(set k3 (fn [v] 1 L3)) +(select {v: (concat (k3 s) "!") from: T}) !- type +;; Provenance through a cast or a bucket bound with let, and through a +;; conditional form over a let local. +(set hx (fn [v] 1 (let w (as 'SYM v)) (concat w "!"))) +(at (select {from: T where: (in (hx s) ['a! 'c!])}) 'x) -- [1 3] +(set hb (fn [v] 1 (let w (xbar v 2)) (+ w 0))) +(at (select {n: (sum (hb x)) by: x from: T asc: x}) 'n) -- [0 2 2] +(set hw (fn [v] 1 (let w v) (or false (in (concat w "!") ['a! 'c!])))) +(at (select {from: T where: (hw s)}) 'x) -- [1 3] +;; Every grouped result keeps the requested output order. +(key (select {n: (+ (count s) 1) m: (sum x) by: k from: TY})) -- ['k 'n 'm] +;; A nested query's result is a new value, not the outer query's row data; +;; a let local in an interpreted lambda and a try handler's value keep the +;; provenance of what they hold. +(set U (table [w y] (list ['p 'q 'r] [1 2 3]))) +(set id1 (fn [z] 1 z)) +(at (select {v: (concat (at (select {w: (id1 w) from: U}) 'w) 'zz) from: T}) 'v) -- ['p 'q 'r 'zz] +(at (select {from: T where: (in (at (select {w: (id1 w) from: U}) 'w) ['p])}) 'x) -- [1] +(at (select {r: ((fn [v] (let w v) (concat w "!")) s) from: T}) 'r) -- ['a! 'b! 'c!] +(set ht (fn [v] (try (+ v 's) (fn [e] v)))) +(at (update {r: (concat (ht s) "!") from: T}) 'r) -- ['a! 'b! 'c!] +(at (select {from: T where: (in (concat (ht s) "!") ['a! 'c!])}) 'x) -- [1 3] +;; A null operand follows the kernel's null rule row by row too. +(set T4 (table [x s] (list [1 2 3 4] (as 'SYM ["a" "" "c" "d"])))) +(at (select {r: (concat s "") e: (reverse x) from: T4}) 'r) -- (as 'SYM ["" "" "" ""]) +;; An opaque by: key sees the rows where: keeps, is named like a planned +;; key, and a body with a condition over one value runs row by row. +(set TB (table [v g] (list [1 2 3 10 20 30] ['a 'a 'b 'b 'c 'c]))) +(set ha (fn [v] 1 (> v (avg v)))) +(at (select {n: (count v) by: (ha v) from: TB where: (< v 5)}) 'n) -- [2 1] +(at (select {n: (count v) by: (ha v) from: TB where: (< v 5)}) 'v) -- [false true] +(at (select {n: (count (distinct g)) by: (ha v) from: TB where: (< v 5)}) 'n) -- [1 1] +(set dbl (fn [v] 1 (* v 2))) +(key (select {n: (count (distinct x)) by: (dbl x) from: T})) -- ['x 'n] +(set hif (fn [v] 1 (if (> v 2) (* v 10) v))) +(at (select {n: (count x) by: (hif x) from: (table [x] (list [1 2 3 4]))}) 'x) -- [1 2 30 40] +;; Provenance is relative to the innermost query: a nested query inside a +;; helper does not take the caller's row value as its own row data. +(set hn (fn [v] 1 (at (select {r: (concat w v) from: U}) 'r))) +(set OUT 0) +(set gset (fn [v] 1 (set OUT (hn v)) 0)) +(update {r: (gset s) from: T}) +OUT -- ['p 'q 'r 'a 'b 'c] +;; A let, a sequence or a loop in an opaque key's body keeps the key whole; +;; only a condition over one value makes it row by row, and a helper bound +;; with let is looked through as a global one is. +(set hlet2 (fn [v] (let m (min v)) (- v m))) +(at (select {n: (count v) by: (hlet2 v) from: TB}) 'v) -- [0 1 2 9 19 29] +(at (select {n: (count v) by: (hlet2 v) from: TB where: (> v 2)}) 'v) -- [0 7 17 27] +((fn [t] (let h (fn [v] 1 (if (> v 2) (* v 10) v))) (at (select {n: (count x) by: (h x) from: t}) 'x)) (table [x] (list [1 2 3 4]))) -- [1 2 30 40] +;; A null cell is empty text row by row, as the vector kernel reads it; a +;; null literal still nulls the row. +(at (select {r: (concat s 'zz) e: (reverse x) from: T4}) 'r) -- ['azz 'zz 'czz 'dzz] +;; A lambda inside a named closure's body is that body's text: its quoted +;; symbols are symbols. set keeps its value's provenance; so does a try +;; handler's value used inside the helper. +(set mk (fn [a] (fn [b] ((fn [z] (concat z (concat 'x a))) b)))) +(set cl (mk 'k)) +(at (select {r: (cl s) e: (reverse x) from: T}) 'r) -- (list ['a 'x 'k] ['b 'x 'k] ['c 'x 'k]) +(at (select {r: ((fn [v] (concat (set G v) "!")) s) e: (reverse x) from: T}) 'r) -- ['a! 'b! 'c!] +(set hy (fn [v] 1 (concat (try (+ v 's) (fn [e] v)) "!"))) +(at (select {r: (hy s) e: (reverse x) from: T}) 'r) -- ['a! 'b! 'c!] +(at (select {r: ((fn [v] 1 (concat (ht v) "!")) s) e: (reverse x) from: T}) 'r) -- ['a! 'b! 'c!] +(key (select {by: (dbl x) from: T})) -- ['x 's] +;; A closure created inside a query while several row bindings are live: +;; its capture holds every binding plus their provenance. +(set TC (table [x s] (list [1 2 3 4] ['a 'b 'c 'd]))) +(at (select {v: ((fn [a] (let b 1) (let c 2) (let d 3) ((fn [z] (concat z (if (> b 0) "!" "?"))) a)) s) e: (reverse x) from: TC}) 'v) -- ['a! 'b! 'c! 'd!] +(at (select {v: ((fn [a] (let b 1) (let c 2) (let d 3) (let e 4) (let f 5) (let g 6) (let h 7) (let i 8) (let j 9) (let k 10) (let l 11) ((fn [z] (concat z (if (> l 0) "!" "?"))) a)) s) e: (reverse x) from: TC}) 'v) -- ['a! 'b! 'c! 'd!] +;; A filtered COUNT over a nullable column counts the kept rows, with or +;; without a computed input. +(set TN (table [k x s] (list [0 0 1 1 2] [1 2 3 4 5] (as 'SYM ["a" "" "c" "" "e"])))) +(at (select {n: (count s) by: k from: TN where: (> x 1) asc: k}) 'n) -- [1 2 1] +(at (select {n: (count (upper s)) by: k from: TN where: (> x 1) asc: k}) 'n) -- [1 2 1] +;; A closure created directly in a per-row expression with exactly four +;; live cells (no call frame in between): the capture must have room for +;; its provenance entry. +(set T4C (table [a b c d] (list ['p 'q] ['r 's] ['t 'u] ['v 'w]))) +(at (select {v: (at (map (fn [z] (concat z "!")) (list a b c d)) 0) e: (reverse a) from: T4C}) 'v) -- ['p! 'q!] +;; A closure stores no provenance. Called while the frames it captured from +;; are live, its captures take the provenance their bindings have now, +;; relative to the innermost query; an escaped closure's captures are data. +(set hc (fn [v] 1 (let f (fn [z] (concat z v))) (at (select {q: (f w) from: U}) 'q))) +(set OUT2 0) +(update {r: ((fn [v] 1 (set OUT2 (hc v)) 0) s) from: T}) +OUT2 -- (list ['p 'a 'b 'c] ['q 'a 'b 'c] ['r 'a 'b 'c]) +(set hy2 (fn [v] 1 (at (select {r: (concat w (try (+ v 's) (fn [e] v))) from: U}) 'r))) +(set OUT3 0) +(update {r: ((fn [v] 1 (set OUT3 (hy2 v)) 0) s) from: T}) +OUT3 -- ['p 'q 'r 'a 'b 'c] +(set hc2 (fn [v] 1 (let f (fn [z] z)) (at (select {q: (concat w (f v)) from: U}) 'q))) +(set OUT4 0) +(update {r: ((fn [v] 1 (set OUT4 (hc2 v)) 0) s) from: T}) +OUT4 -- ['p 'q 'r 'a 'b 'c] +;; The opaque-key gate: and/or work elementwise, a global helper's body +;; resolves names globally, and an if over an aggregate condition is one +;; value for the whole column. +(set hand (fn [v] 1 (and (> v (avg v)) (< v 25)))) +(at (select {n: (count v) by: (hand v) from: TB}) 'v) -- [false true] +(set hmin (fn [v] (- v (min v)))) +(set hg (fn [v] 1 (hmin v))) +((fn [t] (let hmin (fn [v] (if (> v 2) (* v 10) v))) (at (select {n: (count v) by: (hg v) from: t}) 'v)) TB) -- [0 1 2 9 19 29] +(set hifl (fn [v] (let m (if (> (count v) 0) (min v) 0)) (- v m))) +(at (select {n: (count v) by: (hifl v) from: TB}) 'v) -- [0 1 2 9 19 29] +(at (select {n: (count v) by: ((fn [v] (let m (min v)) (- v m)) v) from: TB}) 'v) -- [0 1 2 9 19 29] +;; A null STR literal nulls the row on both paths; a null cell in a compiled +;; helper is empty text; return ends the lambda with its value (so the +;; concat around it never runs) and passes the value's provenance through. +(set TS2 (table [x t] (list [1 2] (list "a" "b")))) +(at (select {r: (concat t "") e: (reverse x) from: TS2}) 'r) -- (as 'STR ["" ""]) +(set hz (fn [v] 1 (concat v 'zz))) +(at (select {r: (hz s) e: (reverse x) from: T4}) 'r) -- ['azz 'zz 'czz 'dzz] +(at (select {r: ((fn [v] 1 (concat (return v) "!")) s) e: (reverse x) from: T}) 'r) -- ['a 'b 'c] +(at (select {r: ((fn [v] 1 (return (concat v "!")) 'never) s) e: (reverse x) from: T}) 'r) -- ['a! 'b! 'c!] +;; A closure's capture flags live in the query frame it was made under and +;; apply only while that frame is the innermost query; identity of the +;; captured object never matters, nor which compiled frame calls it. +(set mk2 (fn [c] (fn [z] (concat z c)))) +(set E2 (mk2 (at T 's))) +(set hk (fn [v] (take (count (first (map E2 ['p]))) (count v)))) +(at (update {r: (hk s) from: T}) 'r) -- [4 4 4] +(set hd3 (fn [v] (let d (at T 's)) (try (+ d 's) (fn [e] (count (concat 'p d)))))) +(at (update {r: (hd3 s) from: T}) 'r) -- [4 4 4] +(set G (fn [f u] 1 (take (count (first (map f ['p]))) (count u)))) +(set H (fn [v] 1 (let f (fn [z] (concat z v))) (at (update {q: (G f s) from: T}) 'q))) +(at (update {r: (H s) from: T}) 'r) -- [4 4 4] +(set hr (fn [v f d] 1 (if (== d 0) (hr ['x 'y] (fn [z] (concat z v)) 1) (take (count (first (map f ['p]))) 3)))) +(set hr2 (fn [v d] 1 (let f (fn [z] (concat z v))) (if (== d 0) (hr2 ['x 'y] 1) 0) (take (count (first (map f ['p]))) 3))) +(at (update {r: (hr s 0 0) from: T}) 'r) -- [3 3 3] +(at (update {r: (hr2 s 0) from: T}) 'r) -- [3 3 3] +;; A closure made in a compiled helper and called through another function. +(set h1 (fn [v] 1 (let f (fn [z] (concat z v))) (count (first (map (fn [g] (g 'p)) (list f)))))) +(at (update {r: (h1 s) from: T}) 'r) -- [3 3 3] +;; The opaque key is evaluated whole; only a conditional that actually +;; tested a vector derived from the rows makes it run row by row. +(set N0 0) +(set clampz (fn [m] (if (> m 0) m 0))) +(at (select {n: (count v) by: ((fn [v] 1 (if (> (count v) N0) (- v (min v)) v)) v) from: TB}) 'v) -- [0 1 2 9 19 29] +(at (select {n: (count v) by: ((fn [v] (let m (min v)) (if (> m 0) (- v m) v)) v) from: TB}) 'v) -- [0 1 2 9 19 29] +(at (select {n: (count v) by: ((fn [v] 1 (- v (clampz (min v)))) v) from: TB}) 'v) -- [0 1 2 9 19 29] +(at (select {n: (count v) by: ((fn [v] 1 (if (in 10 v) (- v (min v)) v)) v) from: TB}) 'v) -- [0 1 2 9 19 29] +(at (select {n: (count v) by: ((fn [v] 1 (if (== (type v) 'I64) (- v (min v)) v)) v) from: TB}) 'v) -- [0 1 2 9 19 29] +;; Two STR literals join as strings on both paths; a try fallback value +;; keeps its provenance like a handler's result. +(set TS3 (table [x t] (list [1 2 3] (list "a" "" "c")))) +(at (select {r: (concat "" "x") e: (reverse x) from: TS3}) 'r) -- (list "x" "x" "x") +(at (select {r: ((fn [v] (concat (try (+ v 's) v) "!")) s) e: (reverse x) from: T}) 'r) -- ['a! 'b! 'c!] +;; A closure's capture flags live on the closure with the serial of the +;; query frame it was made under; no record is keyed by address, so a dead +;; closure's address cannot lend its flags, and lookups are constant time. +(set LX ['x 'y]) +(set mkf (fn [v] 1 (let f (fn [z] (concat z v))) (count (first (map f ['p]))))) +(set hsix (fn [v] 1 (set OUT6 (map (fn [i] (if (== 0 (% i 2)) (mkf v) (mkf LX))) (til 6))) 0)) +(update {r: (hsix s) from: T}) +OUT6 -- [3 3 3 3 3 3] +;; A conditional that tests any vector during the whole-column run of an +;; opaque key sends it row by row, whatever produced the vector; so does a +;; whole-column run that fails. +(at (select {n: (count v) by: ((fn [v] 1 (if (> (fill 0 v) 2) (* v 10) v)) v) from: TB}) 'v) -- [1 2 30 100 200 300] +(set gt2 ((fn [t] (fn [w] (> w t))) 2)) +(at (select {n: (count v) by: ((fn [v] 1 (if (gt2 v) (* v 10) v)) v) from: TB}) 'v) -- [1 2 30 100 200 300] +(at (select {n: (count v) by: ((fn [v] 1 (if (> v 2) (count (til v)) v)) v) from: TB}) 'v) -- [1 2 3 10 20 30] +(at (select {n: (count v) by: ((fn [v] 1 (eval (list 'if (list '> v 2) (list '* v 10) v))) v) from: TB}) 'v) -- [1 2 30 100 200 300] +;; Closures compile, with their captures loaded as fixed values: a +;; recursive closure called from a compiled helper keeps bytecode's depth, +;; and a closure passed through another function keeps its environment, +;; inside and outside a query. +(set rr (((fn [a] (fn [b] (fn [n] (if (== n 0) 0 (+ 1 (self (- n 1))))))) 1) 2)) +(set callr (fn [n] 1 (rr n))) +(callr 50) -- 50 +((fn [g] (g 'p)) (fn [z] (concat z 'q))) -- ['p 'q] +(set mkadd (fn [k] (fn [v] (+ v k)))) +((mkadd 1) 2) -- 3 +(set outer2 (fn [a] (fn [b] ((fn [z] (concat z (concat 'x a))) b)))) +((outer2 'k) 'q) -- ['q 'x 'k] +;; A compiled try with a fallback value keeps that value's provenance. +(set hf (fn [v] 1 (concat (try (+ v 's) v) "!"))) +(at (select {r: (hf s) e: (reverse x) from: T}) 'r) -- ['a! 'b! 'c!] + +;; ── a whole-column key run that fails is swallowed whole ────────────────── +;; Its `raise` payload and trace go with it: the next `try` anywhere gets its +;; own error, not the key's. +(set TB9 (table [v g] (list [1 2 3 10 20 30] ['a 'a 'b 'b 'c 'c]))) +(set kneg (fn [v] 1 (if (< v 0) (raise 'negative) (% v 7)))) +(at (select {n: (count v) by: (kneg v) from: TB9}) 'v) -- [1 2 3 6] +(try (+ 1 'a) (fn [e] e)) -- 0 + +;; ── a key body with an effect runs once per row ─────────────────────────── +;; It is never evaluated whole first, so the effect is not repeated. +(set CNT9 0) +(set kc9 (fn [v] (set CNT9 (+ CNT9 1)) (if (< v 5) 0 1))) +(at (select {n: (count v) by: (kc9 v) from: TB9}) 'n) -- [3 3] +CNT9 -- 6 +(set CNT9 0) +(set kp9 (fn [v] (set CNT9 (+ CNT9 1)) (% v 7))) +(at (select {n: (count v) by: (kp9 v) from: TB9}) 'v) -- [1 2 3 6] +CNT9 -- 6 +;; a pure body with a scalar condition keeps the column whole +(set hmin9 (fn [v] (if (> (min v) 0) (- v 1) v))) +(at (select {n: (count v) by: (hmin9 v) from: TB9}) 'v) -- [0 1 2 9 19 29] + +;; ── a vector condition in a compiled key sends it row by row ────────────── +;; `kfill9` is a global helper with no captures, so it runs as bytecode; the +;; VM's conditional counts the vector test, as the tree walker's does. +(set kfill9 (fn [v] (let w (fill 0 v)) (if (< w 3) v (* v 10)))) +(at (select {n: (count v) by: (kfill9 v) from: TB9}) 'v) -- [1 2 30 100 200 300] + +;; ── a lambda written in query text keeps the query's literal rule ───────── +;; even with nothing to capture: `'p` is the column, so the join is row-wise. +(set T9 (table [v p] (list ["1" "2" "3"] ['x 'y 'z]))) +(at (select {r: ((fn [a] (concat 'p a)) v) from: T9}) 'r) -- ["x1" "y2" "z3"] +;; a lambda with nothing to capture at all is still query text +(at (select {r: ((fn [] (concat 'p "!"))) from: T9}) 'r) -- [x! y! z!] +;; return ends a lambda written in query text, which stays interpreted +(at (select {r: ((fn [a] (return (concat a "!")) a) v) from: T9}) 'r) -- ["1!" "2!" "3!"] + +;; ── a closure is never inlined into a query ─────────────────────────────── +;; Its body reads its captures; inlined, a captured name would read a source +;; column or a global of that name. Whether the closure has run before (it +;; compiles on its second call) must not matter. +(set mk9 (fn [s] (fn [v] (concat v s)))) +(set f9 (mk9 "!")) +(set TC9 (table [name s] (list ["a" "b"] ["x" "y"]))) +(at (select {r: (f9 name) e: (reverse s) from: TC9}) 'r) -- ["a!" "b!"] +(at (select {r: (f9 name) from: TC9}) 'r) -- ["a!" "b!"] +(count (select {from: TC9 where: (== (f9 name) "a!")})) -- 1 +(f9 "q") -- "q!" +(f9 "q") -- "q!" +(at (select {r: (f9 name) e: (reverse s) from: TC9}) 'r) -- ["a!" "b!"] +(at (select {r: (f9 name) from: TC9}) 'r) -- ["a!" "b!"] +(set G9 "g") +(set mkg9 (fn [G9] (fn [v] (concat v G9)))) +(set fg9 (mkg9 "!")) +(at (select {r: (fg9 name) e: (reverse s) from: TC9}) 'r) -- ["a!" "b!"] +(at (select {r: (fg9 name) from: TC9}) 'r) -- ["a!" "b!"] +;; a closure can be the key too, pure or not; its capture is never a column +(set mkk9 (fn [c] (fn [v] (% v c)))) +(set kk9 (mkk9 7)) +(at (select {n: (count v) by: (kk9 v) from: TB9}) 'v) -- [1 2 3 6] +(set CNT9 0) +(set mki9 (fn [c] (fn [v] (set CNT9 (+ CNT9 1)) (% v c)))) +(set ki9 (mki9 7)) +(at (select {n: (count v) by: (ki9 v) from: TB9}) 'v) -- [1 2 3 6] +CNT9 -- 6 + +;; ── purity follows the callee wherever it is bound ──────────────────────── +;; A pure helper reached through a parameter, a let, or a capture keeps the +;; whole-column semantics; only an effect sends the body row by row. +(set T10 (table [v] (list [1 2 3 4 5 6]))) +(set kg10 (fn [v] 1 (> (- v (avg v)) 0))) +(at (select {n: (count v) by: (kg10 v) from: T10}) 'n) -- [3 3] +(set grp10 (fn [t k] (at (select {n: (count v) by: (k v) from: t}) 'n))) +(grp10 T10 kg10) -- [3 3] +(set kl10 (fn [v] 1 (let f (fn [x] (- x (avg x)))) (> (f v) 0))) +(at (select {n: (count v) by: (kl10 v) from: T10}) 'n) -- [3 3] +(set mkc10 (fn [hcap10] (fn [v] (> (hcap10 v) 0)))) +(set kc10 (mkc10 (fn [x] (- x (avg x))))) +(at (select {n: (count v) by: (kc10 v) from: T10}) 'n) -- [3 3] +(set km10 (fn [v] 1 (> v (mavg 3 v)))) +(at (select {n: (count v) by: (km10 v) from: T10}) 'n) -- [1 5] +;; ... through a let alias of a pure helper, and a map or fold over a list +;; of pure helpers: the key means what (kg10 v) means +(set kal10 (fn [v] (let g kg10) (g v))) +(at (select {n: (count v) by: (kal10 v) from: T10}) 'n) -- [3 3] +(set kal210 (fn [v] (let g kg10) (let g2 g) (g2 v))) +(at (select {n: (count v) by: (kal210 v) from: T10}) 'n) -- [3 3] +(set kmap10 (fn [v] (first (map (fn [f] (f v)) (list kg10))))) +(at (select {n: (count v) by: (kmap10 v) from: T10}) 'n) -- [3 3] +(set HL10 (list kg10 kg10)) +(set kmapg10 (fn [v] (last (map (fn [f] (f v)) HL10)))) +(at (select {n: (count v) by: (kmapg10 v) from: T10}) 'n) -- [3 3] +(set hs10 (fn [x] (- x (avg x)))) +(set kfold10 (fn [v] (> (fold (fn [acc f] (+ acc (f v))) 0 (list hs10 hs10)) 0))) +(at (select {n: (count v) by: (kfold10 v) from: T10}) 'n) -- [3 3] +;; ... while an alias, a list or a dict that reaches an effect sends the body +;; row by row; so does a let that may not have run, or one rebinding the name +(set CNT11 0) +(set eff11 (fn [x] (set CNT11 (+ CNT11 1)) x)) +(set kale11 (fn [v] (let g eff11) (g v) (if (< v 4) 0 1))) +(at (select {n: (count v) by: (kale11 v) from: T10}) 'n) -- [3 3] +CNT11 -- 6 +(set CNT11 0) +(set gx11 eff11) +(set kcl11 (fn [v] (if (> 0 1) (let gx11 kg10) 0) (gx11 v) (if (< v 4) 0 1))) +(at (select {n: (count v) by: (kcl11 v) from: T10}) 'n) -- [3 3] +CNT11 -- 6 +(set CNT11 0) +(set kme11 (fn [v] (first (map (fn [f] (f v)) (list eff11))) (if (< v 4) 0 1))) +(at (select {n: (count v) by: (kme11 v) from: T10}) 'n) -- [3 3] +CNT11 -- 6 +(set CNT11 0) +(set HD11 (dict ['a] (list eff11))) +(set kmd11 (fn [v] (first (map (fn [f] (f v)) (value HD11))) (if (< v 4) 0 1))) +(at (select {n: (count v) by: (kmd11 v) from: T10}) 'n) -- [3 3] +CNT11 -- 6 +(set CNT11 0) +(set kfa11 (fn [v] (fold (fn [acc f] (acc v)) eff11 (list kg10)) (if (< v 4) 0 1))) +(at (select {n: (count v) by: (kfa11 v) from: T10}) 'n) -- [3 3] +CNT11 -- 6 +(set CNT11 0) +(set kpa11 (fn [g v] (let g eff11) (g v) (if (< v 4) 0 1))) +(at (select {n: (count v) by: (kpa11 kg10 v) from: T10}) 'n) -- [3 3] +CNT11 -- 6 +(set CNT11 0) +(set krl11 (fn [v] (let g kg10) (let g eff11) (g v) (if (< v 4) 0 1))) +(at (select {n: (count v) by: (krl11 v) from: T10}) 'n) -- [3 3] +CNT11 -- 6 +;; a let in a loop reaches the next iteration's calls, whatever the name held +;; before; a let in a try body may be skipped by a raise +(set pid11 (fn [x] x)) +(set CNT11 0) +(set klp11 (fn [v] (let g pid11) (times 2 (do (let t (g v)) (let g (fn [x] (set CNT11 (+ CNT11 1)) x)))) (kg10 v))) +(at (select {n: (count v) by: (klp11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set CNT11 0) +(set kwh11 (fn [v] (let g pid11) (let i 0) (while (< i 2) (do (let t (g v)) (let g (fn [x] (eff11 x))) (let i (+ i 1)))) (kg10 v))) +(at (select {n: (count v) by: (kwh11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set CNT11 0) +(set klt11 (fn [v] (let g (fn [x] x)) (times 2 (do (let t (g v)) (let g (fn [x] (eff11 x))))) (kg10 v))) +(at (select {n: (count v) by: (klt11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set CNT11 0) +(set ktr11 (fn [v] (let g (fn [x] (eff11 x))) (try (do (raise "x") (let g pid11)) (fn [e] 0)) (let t (g v)) (kg10 v))) +(at (select {n: (count v) by: (ktr11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +;; a local, parameter or capture named map is what is called, not the builtin +(set CNT11 0) +(set kmm11 (fn [v] (let map (fn [f xs] (set CNT11 (+ CNT11 1)) xs)) (let t (map (fn [y] y) [1 2])) (kg10 v))) +(at (select {n: (count v) by: (kmm11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set CNT11 0) +(set mm11 (fn [f xs] (set CNT11 (+ CNT11 1)) xs)) +(set mkmm11 (fn [map] (fn [v] (let t (map (fn [y] y) [1 2])) (kg10 v)))) +(set kmc11 (mkmm11 mm11)) +(at (select {n: (count v) by: (kmc11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +;; a function a builtin calls, reached through a dict, a list or a computed +;; value, counts as called +(set CNT11 0) +(set D11 (dict ['a] (list eff11))) +(set L11 (list eff11)) +(set kda11 (fn [v] (let t (map D11.a (enlist v))) (kg10 v))) +(at (select {n: (count v) by: (kda11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set CNT11 0) +(set kdb11 (fn [v] (let t (map (at D11 'a) (enlist v))) (kg10 v))) +(at (select {n: (count v) by: (kdb11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set CNT11 0) +(set kgl11 (fn [v] (let t (map (fn [f] (f v)) L11)) (kg10 v))) +(at (select {n: (count v) by: (kgl11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +;; data a key only reads is pure whatever it holds, however large: a list of +;; strings, a dict of symbols, a symbol vector naming an effectful global +(set LS11 (map (fn [i] (format "x%" i)) (til 5000))) +(set DB11 (dict (as 'SYMBOL (map (fn [i] (format "s%" i)) (til 5000))) (as 'SYMBOL (map (fn [i] (format "t%" i)) (til 5000))))) +(set SB11 ['eff11 'a 'b]) +(set krd11 (fn [v] 1 (> (- v (avg v)) (+ (- (count LS11) 5000) (+ (- (count DB11) 5000) (- (count SB11) 3)))))) +(set CNT11 0) +(at (select {n: (count v) by: (krd11 v) from: T10}) 'n) -- [3 3] +CNT11 -- 0 +;; ... while a function a builtin calls, taken out of a table cell, a list +;; cell or a dict cell, is a callee the walk cannot see: an effect +(set TF11 (update {f: (list eff11 eff11) from: (table [a] (list [1 2]))})) +(set ktf11 (fn [v] (let t (map (first (at TF11 'f)) (enlist v))) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (ktf11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set TD11 (table [f] (list (list (dict ['a] (list eff11)) (dict ['a] (list eff11)))))) +(set ktd11 (fn [v] (let t (map (at (first (at TD11 'f)) 'a) (enlist v))) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (ktd11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +;; every builtin that calls an argument, at every position it calls, under +;; any name bound to it: fold-left, scan-left, fold-while's step, try's handler +(set eff211 (fn [a x] (set CNT11 (+ CNT11 1)) x)) +(set D211 (dict ['b] (list eff211))) +(set khf11 (fn [v] (let t (fold-left (at D211 'b) 0 (enlist v))) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (khf11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set khs11 (fn [v] (let t (scan-left (at D211 'b) (list v v))) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (khs11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set khw11 (fn [v] (let t (fold-while (fn [a] true) (at D211 'b) 0 (enlist v))) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (khw11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set kha11 (fn [v] (let m map) (let t (m (at D11 'a) (enlist v))) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kha11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set kht11 (fn [v] (let t (try (raise "x") (at D11 'a))) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kht11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +;; a builtin that calls its arguments is not a known-pure value: map handed +;; to map, or as fold's element, then called with a computed function +(set kmm211 (fn [v] (let t (map (fn [f] (f (at D11 'a) (enlist v))) (list map))) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kmm211 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set kfm211 (fn [v] (let t (fold (fn [acc f] (f (at D11 'a) (enlist v))) 0 (list map))) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kfm211 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +;; a lambda object spliced in as try's handler is called as it is +(set trl11 (concat (parse "(try (raise 'x))") (enlist eff11))) +(set ktl11 (eval (concat (take (parse "(fn [v] 0)") 2) (list (concat (parse "(let t)") (enlist trl11)) (parse "(kg10 v)"))))) +(set CNT11 0) +(at (select {n: (count v) by: (ktl11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +;; a name means its binding, not its spelling: a local list or enlist is a +;; call through it, and a `let` in a branch keeps what the name meant before +(set kls11 (fn [v] (let list (fn [x] (set CNT11 (+ CNT11 1)) (enlist x))) (map (fn [x] x) (list 1)) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kls11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set kle11 (fn [v] (let enlist (fn [x] (set CNT11 (+ CNT11 1)) (list x x))) (map (fn [x] x) (enlist 1)) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kle11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set kcb11 (fn [v] (let f (fn [x] (set CNT11 (+ CNT11 1)) x)) (if false (let f (fn [x] x))) (map (fn [g] (g 1)) (list f)) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kcb11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set kcc11 (fn [v] (let f (at D11 'a)) (if false (let f (fn [x] x))) (map (fn [g] (g 1)) (list f)) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kcc11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +;; a local list that is pure itself but hands back an effectful function +(set klp11 (fn [v] (let list (fn [x] (enlist (at D11 'a)))) (map (fn [g] (g 1)) (list 1)) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (klp11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +;; ... so is a parameter spelled like a special form, and an `fn` that is a +;; parameter does not make a lambda literal +(set kif11 (fn [v if] (if v) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kif11 v (at D11 'a)) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set kfn11 (fn [v fn] (let g (fn 1 v)) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kfn11 v (at D211 'b)) from: T10}) 'n) -- [6] +CNT11 -- 6 +;; ... and an effectful builtin bound to another name is still effectful +(set myshow11 show) +(set kms11 (fn [v] (myshow11 'once) (> (- v (avg v)) 0))) +(at (select {n: (count v) by: (kms11 v) from: T10}) 'n) -- [6] +;; quote set globally to a function makes (quote v) a call through it, while +;; do, if, let and the other forms the compiler wires in stay the forms +(set qsave quote) +(set quote (at D11 'a)) +(set kqg11 (fn [v] (quote v) (kg10 v))) +(set CNT11 0) +(at (select {n: (count v) by: (kqg11 v) from: T10}) 'n) -- [6] +CNT11 -- 6 +(set quote qsave) +;; ... while a literal fallback value of try keeps the whole column +(set khv11 (fn [v] (let t (try (raise "x") 'none)) (kg10 v))) +(at (select {n: (count v) by: (khv11 v) from: T10}) 'n) -- [3 3] +;; ... while a pure function value keeps the whole column, a dict's included +(set kpm11 (fn [v] (> (first (map kg10 (enlist v))) 0))) +(at (select {n: (count v) by: (kpm11 v) from: T10}) 'n) -- [3 3] +(set DP11 (dict ['f] (list kg10))) +(set kdp11 (fn [v] (DP11.f v))) +(at (select {n: (count v) by: (kdp11 v) from: T10}) 'n) -- [3 3] +(set kdq11 (fn [v] (first (map (fn [g] (g v)) (list DP11.f))))) +(at (select {n: (count v) by: (kdq11 v) from: T10}) 'n) -- [3 3] +;; a pure body keeps the whole column: the min is the column's minimum +(set kw10 (fn [v] 1 (- v (min v)))) +(at (select {n: (count v) by: (kw10 v) from: T10}) 'v) -- [0 1 2 3 4 5] +;; a computed callee is an effect: the body runs once per row +(set CNT10 0) +(set eff10 (fn [x] (set CNT10 (+ CNT10 1)) x)) +(set H10 (dict ['a] (list eff10))) +(set kdisp10 (fn [v] ((at H10 'a) v) (if (< v 4) 0 1))) +(at (select {n: (count v) by: (kdisp10 v) from: T10}) 'n) -- [3 3] +CNT10 -- 6 +;; a swallowed whole-column failure leaves no trace or message behind: a +;; later uncaught error in a fresh interpreter is reported at its own place +(write "/tmp/rfl_trace_clear.rfl" "(set TB (table [v] (list [1 2 3 10 20 30]))) (set kneg (fn [v] 1 (if (< v 0) (raise 'negative) (% v 7)))) (select {n: (count v) by: (kneg v) from: TB}) (+ 1 'a)") +(.sys.exec "./rayforce /tmp/rfl_trace_clear.rfl 2>&1 | grep -c negative | grep -qx 0") -- 0 +;; an effect reached through a parameter counts: the parameter means the +;; argument it is bound to, not a global or let of the same name +(set CNT12 0) +(set eff12 (fn [x] (set CNT12 (+ CNT12 1)) x)) +(set H12 (dict ['a] (list eff12))) +(set h12 (fn [x] x)) +(set ky12 (fn [v] 1 (let g (fn [h12] (h12 v))) (g (at H12 'a)) (if (< v 4) 0 1))) +(at (select {n: (count v) by: (ky12 v) from: T10}) 'n) -- [3 3] +CNT12 -- 6 +;; and a pure helper passed through a parameter keeps the whole column +(set kp12 (fn [v] 1 (let g (fn [f] (f v))) (> (g kg10) 0))) +(at (select {n: (count v) by: (kp12 v) from: T10}) 'n) -- [3 3] +;; a lambda passed as a value keeps its parameters unknown: a call through +;; one is an effect whatever a global of that name holds +(set ap13 (fn [z g13] (g13 z))) +(set CNT13 0) +(set eff13 (fn [x] (set CNT13 (+ CNT13 1)) x)) +(set H13 (dict ['a] (list eff13))) +(set kf13 (fn [v] (fold ap13 (> v 3) (list (at H13 'a))))) +(select {n: (count v) by: (kf13 v) from: T10}) +CNT13 -- 6 +(set g13 (fn [x] x)) +(set CNT13 0) +(select {n: (count v) by: (kf13 v) from: T10}) +CNT13 -- 6 +;; a literal nested in a body keeps the enclosing body's parameters +(set ap213 (fn [g13 z] ((fn [w] (g13 w)) z))) +(set CNT13 0) +(select {n: (count v) by: (ap213 (at H13 'a) (> v 3)) from: T10}) +CNT13 -- 6 +;; an argument's name means what it meant where the call was written +(set hh13 (fn [x] (> (- x (avg x)) 0))) +(set ap313 (fn [f z] (let hh13 (fn [q] (println "never") q)) (f z))) +(at (select {n: (count v) by: (ap313 hh13 v) from: T10}) 'n) -- [3 3] diff --git a/test/rfl/query/insert_inplace.rfl b/test/rfl/query/insert_inplace.rfl index ecd8cb187..bd698667a 100644 --- a/test/rfl/query/insert_inplace.rfl +++ b/test/rfl/query/insert_inplace.rfl @@ -97,3 +97,22 @@ (map (fn [i] (insert 'big (table [a b] (list (til 100) (as 'F64 (til 100)))))) (til 50)) (count big) -- 5000 (sum (get big 'a)) -- 247500 + +;; ── an empty string is a string column's null: one appended cell ──────── +;; A null atom was appended as a fixed-width zero cell, which a string +;; column (pool payloads) refused: `vec_append: str vectors use +;; ray_str_vec_append`. In place, rebuilt, functional, and a dict row that +;; leaves the string column out all append the empty string. +(set ts (table [s n] (list ["p" "qq"] [1 2]))) +(insert 'ts (list "" 3)) -- 'ts +(get ts 's) -- ["p" "qq" ""] +(get ts 'n) -- [1 2 3] +(insert 'ts (list "x" 4)) -- 'ts +(get ts 's) -- ["p" "qq" "" "x"] +(get (insert ts (list "" 5)) 's) -- ["p" "qq" "" "x" ""] +(set tsr ts) +(insert 'ts (list "" 6)) -- 'ts +(count ts) -- 5 +(count tsr) -- 4 +(get (insert ts (dict [n] (list 7))) 's) -- ["p" "qq" "" "x" "" ""] +(count (select {from: ts where: (in s ["" "x"])})) -- 1 diff --git a/test/rfl/query/literal_col_ref.rfl b/test/rfl/query/literal_col_ref.rfl index 6b9f5c810..f80c95495 100644 --- a/test/rfl/query/literal_col_ref.rfl +++ b/test/rfl/query/literal_col_ref.rfl @@ -83,3 +83,31 @@ (count (select {from: T2 where: (== s 'a)})) -- 2 ;; and-chained predicate operand also folds (no longer "not supported") (count (select {from: T2 where: (and (== s (quote a)) (== s 'a))})) -- 2 + +;; ── where: is alias-blind to a by-dict's keys ─────────────────────────── +;; The eager by-dict path adds each alias as a column of the table the rest +;; of the select is compiled over, so a literal in where: naming an alias +;; resolved to that new column: `{a: k1} where: (!= k1 'a)` compared k1 with +;; itself and kept no rows, while the same select with a distinct count (the +;; two-pass rewrite adds no column) kept the symbol. where: names source +;; columns only; a literal naming an alias stays the symbol on every route. +(set Tal (table [k1 k2 v] (list (take ['a 'b 'c 'd 'e] 100) (take ['p 'q 'r] 100) (til 100)))) +(count (select {from: Tal by: {a: k1} where: (!= k1 'a) n: (count v)})) -- 4 +(count (select {from: Tal by: {a: k1} where: (== k1 'a) n: (count v)})) -- 1 +(at (select {from: Tal by: {a: k1} where: (== k1 'a) n: (count v)}) 'n) -- [20] +(count (select {from: Tal by: {a: k1} where: (!= k1 'a) n: (sum v) asc: a})) -- 4 +(count (select {from: Tal by: {a: k1} where: (!= k1 'a) n: (count v) desc: n take: 2})) -- 2 +(count (select {from: Tal by: {p: k2} where: (!= k2 'p) n: (count v)})) -- 2 +(count (select {from: Tal by: {a: k1 b: k2} where: (and (!= k1 'a) (!= k2 'b)) n: (sum v)})) -- 12 +;; the same select with a distinct count agrees (the rewrite route) +(at (select {from: Tal by: {a: k1} where: (!= k1 'a) n: (count (distinct v)) asc: a}) 'a) -- ['b 'c 'd 'e] +;; a vector literal was never captured; a literal naming a source column still is +(count (select {from: Tal by: {a: k1} where: (in k1 ['a 'b]) n: (count v)})) -- 2 +(count (select {from: Tal by: {a: k1} where: (> 'v 49) n: (count v)})) -- 5 +;; a trivial self-alias keeps the column rule: {k1: k1} adds nothing +(count (select {from: Tal by: {k1: k1} where: (!= k1 'a) n: (count v)})) -- 4 +;; the re-run takes the table from: evaluated to, not the from: expression: +;; its side effects run once +(set Cfrom 0) +(count (select {from: (do (set Cfrom (+ Cfrom 1)) Tal) by: {a: k1} where: (!= k1 'a) n: (count v)})) -- 4 +Cfrom -- 1 diff --git a/test/rfl/query/membership_fallback.rfl b/test/rfl/query/membership_fallback.rfl new file mode 100644 index 000000000..923bdfadb --- /dev/null +++ b/test/rfl/query/membership_fallback.rfl @@ -0,0 +1,39 @@ +;; Membership must give the same query result for a bound probe (DAG) and +;; an inline constructor (interpreter), including nulls on either side. +(set T (table [s x k] (list (as 'SYM (list "a" "" "b" "a" "" "c")) [1 0Nl 2 1 0Nl 3] [0 0 0 1 1 1]))) +(set NA (as 'SYM (list "" "a"))) +(at (select {from: T where: (in s NA)}) 'x) -- [1 1] +(at (select {from: T where: (in s (as 'SYM (list "" "a")))}) 'x) -- [1 1] +(at (select {from: T where: (not-in s NA)}) 'x) -- [2 3] +(at (select {from: T where: (not-in s (as 'SYM (list "" "a")))}) 'x) -- [2 3] +(at (select {from: T where: (not-in s (as 'SYM (list "")))}) 'x) -- [1 2 1 3] +(at (select {from: T where: (not-in s (as 'SYM (list)))}) 'x) -- [1 2 1 3] +(at (select {from: T where: (not-in s (as 'SYM (list "zz")))}) 'x) -- [1 2 1 3] +(count (select {from: T where: (in s (as 'SYM (list "")))})) -- 0 +(count (select {from: T where: (in s (as 'SYM (list "" "a")))})) -- 2 +(count (select {from: T where: (not-in s (as 'SYM (list "" "a")))})) -- 2 + +;; Per-row projection, grouped filtering, and update filtering use the same rule. +(at (select {v: (in s (as 'SYM (list "" "a"))) from: T}) 'v) -- [true false false true false false] +(at (select {v: (not-in s (as 'SYM (list "" "a"))) from: T}) 'v) -- [false false true false false true] +(sum (at (select {n: (count x) by: k from: T where: (in s (as 'SYM (list "" "a")))}) 'n)) -- 2 +(sum (at (select {n: (count x) by: k from: T where: (not-in s (as 'SYM (list "" "a")))}) 'n)) -- 2 +(at (update {x: 9 from: T where: (not-in s (as 'SYM (list "" "a")))}) 'x) -- [1 0Nl 9 1 0Nl 9] +(at (update {x: 9 from: T where: (in s (as 'SYM (list "" "a")))}) 'x) -- [9 0Nl 2 9 0Nl 3] + +;; Numeric nulls and a boxed probe use the same query contract. +(at (select {from: T where: (in x (list 0Nl 1))}) 'x) -- [1 1] +(at (select {from: T where: (not-in x (list 0Nl 1))}) 'x) -- [2 3] +(at (select {v: (not-in x (list 0Nl 1)) from: T}) 'v) -- [false false true false false true] +(set Empty (table [s] (list (as 'SYM (list))))) +(count (select {from: Empty where: (not-in s (as 'SYM (list "a")))})) -- 0 + +;; Outside queries, collection membership retains null-equals-null semantics; +;; not-in is its complement, and query state does not escape after evaluation. +(in (at T 's) NA) -- [true true false true true false] +(not-in (at T 's) NA) -- [false false true false false true] +(not-in 2 [1 3]) -- true +(not-in 0Nl [1]) -- true +(not-in 0Nl [0Nl]) -- false +((fn [v] (not-in v [1 3])) [1 2 3]) -- [false true false] +(not-in [1]) !- arity diff --git a/test/rfl/query/membership_fallback_storage.rfl b/test/rfl/query/membership_fallback_storage.rfl new file mode 100644 index 000000000..4001c07be --- /dev/null +++ b/test/rfl/query/membership_fallback_storage.rfl @@ -0,0 +1,19 @@ +;; @requires: posix (fixture cleanup via .sys.exec) +;; Query fallback must preserve membership semantics across symbol domains. +(.sys.exec "rm -rf /tmp/rfl_membership_fallback") -- 0 +(set T (table [s x] (list (as 'SYM (list "a" "" "b")) [1 0Nl 2]))) +(.db.splayed.set "/tmp/rfl_membership_fallback/1/t/" T) +(.db.splayed.set "/tmp/rfl_membership_fallback/2/t/" (table [s x] (list (at T 's) [11 0Nl 12]))) +(set U (.db.splayed.get "/tmp/rfl_membership_fallback/1/t/")) +(set P (.db.parted.get "/tmp/rfl_membership_fallback/" 't)) +(at (select {from: U where: (in s (as 'SYM (list "a" "")))}) 'x) -- [1] +(at (select {from: U where: (not-in s (as 'SYM (list "a" "")))}) 'x) -- [2] +(at (select {from: U where: (not-in s (as 'SYM (list "zz")))}) 'x) -- [1 2] +(at (select {v: (not-in s (as 'SYM (list "a" ""))) from: U}) 'v) -- [false false true] +(at (select {from: P where: (in s (as 'SYM (list "a" "")))}) 'x) -- [1 11] +(at (select {from: P where: (not-in s (as 'SYM (list "a" "")))}) 'x) -- [2 12] +(at (select {v: (not-in s (as 'SYM (list "a" ""))) from: P}) 'v) -- [false false true false false true] +;; MAPCOMMON partition keys need materialization on the evaluator path too. +(at (select {from: P where: (in part (distinct [1]))}) 'x) -- [1 0Nl 2] +(at (select {from: P where: (not-in part (distinct [1]))}) 'x) -- [11 0Nl 12] +(.sys.exec "rm -rf /tmp/rfl_membership_fallback") -- 0 diff --git a/test/rfl/query/membership_review.rfl b/test/rfl/query/membership_review.rfl new file mode 100644 index 000000000..9790b924b --- /dev/null +++ b/test/rfl/query/membership_review.rfl @@ -0,0 +1,30 @@ +;; Mixed concat results stay on general membership, never a typed LIST probe. +(set T (table [s x] (list ['a 'b 'a] [1 2 3]))) +(at (select {from: T where: (in s (concat ['a] [1]))}) 'x) -- [1 3] +(at (select {from: T where: (not-in s (concat ['a] [1]))}) 'x) -- [2] +(at (select {v: (in s (concat 'a 1)) from: T}) 'v) -- [true false true] +(at (select {v: (not-in s (concat 'a 1)) from: T}) 'v) -- [false true false] + +;; Nested results retain their shape under negation. +(not-in (list (list 1 2) (list 3)) [1]) -- (list [false true] [true]) +(in (list (list 1 2) (list 3)) [1]) -- (list [true false] [false]) + +;; A string element of a collection is one whole value, so a string column +;; answers one verdict per row and filters like any other column. +(not-in ["ab" "c"] "a") -- [true true] +(in ["ab" "c" "a"] "a") -- [false false true] +(set S (table [ss] (list ["ab" "c" "a"]))) +(at (select {from: S where: (in ss (list "" "a"))}) 'ss) -- ["a"] +(at (select {from: S where: (not-in ss (list "" "a"))}) 'ss) -- ["ab" "c"] + +;; Empty evaluator membership must produce an empty BOOL predicate. +(set E (table [s x] (list (as 'SYM (list)) (til 0)))) +(count (select {from: E where: (in s (as 'SYM (list "a")))})) -- 0 +(count (select {from: E where: (not-in s (as 'SYM (list "a")))})) -- 0 + +;; F64 and temporal inline probes use the same null-aware typed kernel. +(set F (table [f d] (list [1.0 0Nf 2.0] [2024.01.01 0Nd 2024.01.02]))) +(at (select {from: F where: (in f (distinct [0Nf 1.0]))}) 'f) -- [1.0] +(at (select {from: F where: (not-in f (distinct [0Nf 1.0]))}) 'f) -- [2.0] +(at (select {from: F where: (in d (distinct [0Nd 2024.01.01]))}) 'f) -- [1.0] +(at (select {from: F where: (not-in d (distinct [0Nd 2024.01.01]))}) 'f) -- [2.0] diff --git a/test/rfl/query/nested_select_merge.rfl b/test/rfl/query/nested_select_merge.rfl new file mode 100644 index 000000000..62481c029 --- /dev/null +++ b/test/rfl/query/nested_select_merge.rfl @@ -0,0 +1,47 @@ +;; #752: nesting must preserve aggregate scope, empty-source behavior and schema. +(set T752 (table [x] (list [1.0 2.0 3.0]))) +(at (select {from:(select {from:T752 x:x q:(- x (avg x))}) where:(> x 1) q:q}) 'q) -- [0.0 1.0] +(at (select {from:T752 where:(> x 1) q:(- x (avg x))}) 'q) -- [-0.5 0.5] + +;; Empty inner source vs nonempty source filtered to zero have distinct behavior. +(count (select {from:(select {from:T752 where:(> x 9) x:x}) where:(> x 1) s:(sum x)})) -- 0 +(count (select {from:(select {from:T752 where:(> x 1) x:x}) where:(> x 9) s:(sum x)})) -- 1 + +;; Alias substitution, including earlier inner aliases, preserves values. +(at (select {from:(select {from:T752 q:(* x 2) r:(+ q 1)}) s:(sum r)}) 's) -- [15.0] +(at (select {from:(select {from:T752 q:(* x 2)}) where:(> q 3)}) 'q) -- [4.0 6.0] +(set N752 (table [x] (list [0Nf 1.0 2.0]))) +(at (select {from:(select {from:N752 x:x q:(- x 0.7)}) where:(== x 0Nf) s:(sum q)}) 's) -- [0.0] + +;; Overflow creates nulls even though the source has no HAS_NULLS flag. +(set D754 (table [f] (list [1.7976931348623157e308 -1.7976931348623157e308 1.0]))) +(at (select {from:(select {from:D754 c:(+ f 1e300)}) total:(sum c)}) 'total) -- (at (select {from:(do (select {from:D754 c:(+ f 1e300)})) total:(sum c)}) 'total) +(at (select {from:(select {from:D754 c:(+ f 1e300)}) total:(avg c)}) 'total) -- (at (select {from:(do (select {from:D754 c:(+ f 1e300)})) total:(avg c)}) 'total) + +;; Numeric width and dropped-column errors must survive. +(set W752 (table [x y] (list (as 'I32 [1 2 3]) [4 5 6]))) +(at (select {from:(select {from:W752 x:x}) take:2}) 'x) -- [1i 2i] +(select {from:(select {from:W752 x:x}) y:y}) !- schema + +;; AND + take over more than one morsel stays on the established path. +(set I752 (til 20000)) +(set L752 (table [x y] (list I752 (% I752 3)))) +(at (select {from:(select {from:L752 where:(> x 8192)}) where:(== y 1) take:3}) 'x) -- [8194 8197 8200] + +;; Admitted rewrites on a table above the size cutoff: combine filters and +;; preserve empty grouped column output, including its serialized schema. +(at (select {from:(select {from:L752 where:(< x 100)}) where:(== y 1) by:y total:(sum x)}) 'total) -- [1617] +(ser (select {from:(select {from:L752 where:(> x 20000)}) by:y x:x})) -- (ser (select {from:(do (select {from:L752 where:(> x 20000)})) by:y x:x})) + +;; A lambda source shadows the global table: its rows and types govern planning. +((fn [L752] (count (select {from:(select {from:L752 where:(> x 5)}) where:(> x 0) s:(sum x)}))) (table [x] (list [1 2 3]))) -- 0 +((fn [L752] (count (select {from:(do (select {from:L752 where:(> x 5)})) where:(> x 0) s:(sum x)}))) (table [x] (list [1 2 3]))) -- 0 +(set F752 (take (table [x] (list [1.0 2.0 3.0])) 10000)) +(set Int752 (take (table [x] (list [9223372036854775807 1 2])) 10000)) +((fn [F752] (ser (select {from:(select {from:F752 q:(* x 2)}) total:(sum q)}))) Int752) -- ((fn [F752] (ser (select {from:(do (select {from:F752 q:(* x 2)})) total:(sum q)}))) Int752) + +;; Column products overflow into null lanes before a materialized reduction. +(set E754 (take (table [f g] (list [1e300 1e10 -1e300 3.0] [1e300 2.0 1e300 4.0])) 10000)) +(at (select {from:(select {from:E754 c:(* f g)}) total:(sum c)}) 'total) -- [50000000030000.0] +(at (select {from:(select {from:E754 c:(* f g)}) total:(avg c)}) 'total) -- [10000000006.0] +(ser (select {from:(select {from:E754 c:(* f f)}) total:(sum c)})) -- (ser (select {from:(do (select {from:E754 c:(* f f)})) total:(sum c)})) diff --git a/test/rfl/query/nested_sort_computed.rfl b/test/rfl/query/nested_sort_computed.rfl new file mode 100644 index 000000000..3ecdcc7f0 --- /dev/null +++ b/test/rfl/query/nested_sort_computed.rfl @@ -0,0 +1,8 @@ +(set NS744 (table [x] (list (til 8192)))) +(at (select {from:(select {from:NS744 q:(* x 2)}) desc:q take:3}) 'q) -- [16382 16380 16378] +(at (select {from:(select {from:NS744 q:(* x 2)}) asc:q take:3}) 'q) -- [0 2 4] +(count (select {from:(select {from:NS744 q:(* x 2)}) desc:q})) -- 8192 +(at (select {from:(select {from:NS744 q:(* x 2) where:(> x 2)}) asc:q take:3}) 'q) -- [6 8 10] +(at (select {from:(select {from:NS744 q:(* x 2.0)}) desc:q take:3}) 'q) -- [16382.0 16380.0 16378.0] +(at (select {from:(select {from:NS744 q:x}) desc:q take:3}) 'q) -- [8191 8190 8189] +(at (select {from:(select {from:NS744 x:x}) desc:x take:3}) 'x) -- [8191 8190 8189] diff --git a/test/rfl/query/query_sort_take_coverage.rfl b/test/rfl/query/query_sort_take_coverage.rfl index 638c9a5f8..68dd9fcd8 100644 --- a/test/rfl/query/query_sort_take_coverage.rfl +++ b/test/rfl/query/query_sort_take_coverage.rfl @@ -187,12 +187,13 @@ ;; `(first (asc col_expr))` where col_expr = (+ v 1) (not a name ref) ;; → col_expr->type == RAY_LIST, not -RAY_SYM → return false at 1858. ;; dep_candidate optimization not applied → falls back to per-group eval. -;; (+ v 1) is not compilable as an agg DAG node → domain error. +;; (+ v 1) is not compilable as an agg DAG node → evaluated per group +;; (it raised "failed to compile aggregation argument"). ;; ──────────────────────────────────────────────────────────────────── (set T1858 (table [k v] (list ['a 'a 'b 'b] [1 2 3 4]))) ;; (first (asc (+ v 1))): inner col_expr = (+ v 1) is LIST → line 1858 -;; simplify_agg_idiom returns false → compilation fails → domain error -(select {m: (first (asc (+ v 1))) by: k from: T1858}) !- domain +;; simplify_agg_idiom returns false → the aggregate runs per group +(select {m: (first (asc (+ v 1))) by: k from: T1858}) -- (table [k m] (list [a b] [2 4])) (set TLimLazy (table [s v] (list (take ['a 'b 'c] 120) (til 120)))) (count (select {s: s from: TLimLazy where: (!= s 'c) take: 20})) -- 20 @@ -219,3 +220,418 @@ (set RHolF2 (select {m: (min s) c: (count s) from: THol where: (>= v 100000) by: k})) (sum (at RHolF2 'c)) -- 100000 (at (at (select {m: m from: RHolF2 where: (== k "0")}) 'm) 0) -- "100000" + +;; ──────────────────────────────────────────────────────────────────── +;; Computed by: key with no outputs. The DAG no-agg branch regroups a +;; computed key (key_sym < 0) at eval level and returned that result +;; without apply_sort_take, so asc:/desc:/take: were dropped and every +;; group came back in first-seen order. Oracles: the same key +;; materialized as a column (a plain key), and the computed key beside an +;; output. The key column keeps its derived name, `x`. +;; ──────────────────────────────────────────────────────────────────── +(set Tck (table [x y] (list [3 1 4 2 3 1] [30 10 40 20 31 11]))) +(set Tckp (update {k: (* x 2) from: Tck})) +(select {by: (* x 2) from: Tck desc: x take: 2}) -- (table [x y] (list [8 6] [40 30])) +(at (select {by: (* x 2) from: Tck desc: x take: 2}) 'x) -- (at (select {c: (count y) by: (* x 2) from: Tck desc: x take: 2}) 'x) +(at (select {by: (* x 2) from: Tck desc: x take: 2}) 'y) -- (at (select {by: k from: Tckp desc: k take: 2}) 'y) +;; asc: and desc: alone, on the key and on a source column +(select {by: (* x 2) from: Tck asc: x}) -- (table [x y] (list [2 4 6 8] [10 20 30 40])) +(at (select {by: (* x 2) from: Tck desc: y}) 'x) -- [8 6 4 2] +(at (select {by: (* x 2) from: Tck desc: y}) 'y) -- (at (select {by: k from: Tckp desc: y}) 'y) +;; take: alone keeps first-seen group order: head, tail, range, more than the groups +(select {by: (* x 2) from: Tck take: 2}) -- (table [x y] (list [6 2] [30 10])) +(at (select {by: (* x 2) from: Tck take: -1}) 'y) -- (at (select {by: k from: Tckp take: -1}) 'y) +(at (select {by: (* x 2) from: Tck take: [1 2]}) 'y) -- (at (select {by: k from: Tckp take: [1 2]}) 'y) +(at (select {by: (* x 2) from: Tck desc: x take: 10}) 'x) -- [8 6 4 2] +;; where: filters the rows before the grouping +(select {by: (* x 2) from: Tck where: (> y 15) asc: x take: 2}) -- (table [x y] (list [4 6] [20 30])) +;; several rows per group: the first row of each, as for a plain key +(select {by: (% x 2) from: Tck asc: x}) -- (table [x y] (list [0 1] [40 30])) +(at (select {by: (% x 2) from: Tck desc: y take: 1}) 'y) -- [40] +;; a null key sorts as the plain key's null does +(set Tckn (table [x y] (list [1 0N 3 0N 5] [10 20 30 40 50]))) +(set Tcknp (update {k: (* x 2) from: Tckn})) +(at (select {by: (* x 2) from: Tckn desc: x}) 'y) -- (at (select {by: k from: Tcknp desc: k}) 'y) +(at (select {by: (* x 2) from: Tckn asc: x take: 2}) 'y) -- (at (select {by: k from: Tcknp asc: k take: 2}) 'y) +(at (select {by: (* x 2) from: Tckn asc: x take: 2}) 'y) -- [20 10] +;; STR and LIST columns are gathered whole. The branch built every column +;; with store_typed_elem, which has no STR case: the cells came back empty +;; or stale, and a sort on them read an unset string pool. +(set Tcks (table [x r] (list [3 1 4 2 3 1] (list "c-long-string-over-12" "a-long-string-over-12" "d-long-string-over-12" "b-long-string-over-12" "c2" "a2")))) +(set Tcksp (update {k: (* x 2) from: Tcks})) +(at (select {by: (* x 2) from: Tcks}) 'r) -- ["c-long-string-over-12" "a-long-string-over-12" "d-long-string-over-12" "b-long-string-over-12"] +(at (select {by: (* x 2) from: Tcks}) 'r) -- (at (select {by: k from: Tcksp}) 'r) +(at (select {by: (* x 2) from: Tcks desc: r}) 'r) -- (at (select {by: k from: Tcksp desc: r}) 'r) +(at (select {by: (* x 2) from: Tcks desc: r}) 'x) -- [8 6 4 2] +(at (select {by: (* x 2) from: Tcks desc: r take: 2}) 'r) -- (at (select {by: k from: Tcksp desc: r take: 2}) 'r) +(at (select {by: (* x 2) from: Tcks desc: r take: 2}) 'r) -- ["d-long-string-over-12" "c-long-string-over-12"] +(set Tckl (table [x l] (list [3 1 4 2] (list [1 2] [3] [4 5 6] [7])))) +(set Tcklp (update {k: (* x 2) from: Tckl})) +(at (select {by: (* x 2) from: Tckl}) 'l) -- (at (select {by: k from: Tcklp}) 'l) +(at (select {by: (* x 2) from: Tckl desc: x take: 2}) 'l) -- (at (select {by: k from: Tcklp desc: k take: 2}) 'l) +(at (select {by: (* x 2) from: Tckl desc: x take: 2}) 'l) -- (list [4 5 6] [1 2]) +;; a STR computed key, over more rows than one gather chunk +(set Tckb (table [x r] (list (til 8192) (concat "row-string-over-twelve-" (as 'STR (% (til 8192) 700)))))) +(set Tckbp (update {k: (concat r "!") from: Tckb})) +(count (select {by: (concat r "!") from: Tckb})) -- 700 +(at (select {by: (concat r "!") from: Tckb desc: r take: 3}) 'r) -- (at (select {by: k from: Tckbp desc: k take: 3}) 'k) +(at (select {by: (concat r "!") from: Tckb desc: r take: 3}) 'x) -- [99 98 97] +(at (select {by: (concat r "!") from: Tckb asc: x take: -2}) 'r) -- (at (select {by: k from: Tckbp asc: x take: -2}) 'k) +;; a dotted key takes the same branch; the by-dict form is the oracle +(set Tckt (table [ts v] (list [2024.01.02D10:00:00.000000000 2024.01.01D09:00:00.000000000 2024.01.02D11:00:00.000000000 2024.01.03D08:00:00.000000000 2024.01.01D12:00:00.000000000] [1 2 3 4 5]))) +(select {by: ts.date from: Tckt desc: date take: 2}) -- (select {by: {date: ts.date} from: Tckt desc: date take: 2}) +(select {by: ts.date from: Tckt asc: date}) -- (select {by: {date: ts.date} from: Tckt asc: date}) +(select {by: ts.date from: Tckt where: (> v 1) desc: v take: -2}) -- (select {by: {date: ts.date} from: Tckt where: (> v 1) desc: v take: -2}) +(at (select {by: ts.date from: Tckt desc: date take: 2}) 'v) -- [4 1] +;; a LIST-valued key: ray_is_vec leaves out RAY_LIST, so the key column was +;; never gathered and the source column it replaces was dropped with it. +;; The plain LIST key is the oracle. The identity lambda is a row-aligned +;; LIST key that the planned grouping and this branch evaluate alike. +(set Tckk (table [x l] (list [3 1 4 2] (list [1 2] [3] [4 5 6] [3])))) +(select {by: ((fn [a] a) l) from: Tckk}) -- (select {by: l from: Tckk}) +(at (select {by: ((fn [a] a) l) from: Tckk}) 'l) -- (at (select {c: (count x) by: ((fn [a] a) l) from: Tckk}) 'l) +(select {by: ((fn [a] a) l) from: Tckk desc: x}) -- (select {by: l from: Tckk desc: x}) +(select {by: ((fn [a] a) l) from: Tckk desc: x take: 2}) -- (select {by: l from: Tckk desc: x take: 2}) +(select {by: ((fn [a] a) l) from: Tckk desc: x take: 2}) -- (table [l x] (list (list [4 5 6] [1 2]) [4 3])) +(select {by: ((fn [a] a) l) from: Tckk desc: x take: -2}) -- (select {by: l from: Tckk desc: x take: -2}) +(select {by: ((fn [a] a) l) from: Tckk where: (== x 4)}) -- (select {by: l from: Tckk where: (== x 4)}) +(select {by: ((fn [a] a) l) from: Tckk where: (> x 100)}) -- (select {by: l from: Tckk where: (> x 100)}) +;; a key of another length is no row-aligned key: its group rows would index +;; past the gathered columns. A LIST key gets past the planned grouping's +;; own length check, which looks at vectors only. +(select {by: ((fn [a] (concat a a)) l) from: Tckk desc: x}) !- length +(select {by: (concat l l) from: Tckk desc: x}) !- length +;; (concat x 99), bare or in a lambda, is a collection of 5 values: the +;; whole-column key evaluation refuses it +(select {by: (concat x 99) from: Tckk}) !- length +(select {by: ((fn [a] (concat a 99)) x) from: Tckk}) !- length +;; a concat of collections is no text: the planner leaves it to the whole +;; column, where an aligned one groups as the column it equals +(set Eck (take [1] 0)) +(value (select {c: (count x) by: (concat x Eck) from: Tckk})) -- (value (select {c: (count x) by: x from: Tckk})) +(at (select {by: (concat x Eck) from: Tckk desc: x}) (quote x)) -- (at (select {by: x from: Tckk desc: x}) (quote x)) +;; any key the planner cannot lower is evaluated over the whole column, as +;; its lambda form and its materialised vector are: with and without +;; outputs, sorted and taken, filtered; a misaligned one is refused +(set Trk (table [x s] (list [3 1 4 2 3 1] [a b a c b a]))) +(set Krev (reverse (at Trk 'x))) +(value (select {c: (count x) by: (reverse x) from: Trk})) -- (value (select {c: (count x) by: ((fn [a] (reverse a)) x) from: Trk})) +(at (select {c: (count x) by: (reverse x) from: Trk}) 'c) -- (at (select {c: (count x) by: {k: Krev} from: Trk}) 'c) +(select {by: (reverse x) from: Trk}) -- (select {by: ((fn [a] (reverse a)) x) from: Trk}) +(select {by: (asc x) from: Trk desc: x take: 2}) -- (select {by: ((fn [a] (asc a)) x) from: Trk desc: x take: 2}) +(select {c: (count x) by: (asc x) from: Trk desc: c take: 2}) -- (select {c: (count x) by: ((fn [a] (asc a)) x) from: Trk desc: c take: 2}) +(at (select {by: (til (count x)) from: Trk where: (> x 1)}) (quote key)) -- (at (select {by: ((fn [a] (til (count a))) x) from: Trk where: (> x 1)}) (quote x)) +(at (select {by: (til (count x)) from: Trk where: (> x 1)}) (quote s)) -- (at (select {by: ((fn [a] (til (count a))) x) from: Trk where: (> x 1)}) (quote s)) +(select {c: (count x) by: (reverse x) from: Trk where: (> x 1)}) -- (select {c: (count x) by: ((fn [a] (reverse a)) x) from: Trk where: (> x 1)}) +(select {by: (distinct x) from: Trk}) !- length +(select {c: (count x) by: (distinct x) from: Trk}) !- length +;; an unknown column reads as schema, lowered or not; an unknown function +;; stays a name error +(select {c: (count x) by: (reverse nosuch) from: Trk}) !- schema +(select {by: (reverse nosuch) from: Trk}) !- schema +(select {c: (count x) by: (+ nosuch 1) from: Trk}) !- schema +(select {c: (count x) by: (reverse nosuch) from: Trk where: (> x 1)}) !- schema +(select {c: (count x) by: (nosuchfn x) from: Trk}) !- name +;; a name the key binds itself, by let or set in a do, is no column; a key +;; that binds names is left to the evaluator, which reports any unknown one +(value (select {c: (count x) by: (do (let qk x) (reverse qk)) from: Trk})) -- (value (select {c: (count x) by: (reverse x) from: Trk})) +(at (select {c: (count x) by: (do (set qkg x) (reverse qkg)) from: Trk}) (quote c)) -- [2 2 1 1] +(select {c: (count x) by: (do (let qk x) (reverse nosuch)) from: Trk}) !- name +(select {c: (count x) by: (do (reverse qk2) (let qk2 x)) from: Trk}) !- name +;; a name bound inside nested forms, by set or let in a do, an if, or +;; through a binder called by another name, is the evaluator's to resolve: +;; the unknown-column check never refuses such a key +(set fnest (fn [a] (let b a) (reverse b))) +;; (a key with an effect runs row by row: each row's key is its x) +(at (select {by: (fnest (do (do (set qn1 x)) qn1)) from: Trk}) 'x) -- (at (select {by: x from: Trk}) 'x) +(count (select {by: (reverse (if true (set qn2 x) (set qn2 s))) from: Trk})) -- (count (select {by: (reverse x) from: Trk})) +(count (select {by: (reverse (do (do (do (set qn3 x))) (do (do qn3)))) from: Trk})) -- (count (select {by: (reverse x) from: Trk})) +(set setalias set) +(count (select {by: (reverse (do (setalias qn4 x) qn4)) from: Trk})) -- (count (select {by: (reverse x) from: Trk})) +;; a binder reached through a lambda parameter, or placed in a built key as +;; the builtin itself, binds too +(set runb (fn [x] (select {by: (reverse (do (x qb s) qb)) from: Trk}))) +(count (runb set)) -- (count (select {by: s from: Trk})) +(set syk (fn [n] (as 'SYMBOL n))) +(set Kset (list (syk "reverse") (list (syk "do") (list set (syk "qo") (syk "x")) (syk "qo")))) +(count (eval (list select (dict [from by] (list Trk Kset))))) -- 4 +;; text concat is still planned, and groups the same +(at (select {c: (count x) by: (concat s "z") from: Trk}) 'c) -- [3 2 1] +;; one value is one group, holding the first row +(select {by: ((fn [a] [7]) x) from: Tcks}) -- (table [x r] (list [7] (list "c-long-string-over-12"))) +;; a name that is no column (a global vector) is grouped by its values, as +;; the with-output and by-dict forms group it. The branch took it for a +;; column and dereferenced the NULL its lookup returned. +(set Tckg (table [x y] (list [3 1 4 2] [30 10 40 20]))) +(set Vck1 [7]) +(set Vck4 [1 1 2 2]) +(set VckL (list [1] [1] [2] [2])) +(select {by: Vck1 from: Tckg}) -- (table [Vck1 x y] (list [7] [3] [30])) +(select {by: Vck4 from: Tckg}) -- (table [Vck4 x y] (list [1 2] [3 4] [30 40])) +(value (select {by: Vck4 from: Tckg})) -- (value (select {by: {k: Vck4} from: Tckg})) +(at (select {by: Vck4 from: Tckg}) 'Vck4) -- (first (value (select {c: (count y) by: Vck4 from: Tckg}))) +(select {by: Vck4 from: Tckg desc: y take: 1}) -- (table [Vck4 x y] (list [2] [4] [40])) +(select {by: Vck1 from: Tckg where: (> y 15)}) -- (table [Vck1 x y] (list [7] [3] [30])) +(key (select {by: Vck1 from: Tckg where: (> y 100)})) -- ['Vck1 'x 'y] +(count (select {by: Vck1 from: Tckg where: (> y 100)})) -- 0 +;; a global LIST is no key here, as with an output +(select {by: VckL from: Tckg}) !- schema +(select {c: (count y) by: VckL from: Tckg}) !- schema +;; a local that shadows a column: the grouping groups by the local, as the +;; with-output form does, and names its key column after no column. The +;; branch looked the key up by the column's name and read unset group keys. +(set Tcksh (table [x y] (list [3 1 4 2] [30 10 40 20]))) +(set Tcksl (table [k s l] (list [1 2 3 4] (list "aa" "bb" "cc" "dd") (list [1] [2] [3] [4])))) +((fn [y] (select {by: y from: Tcksh})) [10 10 30 30]) -- (table [y x] (list [10 30] [3 4])) +((fn [y] (at (select {by: y from: Tcksh}) 'y)) [10 10 30 30]) -- ((fn [y] (first (value (select {c: (first x) by: y from: Tcksh})))) [10 10 30 30]) +((fn [y] (at (select {by: y from: Tcksh}) 'x)) [10 10 30 30]) -- ((fn [y] (at (select {c: (first x) by: y from: Tcksh}) 'c)) [10 10 30 30]) +((fn [k] (select {by: k from: Tcksl})) [9 9 9 9]) -- (table [k s l] (list [9] (list "aa") (list [1]))) +((fn [] (let y [10 10 30 30]) (select {by: y from: Tcksh}))) -- (table [y x] (list [10 30] [3 4])) +((fn [y] (select {by: y from: Tcksh desc: y})) [10 10 30 30]) -- (table [y x] (list [30 10] [4 3])) +((fn [y] (select {by: y from: Tcksh where: (> x 0)})) [10 10 30 30]) -- (table [y x] (list [10 30] [3 4])) +;; xfail: a where: that drops rows refuses the local (4 values for 3 rows), +;; where the with-output form filters the local too: [10 30] [3 4] +;; ((fn [y] (select {by: y from: Tcksh where: (> x 1)})) [10 10 30 30]) -- (table [y x] (list [10 30] [3 4])) +;; a name bound to one value is one group, as the with-output form groups +;; it; the branch handed the atom to a grouping that takes vectors only. +;; A name bound to a function is no key. +(set Acka 5) +(set Acks "abc") +(select {by: Acka from: Tckg}) -- (table [Acka x y] (list [5] [3] [30])) +(at (select {by: Acka from: Tckg}) 'Acka) -- (first (value (select {c: (first x) by: Acka from: Tckg}))) +(at (select {by: Acka from: Tckg}) 'x) -- (at (select {c: (first x) by: Acka from: Tckg}) 'c) +(select {by: Acks from: Tckg where: (> x 3)}) -- (table [Acks x y] (list (list "abc") [4] [40])) +((fn [] (let F 2.5) (select {by: F from: Tckg}))) -- (table [F x y] (list [2.5] [3] [30])) +(type (at (select {by: Acka from: Tckg where: (> y 100)}) 'Acka)) -- 'I64 +(count (select {by: Acka from: Tckg where: (> y 100)})) -- 0 +(select {by: sum from: Tckg}) !- domain +(select {c: (count y) by: sum from: Tckg}) !- domain +;; a key that evaluates lazily (a moving window) is materialised first +(set Tcklz (update {k: (mmax 2 x) from: Tckg})) +(at (select {by: (mmax 2 x) from: Tckg}) (quote x)) -- (at (select {by: k from: Tcklz}) (quote k)) +(at (select {by: (mmax 2 x) from: Tckg}) (quote y)) -- (at (select {by: k from: Tcklz}) (quote y)) +(at (select {by: (mmax 2 x) from: Tckg desc: x}) (quote y)) -- (at (select {by: k from: Tcklz desc: k}) (quote y)) +(type (at (select {by: (mmax 2 x) from: Tckg where: (> y 100)}) (quote x))) -- (quote I64) +;; a computed by-dict key with a where: and no outputs keeps every column, in +;; the table's order: the prefilter narrowed the table to the columns the +;; clauses name, which are all an output-less select returns +(set Tckp3 (table [x y z] (list [3 1 4 2] [30 10 40 20] [7 8 9 6]))) +(set Tckp3k (update {k: (* x 2) from: Tckp3})) +(select {by: {k: (* x 2)} from: Tckp3 where: (> y 15)}) -- (select {by: k from: Tckp3k where: (> y 15)}) +(select {by: {k: (* x 2)} from: Tckp3 where: (> y 15)}) -- (table [k x y z] (list [6 8 4] [3 4 2] [30 40 20] [7 9 6])) +(key (select {by: {a: x b: (* y 2)} from: Tckp3 where: (> y 15)})) -- ['a 'b 'x 'y 'z] +(select {by: {k: (* x 2)} from: Tckp3 where: (> y 15) desc: k take: 2}) -- (table [k x y z] (list [8 6] [4 3] [40 30] [9 7])) +;; on a parted table every no-output form matches the same select on the +;; materialised table; each read a parted column as a plain one and failed +(.sys.exec "rm -rf /tmp/rfl_ckparted") +(.db.splayed.set "/tmp/rfl_ckparted/2024.01.01/t/" (table [x y s r] (list [3 1 4] [30 10 40] ['c 'a 'd] (list "c-long-string-over-12" "a" "d")))) +(.db.splayed.set "/tmp/rfl_ckparted/2024.01.02/t/" (table [x y s r] (list [2 3 1 5] [20 31 11 50] ['b 'c 'a 'e] (list "b" "c2" "a2" "e")))) +(set Pck (.db.parted.get "/tmp/rfl_ckparted/" 't)) +(set Mck (select {from: Pck where: (>= y 0)})) +(count (select {by: x from: Pck})) -- 5 +(select {by: x from: Pck}) -- (select {by: x from: Mck}) +(select {by: x from: Pck desc: y take: 2}) -- (select {by: x from: Mck desc: y take: 2}) +(select {by: (% x 2) from: Pck asc: x}) -- (select {by: (% x 2) from: Mck asc: x}) +(select {by: s from: Pck}) -- (select {by: s from: Mck}) +(select {by: r from: Pck}) -- (select {by: r from: Mck}) +(select {by: [x s] from: Pck}) -- (select {by: [x s] from: Mck}) +(select {by: {k: (* x 2)} from: Pck}) -- (select {by: {k: (* x 2)} from: Mck}) +(select {by: date from: Pck}) -- (select {by: date from: Mck}) +(select {by: x from: Pck where: (> y 15)}) -- (select {by: x from: Mck where: (> y 15)}) +;; a where: on the key column itself: kept on the row path, which flattens +;; the rows it keeps (deferred, it left the no-output paths a parted key) +(select {by: x from: Pck where: (> x 2)}) -- (select {by: x from: Mck where: (> x 2)}) +(select {by: x from: Pck where: (>= x 0)}) -- (select {by: x from: Mck where: (>= x 0)}) +(select {by: date from: Pck where: (> date 2024.01.01)}) -- (select {by: date from: Mck where: (> date 2024.01.01)}) +;; a key the planner cannot lower reads whole columns of a parted table, as +;; of the flat one: a helper, a builtin with no kernel; with and without +;; outputs, sorted and taken, filtered +(set fkp (fn [] (% x 2))) +(select {by: (fkp) from: Pck}) -- (select {by: (fkp) from: Mck}) +(select {c: (count y) by: (fkp) from: Pck}) -- (select {c: (count y) by: (fkp) from: Mck}) +(select {by: (reverse x) from: Pck}) -- (select {by: (reverse x) from: Mck}) +(select {c: (count y) by: (reverse x) from: Pck}) -- (select {c: (count y) by: (reverse x) from: Mck}) +(select {s: (sum y) by: (reverse x) from: Pck desc: s take: 2}) -- (select {s: (sum y) by: (reverse x) from: Mck desc: s take: 2}) +(select {c: (count y) by: (reverse x) from: Pck where: (> y 15)}) -- (select {c: (count y) by: (reverse x) from: Mck where: (> y 15)}) +(select {by: (reverse x) from: Pck desc: y take: 2}) -- (select {by: (reverse x) from: Mck desc: y take: 2}) +(select {by: (fkp) from: Pck asc: r}) -- (select {by: (fkp) from: Mck asc: r}) +(select {c: (count y) by: (distinct x) from: Pck}) !- length +;; and as a by-dict value: a helper or a builtin with no kernel, beside +;; outputs, sorted, filtered, with a second key, with no output +(select {c: (count y) by: {k: (fkp)} from: Pck}) -- (select {c: (count y) by: {k: (fkp)} from: Mck}) +(select {c: (count y) by: {k: (reverse x)} from: Pck}) -- (select {c: (count y) by: {k: (reverse x)} from: Mck}) +(select {sy: (sum y) by: {k: (fkp)} from: Pck desc: sy take: 2}) -- (select {sy: (sum y) by: {k: (fkp)} from: Mck desc: sy take: 2}) +(select {c: (count y) by: {k: (fkp)} from: Pck where: (> y 15)}) -- (select {c: (count y) by: {k: (fkp)} from: Mck where: (> y 15)}) +(select {c: (count y) by: {k: (fkp) ks: s} from: Pck}) -- (select {c: (count y) by: {k: (fkp) ks: s} from: Mck}) +(select {by: {k: (fkp)} from: Pck}) -- (select {by: {k: (fkp)} from: Mck}) +;; a where: before a computed key keeps every column when a helper reads +;; one the clauses do not name (x here) +(set Tnw (table [x y z] (list [3 1 4 2 3] [10 20 30 40 50] [1 1 1 1 1]))) +(select {c: (count y) by: {k: (fkp)} from: Tnw where: (> y 15)}) -- (select {c: (count y) by: {k: (% x 2)} from: Tnw where: (> y 15)}) +;; a sort without by: sorts the keys and gathers the rows they keep; the +;; flat sort it fell to read parted columns as plain ones and failed +(select {from: Pck desc: x}) -- (select {from: Mck desc: x}) +(select {from: Pck asc: y}) -- (select {from: Mck asc: y}) +(select {from: Pck desc: x take: 2}) -- (select {from: Mck desc: x take: 2}) +(select {from: Pck asc: x take: -2}) -- (select {from: Mck asc: x take: -2}) +;; take: 0 with a sort keeps no row, on every path (the flat sort fused +;; with its take read 0 as no limit and kept every row) +(select {from: Pck asc: x take: 0}) -- (select {from: Mck asc: x take: 0}) +(count (select {from: Mck asc: x take: 0})) -- 0 +(count (select {from: Pck asc: x take: 0})) -- 0 +(count (select {from: Mck desc: x take: 0})) -- 0 +(count (select {x: x from: Mck asc: x take: 0})) -- 0 +(count (select {x: x from: Pck asc: x take: 0})) -- 0 +(count (select {y: y from: Pck desc: x take: 0})) -- 0 +(count (select {from: Mck asc: [x y] take: 0})) -- 0 +(count (select {from: Mck where: (> y 15) asc: x take: 0})) -- 0 +(count (select {from: Pck where: (> y 15) asc: x take: 0})) -- 0 +(key (select {x: x from: Mck asc: x take: 0})) -- [x] +(select {from: Pck asc: x take: [1 3]}) -- (select {from: Mck asc: x take: [1 3]}) +(select {from: Pck asc: [x y]}) -- (select {from: Mck asc: [x y]}) +(select {from: Pck asc: x desc: y}) -- (select {from: Mck asc: x desc: y}) +(select {from: Pck where: (> y 15) desc: x take: 2}) -- (select {from: Mck where: (> y 15) desc: x take: 2}) +(select {from: Pck asc: s}) -- (select {from: Mck asc: s}) +(select {from: Pck desc: r take: 3}) -- (select {from: Mck desc: r take: 3}) +(select {from: Pck desc: date}) -- (select {from: Mck desc: date}) +(select {from: Pck desc: 'y}) -- (select {from: Mck desc: 'y}) +(select {x: x from: Pck desc: x}) -- (select {x: x from: Mck desc: x}) +(select {y: y from: Pck desc: x}) -- (select {y: y from: Mck desc: x}) +;; sort keys no output carries, or carried under another name: the sort +;; reads them as columns whatever the outputs are named, as the flat one +;; does; an output naming another output reads that output +(select {y: y s: s from: Pck desc: x take: 2}) -- (select {y: y s: s from: Mck desc: x take: 2}) +(select {s: s from: Pck asc: [y x] take: -2}) -- (select {s: s from: Mck asc: [y x] take: -2}) +(select {z: x r: r from: Pck asc: x}) -- (select {z: x r: r from: Mck asc: x}) +(select {date: date y: y from: Pck desc: y take: 3}) -- (select {date: date y: y from: Mck desc: y take: 3}) +(select {x: y r: r from: Pck desc: x}) -- (select {x: y r: r from: Mck desc: x}) +(select {x: y y: x from: Pck desc: y}) -- (select {x: y y: x from: Mck desc: y}) +(select {x: y z: x y: y from: Pck desc: y}) -- (select {x: y z: x y: y from: Mck desc: y}) +;; an output named after a lambda parameter reads the parameter, not the +;; column it hides +(set runs (fn [tbl x] (select {y: y x: x from: tbl desc: y}))) +(runs Pck 7) -- (runs Mck 7) +;; a dotted output (a field of the partition date) is no stored column: the +;; flat sort answers it +(select {month: date.mm from: Pck desc: x}) -- (select {month: date.mm from: Mck desc: x}) +(select {day: date.dd from: Pck asc: y}) -- (select {day: date.dd from: Mck asc: y}) +(select {month: date.mm y: y from: Pck desc: y take: 2}) -- (select {month: date.mm y: y from: Mck desc: y take: 2}) +;; with take: too (the per-partition top-k sorted each partition on the +;; column and merged them on the output of that name) +(select {x: y r: r from: Pck desc: x take: 3}) -- (select {x: y r: r from: Mck desc: x take: 3}) +(select {x: y y: x from: Pck desc: y take: 2}) -- (select {x: y y: x from: Mck desc: y take: 2}) +;; it groups on the columns the clauses name and gathers the others at the +;; rows kept: a sort key only in desc:/asc:, a by-dict value's column, the +;; partition key sorted, every row its own group, a key from a global +(select {by: x from: Pck desc: r take: 3}) -- (select {by: x from: Mck desc: r take: 3}) +(select {by: x from: Pck asc: s}) -- (select {by: x from: Mck asc: s}) +(select {by: {k: y} from: Pck}) -- (select {by: {k: y} from: Mck}) +(select {by: {k: (% y 20)} from: Pck}) -- (select {by: {k: (% y 20)} from: Mck}) +(select {by: date from: Pck desc: date}) -- (select {by: date from: Mck desc: date}) +(select {by: y from: Pck}) -- (select {by: y from: Mck}) +(select {by: y from: Pck desc: y}) -- (select {by: y from: Mck desc: y}) +(set Vck7 [1 1 2 2 3 3 3]) +(select {by: Vck7 from: Pck}) -- (select {by: Vck7 from: Mck}) +(select {by: x from: Pck take: [1 2]}) -- (select {by: x from: Mck take: [1 2]}) +;; a quoted symbol naming the key or the sort column is that column too +(select {by: 's from: Pck}) -- (select {by: 's from: Mck}) +(select {by: 'r from: Pck}) -- (select {by: 'r from: Mck}) +(select {by: 'date from: Pck}) -- (select {by: 'date from: Mck}) +(select {by: s from: Pck desc: 'y}) -- (select {by: s from: Mck desc: 'y}) +(select {by: s from: Pck asc: 'r take: 2}) -- (select {by: s from: Mck asc: 'r take: 2}) +(.sys.exec "rm -rf /tmp/rfl_ckparted") +;; a column named as a computed key is (`key`): the key replaces it in the +;; result, as on the flattened table +(.sys.exec "rm -rf /tmp/rfl_ckpkey") +(.db.splayed.set "/tmp/rfl_ckpkey/2024.01.01/t/" (table [x key] (list [3 1 4] [7 8 9]))) +(.db.splayed.set "/tmp/rfl_ckpkey/2024.01.02/t/" (table [x key] (list [2 3 1 5] [6 5 4 3]))) +(set Pckk (.db.parted.get "/tmp/rfl_ckpkey/" 't)) +(set Mckk (select {from: Pckk where: (>= x 0)})) +(select {by: (+ (% x 2) 1) from: Pckk}) -- (select {by: (+ (% x 2) 1) from: Mckk}) +(select {by: 5 from: Pckk}) -- (select {by: 5 from: Mckk}) +(.sys.exec "rm -rf /tmp/rfl_ckpkey") +;; columns a key's naming checks read are grouped on for real: a dotted +;; key's tail names a column (mm), so the key takes the full name; a +;; by-dict alias that names a column is refused +(.sys.exec "rm -rf /tmp/rfl_ckpkn") +(.db.splayed.set "/tmp/rfl_ckpkn/2024.01.01/t/" (table [x mm dd] (list [0 1 2] [7 8 9] [5 5 6]))) +(.db.splayed.set "/tmp/rfl_ckpkn/2024.02.02/t/" (table [x mm dd] (list [10 11 12] [7 8 9] [5 5 6]))) +(set Pckn (.db.parted.get "/tmp/rfl_ckpkn/" 't)) +(set Mckn (select {from: Pckn where: (>= x 0)})) +(select {by: date.mm from: Pckn}) -- (select {by: date.mm from: Mckn}) +(select {by: date.dd from: Pckn}) -- (select {by: date.dd from: Mckn}) +(select {by: {mm: (% x 2)} from: Mckn}) !- domain +(select {by: {mm: (% x 2)} from: Pckn}) !- domain +(.sys.exec "rm -rf /tmp/rfl_ckpkn") +;; the row-number column the parted paths add is never one the select +;; names: a by-dict key, a bound variable a key reads, a sort key +(.sys.exec "rm -rf /tmp/rfl_ckrown") +(.db.splayed.set "/tmp/rfl_ckrown/2024.01.01/t/" (table [i s] (list [3 1 2 5] [b a b c]))) +(.db.splayed.set "/tmp/rfl_ckrown/2024.01.02/t/" (table [i s] (list [4 0 7] [a c a]))) +(set Prn (.db.parted.get "/tmp/rfl_ckrown/" 't)) +(set Mrn (select {from: Prn where: (>= i 0)})) +(select {by: {__row: s} from: Prn}) -- (select {by: {__row: s} from: Mrn}) +(count (select {by: {__row: s} from: Prn})) -- 3 +;; nor one a select reads unseen: a helper that reads a column by name, or +;; a name made at run time (the column a helper or eval reads is not in +;; the clauses, so the narrow copy would miss it or offer the row number) +(set hx (fn [] i)) +(select {by: {k: (hx)} from: Prn}) -- (select {by: {k: (hx)} from: Mrn}) +(set hr2 (fn [] __row)) +(select {by: {k: (hr2)} from: Mrn}) !- name +(select {by: {k: (hr2)} from: Prn}) !- name +(select {by: {k: (eval (parse "__row"))} from: Mrn}) !- name +(select {by: {k: (eval (parse "__row"))} from: Prn}) !- name +(select {by: {k: (eval (as 'SYMBOL "__row"))} from: Mrn}) !- name +(select {by: {k: (eval (as 'SYMBOL "__row"))} from: Prn}) !- name +;; the helper called by a quoted name, through a computed callee, or out of +;; a list +(set hy (fn [x] i)) +(set Ly (list hy)) +(select {by: {k: ('hy 0)} from: Prn}) -- (select {by: {k: ('hy 0)} from: Mrn}) +(select {by: {k: ((first Ly) 0)} from: Prn}) -- (select {by: {k: ((first Ly) 0)} from: Mrn}) +(select {by: {k: (first (map (first Ly) [0]))} from: Prn}) -- (select {by: {k: (first (map (first Ly) [0]))} from: Mrn}) +;; or by a dotted name into a dict of helper names ({f: hy} holds the name) +(set Dl {f: hy}) +(select {by: {k: (Dl.f 0)} from: Prn}) -- (select {by: {k: (Dl.f 0)} from: Mrn}) +(count (select {by: {k: (Dl.f 0)} from: Prn})) -- 7 +(set hz (fn [] __row)) +(set Dz {g: hz}) +(select {by: {k: (Dz.g)} from: Mrn}) !- name +(select {by: {k: (Dz.g)} from: Prn}) !- name +;; or by a name bound to the helper's name +(set gy 'hy) +(select {by: {k: (gy 0)} from: Prn}) -- (select {by: {k: (gy 0)} from: Mrn}) +(set __row [1 1 2 2 3 3 3]) +(select {by: {k: __row} from: Prn}) -- (select {by: {k: __row} from: Mrn}) +(count (select {by: {k: __row} from: Prn})) -- 3 +;; a helper reading the bound __row reads the variable, as on the flat table +(set hr (fn [] __row)) +(select {by: {k: (hr)} from: Prn}) -- (select {by: {k: (hr)} from: Mrn}) +(count (select {by: {k: (hr)} from: Prn})) -- 3 +;; a builtin that evaluates a name, called by another name, is code too: +;; it reads the variable, as on the flat table, not the row number +(set getv resolve) +(set rname '__row) +(select {by: {k: (getv rname)} from: Prn}) -- (select {by: {k: (getv rname)} from: Mrn}) +(count (select {by: {k: (getv rname)} from: Prn})) -- 3 +(set getq 'resolve) +(select {by: {k: (getq rname)} from: Prn}) -- (select {by: {k: (getq rname)} from: Mrn}) +(set evq eval) +(set paq parse) +(select {by: {k: (evq (paq "__row"))} from: Prn}) -- (select {by: {k: (evq (paq "__row"))} from: Mrn}) +(count (select {by: {k: (evq (paq "__row"))} from: Prn})) -- 3 +;; the builtin itself placed in a built query is code as well +(set Erow (list resolve (syk "rname"))) +(set Qrp (dict [from by] (list Prn (dict [k] (list Erow))))) +(set Qrm (dict [from by] (list Mrn (dict [k] (list Erow))))) +(eval (list select Qrp)) -- (eval (list select Qrm)) +(count (eval (list select Qrp))) -- 3 +;; a lambda parameter hides the column of its name: the helper passed in it +;; reads a column (s) the clauses do not name +(set runl (fn [tbl i] (select {by: {k: (i)} from: tbl}))) +(runl Prn (fn [] s)) -- (runl Mrn (fn [] s)) +(select {i: i from: Prn desc: i take: 2}) -- (select {i: i from: Mrn desc: i take: 2}) +(select {from: Prn asc: s}) -- (select {from: Mrn asc: s}) +(set __row 0) +(.sys.exec "rm -rf /tmp/rfl_ckrown") diff --git a/test/rfl/query/select_agg_eval_fallback.rfl b/test/rfl/query/select_agg_eval_fallback.rfl index fe2fd210c..0625e7892 100644 --- a/test/rfl/query/select_agg_eval_fallback.rfl +++ b/test/rfl/query/select_agg_eval_fallback.rfl @@ -70,5 +70,8 @@ (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 +;; A scalar aggregate broadcasts to the collection's length in either order. +(set D (table [i] (list [1 2 2 3]))) +(at (select {a: (distinct i) m: (max i) from: D}) 'm) -- [3 3 3] +(at (select {m: (max i) a: (distinct i) from: D}) 'm) -- [3 3 3] +(select {a: (distinct i) v: i from: D}) !- length diff --git a/test/rfl/query/sym_not_in_nulls.rfl b/test/rfl/query/sym_not_in_nulls.rfl new file mode 100644 index 000000000..ecc8965c2 --- /dev/null +++ b/test/rfl/query/sym_not_in_nulls.rfl @@ -0,0 +1,45 @@ +;; @requires: posix (splayed fixture cleanup via .sys.exec) +;; #739: null SYM rows must fail both in and not-in, whether the probe +;; uses the domain LUT or falls back after all literals miss the file domain. +(.sys.exec "rm -rf /tmp/rfl_sym_not_in_nulls") -- 0 +(set T (table [s x] (list (as 'SYM (list "a" "" "b" "a" "" "c")) [1 0Nl 2 1 0Nl 3]))) +(.db.splayed.set "/tmp/rfl_sym_not_in_nulls/" T) +(set U (.db.splayed.get "/tmp/rfl_sym_not_in_nulls/")) + +;; Matched/mixed and wholly absent probes, scalar and vector forms. +(at (select {from: T where: (not-in s 'a)}) 'x) -- [2 3] +(at (select {from: U where: (not-in s 'a)}) 'x) -- [2 3] +(at (select {from: T where: (not-in s ['a 'zz])}) 'x) -- [2 3] +(at (select {from: U where: (not-in s ['a 'zz])}) 'x) -- [2 3] +(at (select {from: T where: (not-in s 'zz)}) 'x) -- [1 2 1 3] +(at (select {from: U where: (not-in s 'zz)}) 'x) -- [1 2 1 3] +(at (select {from: T where: (not-in s ['zz 'qq])}) 'x) -- [1 2 1 3] +(at (select {from: U where: (not-in s ['zz 'qq])}) 'x) -- [1 2 1 3] +(count (select {from: T where: (not-in s ['a 'zz])})) -- 2 +(count (select {from: U where: (not-in s ['a 'zz])})) -- 2 +(count (select {from: T where: (not-in x [1 9])})) -- 2 +(count (select {from: U where: (not-in x [1 9])})) -- 2 + +;; Null set elements are ignored; empty/all-null sets still exclude null rows. +(set WithNull (as 'SYM (list "a" "" "zz"))) +(set NullSet (as 'SYM (list ""))) +(set EmptySet (as 'SYM (list))) +(at (select {from: T where: (not-in s WithNull)}) 'x) -- [2 3] +(at (select {from: U where: (not-in s WithNull)}) 'x) -- [2 3] +(at (select {from: T where: (not-in s NullSet)}) 'x) -- [1 2 1 3] +(at (select {from: U where: (not-in s NullSet)}) 'x) -- [1 2 1 3] +(at (select {from: T where: (not-in s EmptySet)}) 'x) -- [1 2 1 3] +(at (select {from: U where: (not-in s EmptySet)}) 'x) -- [1 2 1 3] + +;; Projection checks the entire boolean output, including both null positions. +(at (select {v: (not-in s ['a 'zz]) from: T}) 'v) -- [false false true false false true] +(at (select {v: (not-in s ['a 'zz]) from: U}) 'v) -- [false false true false false true] +(at (select {v: (not-in s 'zz) from: T}) 'v) -- [true false true true false true] +(at (select {v: (not-in s 'zz) from: U}) 'v) -- [true false true true false true] + +;; Positive membership must retain its existing null-matches-nothing behavior. +(at (select {from: T where: (in s WithNull)}) 'x) -- [1 1] +(at (select {from: U where: (in s WithNull)}) 'x) -- [1 1] +(count (select {from: T where: (in s NullSet)})) -- 0 +(count (select {from: U where: (in s NullSet)})) -- 0 +(.sys.exec "rm -rf /tmp/rfl_sym_not_in_nulls") -- 0 diff --git a/test/rfl/query/sym_ordered_compare.rfl b/test/rfl/query/sym_ordered_compare.rfl new file mode 100644 index 000000000..312a71c3a --- /dev/null +++ b/test/rfl/query/sym_ordered_compare.rfl @@ -0,0 +1,82 @@ +;; #738: query ordering must follow strings, regardless of intern order. +(set T (table [s n] (list (as 'SYM ["zz" "mm" "" "aa" "mm"]) (til 5)))) +(sum (< (at T 's) 'mm)) -- 2 +(count (select {from: T where: (< s 'mm)})) -- 2 +(at (select {from: T where: (< s 'mm)}) 'n) -- [2 3] +(at (select {from: T where: (and (< s 'mm) true)}) 'n) -- [2 3] +(at (select {from: T where: (< s "mm")}) 'n) -- [2 3] +(sum (<= (at T 's) 'mm)) -- 4 +(count (select {from: T where: (<= s 'mm)})) -- 4 +(at (select {from: T where: (<= s 'mm)}) 'n) -- [1 2 3 4] +(at (select {from: T where: (and (<= s 'mm) true)}) 'n) -- [1 2 3 4] +(at (select {from: T where: (<= s "mm")}) 'n) -- [1 2 3 4] +(sum (> (at T 's) 'mm)) -- 1 +(count (select {from: T where: (> s 'mm)})) -- 1 +(at (select {from: T where: (> s 'mm)}) 'n) -- [0] +(at (select {from: T where: (and (> s 'mm) true)}) 'n) -- [0] +(at (select {from: T where: (> s "mm")}) 'n) -- [0] +(sum (>= (at T 's) 'mm)) -- 3 +(count (select {from: T where: (>= s 'mm)})) -- 3 +(at (select {from: T where: (>= s 'mm)}) 'n) -- [0 1 4] +(at (select {from: T where: (and (>= s 'mm) true)}) 'n) -- [0 1 4] +(at (select {from: T where: (>= s "mm")}) 'n) -- [0 1 4] +(sum (== (at T 's) 'mm)) -- 2 +(count (select {from: T where: (== s 'mm)})) -- 2 +(at (select {from: T where: (== s 'mm)}) 'n) -- [1 4] +(at (select {from: T where: (and (== s 'mm) true)}) 'n) -- [1 4] +(at (select {from: T where: (== s "mm")}) 'n) -- [1 4] +(sum (!= (at T 's) 'mm)) -- 3 +(count (select {from: T where: (!= s 'mm)})) -- 3 +(at (select {from: T where: (!= s 'mm)}) 'n) -- [0 2 3] +(at (select {from: T where: (and (!= s 'mm) true)}) 'n) -- [0 2 3] +(at (select {from: T where: (!= s "mm")}) 'n) -- [0 2 3] + +;; Operand reversal, projection, compound predicates and absent literals. +(at (select {from: T where: (> 'mm s)}) 'n) -- [2 3] +(at (select {v: (< s 'mm) from: T}) 'v) -- [false false true true false] +(at (select {from: T where: (or (< s 'mm) (> s 'mm))}) 'n) -- [0 2 3] +(at (select {from: T where: (< s 'nn)}) 'n) -- [1 2 3 4] +(at (select {from: T where: (< s "nn-uninterned-738")}) 'n) -- [1 2 3 4] +(at (select {from: T where: (> "nn-uninterned-738" s)}) 'n) -- [1 2 3 4] +(at (select {from: T where: (<= s "")}) 'n) -- [2] +(at (select {from: T where: (< s "")}) 'n) -- [] +(at (select {from: T where: (> s "")}) 'n) -- [0 1 3 4] + +;; SYM columns conservatively fail the count shortcut's null proof, even +;; without null rows. Check counts and row identities through the DAG path. +(set U (table [s n] (list (as 'SYM ["zz" "mm" "aa" "mm"]) (til 4)))) +(count (select {from: U where: (< s 'mm)})) -- 1 +(count (select {from: U where: (<= s 'mm)})) -- 3 +(count (select {from: U where: (> s 'mm)})) -- 1 +(count (select {from: U where: (>= s 'mm)})) -- 3 +(at (select {from: U where: (< s 'mm)}) 'n) -- [2] +(at (select {from: U where: (> s 'mm)}) 'n) -- [0] + +;; Single-row inputs and empty outputs. +(set O (table [s] (list (as 'SYM ["aa"])))) +(count (select {from: O where: (< s 'mm)})) -- 1 +(at (select {v: (< s 'mm) from: O}) 'v) -- [true] +(set E (select {from: T where: (< n 0)})) +(count (select {from: E where: (< s 'mm)})) -- 0 + +;; Parallel-sized input: count, materialized filter, projection and top-k. +(set B (table [s n] (list (as 'SYM (at ["zz" "mm" "" "aa" "mm"] (% (til 50000) 5))) (til 50000)))) +(count (select {from: B where: (< s 'mm)})) -- 20000 +(count (at (select {from: B where: (and (< s 'mm) true)}) 'n)) -- 20000 +(sum (at (select {v: (< s 'mm) from: B}) 'v)) -- 20000 +(count (select {from: B where: (<= s 'mm)})) -- 40000 +(count (at (select {from: B where: (and (<= s 'mm) true)}) 'n)) -- 40000 +(sum (at (select {v: (<= s 'mm) from: B}) 'v)) -- 40000 +(count (select {from: B where: (> s 'mm)})) -- 10000 +(count (at (select {from: B where: (and (> s 'mm) true)}) 'n)) -- 10000 +(sum (at (select {v: (> s 'mm) from: B}) 'v)) -- 10000 +(count (select {from: B where: (>= s 'mm)})) -- 30000 +(count (at (select {from: B where: (and (>= s 'mm) true)}) 'n)) -- 30000 +(sum (at (select {v: (>= s 'mm) from: B}) 'v)) -- 30000 +(at (select {n: n from: B where: (< s 'mm) asc: n take: 5}) 'n) -- [2 3 7 8 12] + +;; Symbol constants must not be folded using integer IDs either. +(sum (at (select {v: (< 'zz 'mm) from: T}) 'v)) -- 0 +(sum (at (select {v: (> 'zz 'mm) from: T}) 'v)) -- 5 +(sum (at (select {v: (<= 'aa 'mm) from: T}) 'v)) -- 5 +(sum (at (select {v: (>= 'aa 'mm) from: T}) 'v)) -- 0 diff --git a/test/rfl/query/update_fallback_semantics.rfl b/test/rfl/query/update_fallback_semantics.rfl index 072916325..b1f6e0629 100644 --- a/test/rfl/query/update_fallback_semantics.rfl +++ b/test/rfl/query/update_fallback_semantics.rfl @@ -64,3 +64,13 @@ ;; (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 +;; under by: as well, including after an output of the same update, or an +;; earlier update, whose expression the planner declined: the planner is +;; asked again for every expression of every call +(set hw5 (fn [m] (let a 0) (times 10 (let a (+ a m))) a)) +(update {x: (+ nosuch 1) by: k from: t}) !- schema +(update {a: (hw5 (count i)) x: (+ nosuch 1) by: k from: t}) !- schema +(at (update {a: (hw5 (count i)) by: k from: t}) 'a) -- [20 20 30 30 30] +(update {x: (+ nosuch 1) by: k from: t}) !- schema +(times 20 (eval (parse "(update {a: (hw5 (count i)) by: k from: t})"))) +(eval (parse "(update {x: (+ nosuch 1) by: k from: t})")) !- schema diff --git a/test/rfl/regress/issue_756.rfl b/test/rfl/regress/issue_756.rfl new file mode 100644 index 000000000..70b030158 --- /dev/null +++ b/test/rfl/regress/issue_756.rfl @@ -0,0 +1,111 @@ +;; #756 — a select grouped by two or more keys failed with `name` when it held +;; a `(count (distinct x))` beside an aggregate over an expression, such as +;; `(sum (if …))`. The shape took the eval-level grouping, which evaluated an +;; aggregate's argument with no column in scope — and that grouping is serial. +;; A plain multi-key by: whose only non-DAG outputs are distinct counts and +;; literal broadcasts now stays on the parallel DAG path: the post-group +;; scatter maps rows to groups through the composite key. The eval-level +;; grouping (a row expression beside the key) evaluates an aggregate's +;; argument over the selected rows, as a row-wise projection. +(set T (table [k1 k2 id st v] (list (take ['a 'b 'c 'd 'e] 1000) (take ['p 'q 'r 's 't 'u 'v 'w 'x] 1000) (% (til 1000) 300) (take ['ok 'ok 'ok 'ok 'ok 'ok 'bad] 1000) (% (til 1000) 7)))) +;; the oracle: the two aggregates in two selects, joined on the keys +(set O (left-join [k1 k2] (select {from: T by: [k1 k2] n: (count (distinct id)) asc: [k1 k2]}) (select {from: T by: [k1 k2] bad: (sum (if (== st 'bad) 1 0))}))) +(set A (select {from: T by: [k1 k2] n: (count (distinct id)) bad: (sum (if (== st 'bad) 1 0)) asc: [k1 k2]})) +(count A) -- 45 +(key A) -- ['k1 'k2 'n 'bad] +(at A 'k1) -- (at O 'k1) +(at A 'k2) -- (at O 'k2) +(at A 'n) -- (at O 'n) +(at A 'bad) -- (at O 'bad) +(sum (at A 'bad)) -- 142 +;; the aggregates in the other order, and an aggregate over arithmetic +(at (select {from: T by: [k1 k2] bad: (sum (if (== st 'bad) 1 0)) n: (count (distinct id)) asc: [k1 k2]}) 'n) -- (at O 'n) +(at (select {from: T by: [k1 k2] n: (count (distinct id)) m: (max (+ id 1)) asc: [k1 k2]}) 'm) -- (at (select {from: T by: [k1 k2] m: (max (+ id 1)) asc: [k1 k2]}) 'm) +;; the inner-select form the issue used as a workaround agrees +(at (select {from: (select {from: T id: id k1: k1 k2: k2 bad_arg: (if (== st 'bad) 1 0)}) by: [k1 k2] n: (count (distinct id)) bad: (sum bad_arg) asc: [k1 k2]}) 'bad) -- (at O 'bad) + +;; where: — a whole-key filter, and one that keeps part of every morsel +(set Ow (left-join [k1 k2] (select {from: T where: (!= k1 'a) by: [k1 k2] n: (count (distinct id)) asc: [k1 k2]}) (select {from: T where: (!= k1 'a) by: [k1 k2] bad: (sum (if (== st 'bad) 1 0))}))) +(set Aw (select {from: T where: (!= k1 'a) by: [k1 k2] n: (count (distinct id)) bad: (sum (if (== st 'bad) 1 0)) asc: [k1 k2]})) +(count Aw) -- 36 +(at Aw 'n) -- (at Ow 'n) +(at Aw 'bad) -- (at Ow 'bad) +(set Om (left-join [k1 k2] (select {from: T where: (< v 3) by: [k1 k2] n: (count (distinct id)) asc: [k1 k2]}) (select {from: T where: (< v 3) by: [k1 k2] c: (count id)}))) +(set Am (select {from: T where: (< v 3) by: [k1 k2] n: (count (distinct id)) c: (count id) asc: [k1 k2]})) +(count Am) -- 45 +(at Am 'n) -- (at Om 'n) +(at Am 'c) -- (at Om 'c) +(count (select {from: T where: (> v 100) by: [k1 k2] n: (count (distinct id)) bad: (sum (if (== st 'bad) 1 0))})) -- 0 + +;; three keys, one of them an integer column +(set O3 (left-join [k1 k2 v] (select {from: T by: [k1 k2 v] n: (count (distinct id)) asc: [k1 k2 v]}) (select {from: T by: [k1 k2 v] s: (sum (* id 2))}))) +(set A3 (select {from: T by: [k1 k2 v] n: (count (distinct id)) s: (sum (* id 2)) asc: [k1 k2 v]})) +(count A3) -- 315 +(at A3 'n) -- (at O3 'n) +(at A3 's) -- (at O3 's) + +;; a literal broadcast beside the distinct count; desc:/take: over the result +(at (select {from: T by: [k1 k2] one: 1 n: (count (distinct id)) asc: [k1 k2]}) 'n) -- (at O 'n) +(sum (at (select {from: T by: [k1 k2] one: 1 n: (count (distinct id))}) 'one)) -- 45 +(at (select {from: T by: [k1 k2] n: (count (distinct id)) bad: (sum (if (== st 'bad) 1 0)) desc: bad take: 3}) 'bad) -- (at (select {from: O desc: bad take: 3}) 'bad) + +;; the eval-level grouping: a row expression beside the key keeps it, and +;; the expression aggregate evaluates there too — two keys and one +(at (select {from: T by: [k1 k2] bad: (sum (if (== st 'bad) 1 0)) r: (+ v 1) asc: [k1 k2]}) 'bad) -- (at O 'bad) +(at (select {from: T by: [k1 k2] n: (count (distinct id)) bad: (sum (if (== st 'bad) 1 0)) r: (+ v 1) asc: [k1 k2]}) 'n) -- (at O 'n) +(at (select {from: T by: k1 bad: (sum (if (== st 'bad) 1 0)) r: (+ v 1) asc: k1}) 'bad) -- (at (select {from: T by: k1 bad: (sum (if (== st 'bad) 1 0)) asc: k1}) 'bad) +;; a distinct count alone beside a composite key takes the same path when its +;; (keys, value) grouping would not be dense — two keys, where:, a by-dict — +;; and the two-pass rewrite otherwise (xlo: 7 values beside 45 groups) +(at (select {from: T by: [k1 k2] n: (count (distinct id)) asc: [k1 k2]}) 'n) -- (at O 'n) +(at (select {from: T where: (!= k1 'a) by: [k1 k2] n: (count (distinct id)) asc: [k1 k2]}) 'n) -- (at Ow 'n) +(at (select {from: T by: {a: k1 b: k2} n: (count (distinct id)) asc: [a b]}) 'n) -- (at O 'n) +(key (select {from: T by: {a: k1 b: k2} n: (count (distinct id))})) -- ['a 'b 'n] +;; a by-dict names its keys on every route: the rewrite (v: 7 values beside +;; 45 groups, a dense composite) emits the aliases as the scatter does — a +;; planner choice may not change the result's names — with the count +;; renamed beside them, under desc:/take:, and for one key under where: +(key (select {from: T by: {a: k1 b: k2} n: (count (distinct v))})) -- ['a 'b 'n] +(at (select {from: T by: {a: k1 b: k2} n: (count (distinct v)) asc: [a b]}) 'n) -- (at (select {from: T by: [k1 k2] n: (count (distinct v)) asc: [k1 k2]}) 'n) +(key (select {from: T by: {a: k1 b: k2} n: (count (distinct v)) desc: n take: 3})) -- ['a 'b 'n] +(key (select {from: T by: {g: k1} where: (!= k1 'a) n: (count (distinct v))})) -- ['g 'n] +(at (select {from: T by: {g: k1} where: (!= k1 'a) n: (count (distinct v)) asc: g}) 'g) -- ['b 'c 'd 'e] +;; the fused single-key kernel (262 144 rows and up, with workers) names the +;; key by its alias as the other routes do +(set Tb (table [k1 k2 x] (list (as 'SYM (% (til 300000) 7)) (% (til 300000) 3) (% (til 300000) 1000)))) +(key (select {from: Tb by: {g: k1} n: (count (distinct x)) desc: n take: 2})) -- ['g 'n] +(key (select {from: Tb by: {g: k1} n: (count (distinct x))})) -- ['g 'n] +(at (select {from: Tb by: {g: k1} n: (count (distinct x)) asc: g}) 'n) -- (at (select {from: Tb by: k1 n: (count (distinct x)) asc: k1}) 'n) +;; a duplicate alias is the by-dict's error on every route; an alias equal to +;; the count's name yields the same two columns on every route — the key +;; under it first, the count second +(select {from: Tb by: {g: k1 g: k2} n: (count (distinct x))}) !- domain +(select {from: Tb by: {g: k1 g: k1} n: (count (distinct x))}) !- domain +(key (select {from: Tb by: {n: k1} n: (count (distinct x))})) -- ['n 'n] +(at (value (select {from: Tb by: {n: k1} n: (count (distinct x))})) 1) -- (take [1000] 7) +(key (select {from: Tb by: {n: k1 h: k2} n: (count (distinct x))})) -- ['n 'h 'n] +(at (value (select {from: Tb by: {n: k1 h: k2} n: (count (distinct x))})) 2) -- (take [1000] 21) +;; an alias naming another input column is rejected the same way on every route +(select {from: T by: {k2: k1} n: (count (distinct v))}) !- domain +(select {from: T by: {k2: k1 k1: k2} n: (count (distinct v))}) !- domain +(at (select {from: T by: [k1 k2] n: (count (distinct v)) asc: [k1 k2]}) 'n) -- (at (select {from: T by: [k1 k2] one: 1 n: (count (distinct v)) asc: [k1 k2]}) 'n) +(at (select {from: T by: [k1 k2] n: (count (distinct id)) desc: n take: 3}) 'n) -- (at (select {from: O desc: n take: 3}) 'n) +;; an aggregate over an `if` under where: — the v2 engine takes it through +;; a materialized input instead of the legacy group +(at (select {from: T where: (!= k1 'a) by: [k1 k2] bad: (sum (if (== st 'bad) 1 0)) asc: [k1 k2]}) 'bad) -- (at Ow 'bad) +(at (select {from: T where: (< v 3) by: k1 bad: (sum (if (== st 'bad) 1 0)) asc: k1}) 'bad) -- (at (select {from: (select {from: T where: (< v 3) k1: k1 b: (if (== st 'bad) 1 0)}) by: k1 bad: (sum b) asc: k1}) 'bad) +;; one key, the shape that always worked +(at (select {from: T by: k1 n: (count (distinct id)) bad: (sum (if (== st 'bad) 1 0)) asc: k1}) 'bad) -- (at (select {from: T by: k1 bad: (sum (if (== st 'bad) 1 0)) asc: k1}) 'bad) + +;; 60 K groups under where: — the composite probe applies the selection, and +;; past 50 K groups the distinct counts come from the global-hash kernel, +;; which reads the probe's row→group map alone. Every group has four rows, +;; one in each quarter of the table; the filter keeps the first, so a probe +;; ignoring it would count every group's two distinct ids instead of one. +(set W (table [k1 k2 i id] (list (% (til 240000) 300) (div (% (til 240000) 60000) 300) (til 240000) (% (div (til 240000) 60000) 2)))) +(set Wr (select {from: W where: (< i 60000) by: [k1 k2] n: (count (distinct id)) c: (count i)})) +(count Wr) -- 60000 +(sum (at Wr 'c)) -- 60000 +(sum (at Wr 'n)) -- 60000 +(sum (at (select {from: W where: (< i 120000) by: [k1 k2] n: (count (distinct id)) c: (count i)}) 'n)) -- 120000 +(sum (at (select {from: W by: [k1 k2] n: (count (distinct id)) c: (count i)}) 'n)) -- 120000 diff --git a/test/rfl/sort/sort_parted_presorted.rfl b/test/rfl/sort/sort_parted_presorted.rfl index d3d0aa6cc..06f701a25 100644 --- a/test/rfl/sort/sort_parted_presorted.rfl +++ b/test/rfl/sort/sort_parted_presorted.rfl @@ -71,13 +71,11 @@ ;; ── NOTE on the decline path ──────────────────────────────────────────────── ;; When ANY eligibility gate fails, the streaming path declines (perpart delta -;; 0) and falls through to the flat flatten+sort path. That flat path is a -;; PRE-EXISTING lazy-sort-over-parted limitation: `(select {asc:… from: PARTED})` -;; is unmaterialisable in the eager path and surfaces a LOUD `type` error rather -;; than a silently per-partition-sorted (wrong) result — the exact contract the -;; asof fallback documents (asof_clause_fallback §C: "loud error ≫ silent wrong -;; answer"). The negatives below therefore assert that an ineligible shape -;; DECLINES (delta 0) AND surfaces that loud error — never a silent bad answer. +;; 0) and the general parted sort answers instead: it sorts the key columns +;; and gathers the rows they keep from the partitions (it used to fall to the +;; flat sort, which read parted columns as plain ones and failed with `type`). +;; The negatives below therefore assert that an ineligible shape DECLINES +;; (delta 0) AND matches the same select over the materialised table. ;; ══════════════════════════════════════════════════════════════════════════ ;; NEGATIVE (a) — a partition NOT internally sorted on the key → DECLINE. @@ -90,8 +88,8 @@ (.db.splayed.set "/tmp/rfl_spu/2024.01.02/t/" U2) (set Pu (.db.parted.get "/tmp/rfl_spu/" 't)) (set Bu (at (.sys.mem) 'sort-perpart-runs)) -;; DECLINED (unsorted partition) → flat path surfaces the loud pre-existing error. -(select {Sym: Sym Time: Time Seq: Seq from: Pu asc: Time}) !- type +;; DECLINED (unsorted partition) → the general parted sort, as the flat oracle. +(select {Sym: Sym Time: Time Seq: Seq from: Pu asc: Time}) -- (select {Sym: Sym Time: Time Seq: Seq from: (select {from: Pu where: (>= Seq 0)}) asc: Time}) (set Au (at (.sys.mem) 'sort-perpart-runs)) (- Au Bu) -- 0 @@ -107,8 +105,8 @@ (.db.splayed.set "/tmp/rfl_spo/2024.01.02/t/" O2) (set Po (.db.parted.get "/tmp/rfl_spo/" 't)) (set Bo (at (.sys.mem) 'sort-perpart-runs)) -;; DECLINED (overlapping ranges) → flat path surfaces the loud pre-existing error. -(select {Sym: Sym Time: Time Seq: Seq from: Po asc: Time}) !- type +;; DECLINED (overlapping ranges) → the general parted sort, as the flat oracle. +(select {Sym: Sym Time: Time Seq: Seq from: Po asc: Time}) -- (select {Sym: Sym Time: Time Seq: Seq from: (select {from: Po where: (>= Seq 0)}) asc: Time}) (set Ao (at (.sys.mem) 'sort-perpart-runs)) (- Ao Bo) -- 0 @@ -117,10 +115,10 @@ ;; sortedness check runs in the requested (descending) direction and FAILS on ;; ascending data → DECLINE. (Documented choice: desc streams only when ;; partitions are physically stored descending; ascending-stored + desc -;; declines — no reverse/re-sort — and surfaces the loud flat-path error.) +;; declines — no reverse/re-sort — and the general parted sort answers.) ;; ══════════════════════════════════════════════════════════════════════════ (set Bd (at (.sys.mem) 'sort-perpart-runs)) -(select {Sym: Sym Time: Time Seq: Seq from: Pp desc: Time}) !- type +(select {Sym: Sym Time: Time Seq: Seq from: Pp desc: Time}) -- (select {Sym: Sym Time: Time Seq: Seq from: (select {from: Pp where: (>= Seq 0)}) desc: Time}) (set Ad (at (.sys.mem) 'sort-perpart-runs)) (- Ad Bd) -- 0 @@ -135,8 +133,8 @@ ;; path. Pp (from the single-key POSITIVE case above) is reused unchanged. ;; ══════════════════════════════════════════════════════════════════════════ (set Bg (at (.sys.mem) 'sort-perpart-runs)) -;; DECLINED (aggregate output) → flat path surfaces the same loud pre-existing -;; error as the other declines above (observed: `nyi`, not `type`). +;; DECLINED (aggregate output) → an aggregate under a sort without by: is +;; refused, as it is over a flat table (`nyi`). (select {Tot: (sum Seq) from: Pp asc: Time}) !- nyi (set Ag (at (.sys.mem) 'sort-perpart-runs)) (- Ag Bg) -- 0 diff --git a/test/rfl/sort/sort_parted_topk.rfl b/test/rfl/sort/sort_parted_topk.rfl index 856dffdb2..6812f9f4a 100644 --- a/test/rfl/sort/sort_parted_topk.rfl +++ b/test/rfl/sort/sort_parted_topk.rfl @@ -193,8 +193,8 @@ ;; ══════════════════════════════════════════════════════════════════════════ ;; REVIEW MINOR (i) — the PRE-SORTED CONCAT path (no take:) still DECLINES ;; cleanly for a 1-row partition with an UNDECIDABLE (F64) key: the base-type -;; gate rejects F64, delta 0, and the flat path surfaces the loud `type` error -;; (unmaterialisable lazy sort over parted) — never a silent wrong answer. +;; gate rejects F64, delta 0, and the general parted sort answers (it fell to +;; the flat sort, which failed with `type` on the parted columns). ;; ══════════════════════════════════════════════════════════════════════════ (.sys.exec "rm -rf /tmp/rfl_tkf") (set F1 (table [x Seq] (list (as 'F64 [1.5]) [0]))) @@ -203,7 +203,7 @@ (.db.splayed.set "/tmp/rfl_tkf/2024.01.02/t/" F2) (set Pf (.db.parted.get "/tmp/rfl_tkf/" 't)) (set BF (at (.sys.mem) 'sort-perpart-runs)) -(select {x: x Seq: Seq from: Pf asc: x}) !- type +(select {x: x Seq: Seq from: Pf asc: x}) -- (select {x: x Seq: Seq from: (select {from: Pf where: (>= Seq 0)}) asc: x}) (set AF (at (.sys.mem) 'sort-perpart-runs)) (- AF BF) -- 0 ;; …but WITH take:, the top-k path DOES handle an F64 key (broader eligibility): diff --git a/test/rfl/storage/atomic_generations.rfl b/test/rfl/storage/atomic_generations.rfl index 731eb772a..ddfe18d51 100644 --- a/test/rfl/storage/atomic_generations.rfl +++ b/test/rfl/storage/atomic_generations.rfl @@ -46,9 +46,12 @@ (.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. +;; Only the selected generation is kept, and the first write's columns are +;; gone: a table replaced three times holds one copy of itself (issue 713). (.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 "test $(find /tmp/rf_test_atomic_generations/2026.09.28/t/.generations -mindepth 1 -maxdepth 1 -type d | wc -l) -eq 1") -- 0 +(.sys.exec "test \"$(ls -A /tmp/rf_test_atomic_generations/2026.09.28/t | tr '\\n' ' ')\" = '.current .generations .write.lock '") -- 0 +(sum (at (.db.splayed.get agLeaf) 'x)) -- 31 (.sys.exec "rm -rf /tmp/rf_test_atomic_generations") -- 0 diff --git a/test/rfl/store/parted_remount.rfl b/test/rfl/store/parted_remount.rfl new file mode 100644 index 000000000..e61a728ee --- /dev/null +++ b/test/rfl/store/parted_remount.rfl @@ -0,0 +1,54 @@ +;; .db.parted.get reuses unchanged partitions across calls. +;; +;; A second mount of the same root keeps the partitions whose files did not +;; change and loads only the ones that are new or replaced; partitions that +;; disappeared are dropped. Reuse must be invisible: every remount reports +;; exactly what is on disk, and a view taken earlier keeps its own rows. + +(.sys.exec "rm -rf /tmp/rfl_parted_remount") -- 0 +(set S "/tmp/rfl_parted_remount/.sym") +(.db.splayed.set "/tmp/rfl_parted_remount/2024.01.01/t" (table [id s] (list [1 2 3] (as 'sym ["a" "b" "c"]))) S) +(.db.splayed.set "/tmp/rfl_parted_remount/2024.01.02/t" (table [id s] (list [4 5 6] (as 'sym ["d" "e" "f"]))) S) + +(set T1 (.db.parted.get "/tmp/rfl_parted_remount" 't)) +(count T1) -- 6 +(sum (get T1 'id)) -- 21 + +;; Nothing changed: the remount answers the same. +(set T1b (.db.parted.get "/tmp/rfl_parted_remount" 't)) +(count T1b) -- 6 +(sum (get T1b 'id)) -- 21 + +;; A partition replaced (a new generation) and a symbol appended. +(.db.splayed.set "/tmp/rfl_parted_remount/2024.01.02/t" (table [id s] (list [40 50 60 70] (as 'sym ["d" "e" "f" "g"]))) S) +(set T2 (.db.parted.get "/tmp/rfl_parted_remount" 't)) +(count T2) -- 7 +(sum (get T2 'id)) -- 226 +(count (select {s: s from: T2 where: (== s 'g)})) -- 1 +;; The earlier view is untouched. +(count T1) -- 6 +(sum (get T1 'id)) -- 21 + +;; A partition added. +(.db.splayed.set "/tmp/rfl_parted_remount/2024.01.03/t" (table [id s] (list [7] (as 'sym ["h"]))) S) +(set T3 (.db.parted.get "/tmp/rfl_parted_remount" 't)) +(count T3) -- 8 +(sum (get T3 'id)) -- 233 + +;; A partition removed. +(.sys.exec "rm -rf /tmp/rfl_parted_remount/2024.01.01") -- 0 +(set T4 (.db.parted.get "/tmp/rfl_parted_remount" 't)) +(count T4) -- 5 +(sum (get T4 'id)) -- 227 + +;; A column file replaced by another tool inside the same generation: the +;; per-file signature (inode, size, time) must see it. 2024.01.04 holds one +;; row like 2024.01.03, so its id file fits in place. +(.db.splayed.set "/tmp/rfl_parted_remount/2024.01.04/t" (table [id s] (list [9] (as 'sym ["h"]))) S) +(count (.db.parted.get "/tmp/rfl_parted_remount" 't)) -- 6 +(.sys.exec "cp /tmp/rfl_parted_remount/2024.01.04/t/id /tmp/rfl_parted_remount/2024.01.03/t/id") -- 0 +(set T5 (.db.parted.get "/tmp/rfl_parted_remount" 't)) +(count T5) -- 6 +(sum (get T5 'id)) -- 238 + +(.sys.exec "rm -rf /tmp/rfl_parted_remount") -- 0 diff --git a/test/rfl/store/splayed_str_pool_lifetime.rfl b/test/rfl/store/splayed_str_pool_lifetime.rfl index 223b30c7e..ca7e588f7 100644 --- a/test/rfl/store/splayed_str_pool_lifetime.rfl +++ b/test/rfl/store/splayed_str_pool_lifetime.rfl @@ -101,9 +101,24 @@ (set u (.db.splayed.get "rf_bigstr/")) (set v (take (at u 'note) 3)) (set u 0) (set v 0) (set u (.db.splayed.get "rf_bigstr/")) (set v (take (at u 'note) 3)) (set u 0) (set v 0) (set u (.db.splayed.get "rf_bigstr/")) (set v (take (at u 'note) 3)) (set u 0) (set v 0) -;; One file's worth of growth would be over a million bytes; the small -;; negative drift is the release path rounding to whole pages while the -;; map counted the file, and predates this change. -(< (- (at (.sys.mem) 'sys-mapped) _m0) 4096) -- true +;; One file's worth of growth would be over a million bytes. Map and +;; release both count whole pages, so the count comes back exactly. +(- (at (.sys.mem) 'sys-mapped) _m0) -- 0 (.sys.exec "rm -rf rf_bigstr") -- 0 + +;; ── The mapped-byte count balances for plain columns too (#786). Mapping +;; counted each file's exact length while the free re-derived it from the +;; header and rounded it to a page, so every read of a column whose file +;; is not a whole number of pages left its tail behind: a 20,000-row +;; table read 1,000 times ended millions of bytes below zero. ───────── +(.sys.exec "rm -rf rf_mapcnt") -- 0 +(.db.splayed.set "rf_mapcnt/" (table [i f s c] (list (til 20000) (as 'F64 (til 20000)) (take [x y z] 20000) (take ["ab" "cde" ""] 20000)))) +(set _m0 (at (.sys.mem) 'sys-mapped)) +(set u (.db.splayed.get "rf_mapcnt/")) +;; Held, the table is counted: the check below is not vacuous. +(> (- (at (.sys.mem) 'sys-mapped) _m0) 160000) -- true +(set u 0) +(do (set _k 0) (while (< _k 200) (set u (.db.splayed.get "rf_mapcnt/")) (set u 0) (set _k (+ _k 1)))) +(- (at (.sys.mem) 'sys-mapped) _m0) -- 0 +(.sys.exec "rm -rf rf_mapcnt") -- 0 diff --git a/test/rfl/system/objsize.rfl b/test/rfl/system/objsize.rfl index f5f3c93f1..31c40ad3a 100644 --- a/test/rfl/system/objsize.rfl +++ b/test/rfl/system/objsize.rfl @@ -13,3 +13,7 @@ ;; The allocator-maintenance builtin remains callable from Rayfall. (.sys.gc) -- 0 + +;; A closure's captured environment is part of the lambda's retained graph. +(set _objsize_k (til 64)) +(> (.mem.objsize ((fn [k] (fn [v] (+ v k))) _objsize_k)) (.mem.objsize (fn [v] (+ v 1)))) -- true diff --git a/test/rfl/table/update.rfl b/test/rfl/table/update.rfl index 4a909bc20..c5aea72ae 100644 --- a/test/rfl/table/update.rfl +++ b/test/rfl/table/update.rfl @@ -99,6 +99,41 @@ t -- (table [ID Name Value] (list [1 2] [alice bob] [10.0 20.0])) ;; Partial updates MUST include the key column(s) — otherwise the match/insert ;; logic would dereference a null-filled key and segfault. (set t (table [ID Name Value] (list [1 2] [alice bob] [10.0 20.0])))(upsert t 1 (table [Name Value] (list [charlie] [30.0]))) !- value +;; A dict row is a partial row too, exactly as the one-row table above: it +;; used to require every column and refused this with a bare `value`. A new +;; key null-fills the columns it leaves out; a matched key keeps them. +(set t (table [ID Name Value] (list [1] [alice] [10.0])))(upsert t 1 (dict [ID Value] (list 2 20.0))) -- (table [ID Name Value] (list [1 2] [alice '] [10.0 20.0])) +(set t (table [ID Name Value] (list [1 2] [alice bob] [10.0 20.0])))(upsert t 1 (dict [Value ID] (list 25.0 2))) -- (table [ID Name Value] (list [1 2] [alice bob] [10.0 25.0])) +(set t (table [ID Name Value] (list [1 2] [alice bob] [10.0 20.0])))(upsert 't 'ID (dict [ID Value] (list [2 3] [25.0 30.0])))t -- (table [ID Name Value] (list [1 2 3] [alice bob '] [10.0 25.0 30.0])) +(set t (table [k s n] (list [a b] (list "p" "qq") [1 2])))(get (upsert t 1 (dict [k n] (list 'e 50))) 's) -- ["p" "qq" ""] +;; ... and must still carry the key column(s) +(set t (table [ID Name Value] (list [1 2] [alice bob] [10.0 20.0])))(upsert t 1 (dict [Name Value] (list 'charlie 30.0))) !- value +(set t (table [ID Name Value] (list [1 2] [alice bob] [10.0 20.0])))(upsert t 2 (dict [ID Value] (list 2 30.0))) !- value +;; A left-out LIST column boxes the null object. It was a C NULL cell, +;; and reading it aborted ("value-null must be RAY_NULL_OBJ") — through a +;; one-row table or an insert dict before, and a dict upsert now too. +(set t (table [k i l] (list [a b] [1 2] (list [1 2] "w"))))(nil? (at (at (upsert t 'k (dict [k i] (list 'c 30))) 'l) 2)) -- true +(set t (table [k i l] (list [a b] [1 2] (list [1 2] "w"))))(nil? (at (at (upsert t 'k (dict [k i] (list [c e] [30 40]))) 'l) 3)) -- true +(set t (table [k i l] (list [a b] [1 2] (list [1 2] "w"))))(nil? (at (at (upsert t 'k (table [k i] (list [c] [30]))) 'l) 2)) -- true +(set t (table [k i l] (list [a b] [1 2] (list [1 2] "w"))))(upsert 't 'k (dict [k i] (list 'c 30)))(nil? (at (at t 'l) 2)) -- true +(set t (table [k i l] (list [a b] [1 2] (list [1 2] "w"))))(nil? (at (at (insert t (dict [k i] (list 'c 30))) 'l) 2)) -- true +(set t (table [k i l] (list [a b] [1 2] (list [1 2] "w"))))(insert 't (dict [k i] (list 'c 30)))(nil? (at (at t 'l) 2)) -- true +;; A mapped target checks multi-row value lengths as an in-memory one does; +;; it read past the shorter vector and appended whatever followed it. +(.sys.exec "rm -rf rf_upsert_map") -- 0 +(.db.splayed.set "rf_upsert_map/" (table [k n] (list [a b] [1 2]))) +(set m (.db.splayed.get "rf_upsert_map/")) +(get (upsert m 'k (dict [k n] (list [c d] [3 4]))) 'n) -- [1 2 3 4] +(upsert m 'k (dict [k n] (list [c d e] [3 4]))) !- length +(upsert m 'k (list [c d e] [3 4])) !- length +(upsert m 'k (list [c d] 3)) !- type +(set m 0) +(.sys.exec "rm -rf rf_upsert_map") -- 0 +;; Known bugs found alongside, not fixed here (a list column on a mapped +;; target, and saving a null list cell): +;; (.db.splayed.set "rf_upsert_ml/" (table [k n l] (list [a b] [1 2] (list [1] [2 3])))) +;; (get (upsert (.db.splayed.get "rf_upsert_ml/") 'k (list 'b 5 [9])) 'l) -- (list [1] [9]) ;; xfail BUG: a matched key on a mapped table with a LIST column errors "vec_new: type must be a positive concrete vector type, got LIST" (in memory it works) +;; (count (.db.splayed.set "rf_upsert_nl/" (table [k l] (list [a b] (list [1 2] null))))) -- 2 ;; xfail BUG: a LIST column holding a null cell cannot be saved splayed (nyi); ser/de round-trips it ;; Zero-row payloads are a no-op regardless of schema (restore pre-existing behavior ;; — rejecting an empty partial payload for missing key columns would break callers ;; that build up upserts unconditionally and may pass empty batches). diff --git a/test/test_agg_contract.c b/test/test_agg_contract.c index 134b1555e..143dc6048 100644 --- a/test/test_agg_contract.c +++ b/test/test_agg_contract.c @@ -1,6 +1,9 @@ /* Scalar/grouped semantic contracts, independent of optimized admission. * Baseline census: docs/aggregation-type-census.csv. Extend this table when * language semantics change; adding a vtable alone must not change it. */ +#if defined(__linux__) && !defined(_POSIX_C_SOURCE) +#define _POSIX_C_SOURCE 200809L /* posix_fadvise, fdatasync */ +#endif #include "test.h" #include "test_rfl.h" #include "ops/agg_engine.h" @@ -13,7 +16,9 @@ #include "ops/internal.h" #include "lang/internal.h" #include "lang/env.h" +#include "table/sym.h" #include +#include static ray_runtime_t* contract_runtime; static uint32_t contract_cores; @@ -2156,7 +2161,752 @@ static test_result_t test_first_n_take(void) { PASS(); } +#if defined(__linux__) +#include +#include +#include +#include + +/* -------------------------------------------------------------------------- + * Selects over a mapped table whose pages were evicted: the scan read-ahead + * registers the columns (select level, zone gate from the filter) and the + * grouping kernels report their rows, so every route below reads ahead. + * Results must equal the same selects over the in-memory table. + * -------------------------------------------------------------------------- */ +#define PFS_ROOT "/tmp/rayforce_test_pf_select" +#define PFS_DIR PFS_ROOT "/t/" + +static bool pfs_evict(void) { + DIR* d = opendir(PFS_DIR); + if (!d) return false; + bool ok = true; + char path[512]; + for (struct dirent* e; (e = readdir(d)); ) { + if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue; + snprintf(path, sizeof path, "%s%s", PFS_DIR, e->d_name); + int fd = open(path, O_RDONLY); + if (fd < 0) continue; + if (fdatasync(fd) != 0 || posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED) != 0) ok = false; + close(fd); + } + closedir(d); + return ok; +} + +static bool pfs_col_resident(const char* name) { + ray_t* m = ray_eval_str("pfs_m"); + if (!m || RAY_IS_ERR(m)) { if (m) ray_error_free(m); return true; } + ray_t* col = ray_table_get_col(m, ray_sym_intern(name, strlen(name))); + bool res = !col || col->mmod != 1 || + ray_vm_resident(ray_data(col), (size_t)col->len * ray_sym_elem_size(col->type, col->attrs)); + ray_release(m); + return res; +} + +static test_result_t test_select_read_ahead_mapped(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + (void)ray_test_rm_rf(PFS_ROOT); + ray_t* r = ray_eval_str( + "(set pfs_i (til 400000))" + "(set pfs_t (table [k d g u v] (list (div pfs_i 1000) (+ 2013.07.01 (div pfs_i 50000))" + " (as 'I16 (% pfs_i 50)) (% (* pfs_i 7919) 1000003) (as 'I32 (% pfs_i 977)))))" + "(.db.splayed.set \"" PFS_DIR "\" pfs_t)" + "(set pfs_m (.db.splayed.get \"" PFS_DIR "\"))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + if (!pfs_evict() || pfs_col_resident("u")) { + (void)ray_test_rm_rf(PFS_ROOT); + SKIP("page cache eviction has no effect here"); + } + + /* X is the table: the mapped one first, then the in-memory oracle. */ + static const struct { const char* q; agg_route_t route; } cases[] = { + { "(select {from:X by:g c:(count v) s:(sum v) where:(and (== k 123) (within d [2013.07.03 2013.07.05])) asc:g})", AGG_ROUTE_NONE }, + { "(select {from:X c:(count v) s:(sum u) where:(> k 390)})", AGG_ROUTE_NONE }, + { "(select {from:X by:g s:(sum v) asc:g})", AGG_ROUTE_V2_DENSE }, + { "(select {from:(select {from:X by:u c:(count v)}) n:(count c) s:(sum c)})", AGG_ROUTE_V2_RADIX }, + { "(select {from:X by:g n:(count (distinct u)) asc:g})", AGG_ROUTE_NONE }, + { "(select {from:X by:[u g] c:(count v) take:3})", AGG_ROUTE_NONE }, + { "(select {from:X s:(sum (+ u v)) where:(> v 5)})", AGG_ROUTE_NONE }, + { "(select {from:X where:(> v 970) asc:u take:5})", AGG_ROUTE_NONE }, + }; + for (size_t c = 0; c < sizeof(cases) / sizeof(cases[0]); c++) { + char qm[512], qt[512]; + const char* x = strstr(cases[c].q, "X"); + snprintf(qm, sizeof qm, "%.*spfs_m%s", (int)(x - cases[c].q), cases[c].q, x + 1); + snprintf(qt, sizeof qt, "%.*spfs_t%s", (int)(x - cases[c].q), cases[c].q, x + 1); + TEST_ASSERT_TRUE(pfs_evict()); + agg_route_reset(); + ray_t* got = ray_eval_str(qm); + agg_route_stats_t stats = agg_route_stats(); + ray_t* want = ray_eval_str(qt); + bool ok = got && !RAY_IS_ERR(got) && want && !RAY_IS_ERR(want); + if (ok) { + ray_t* fg = ray_fmt(got, 0); + ray_t* fw = ray_fmt(want, 0); + ok = fg && fw && ray_str_len(fg) == ray_str_len(fw) && + memcmp(ray_str_ptr(fg), ray_str_ptr(fw), ray_str_len(fw)) == 0; + if (fg) ray_release(fg); + if (fw) ray_release(fw); + } + if (got) { if (RAY_IS_ERR(got)) ray_error_free(got); else ray_release(got); } + if (want) { if (RAY_IS_ERR(want)) ray_error_free(want); else ray_release(want); } + TEST_ASSERT_FMT(ok, "case %zu: mapped result differs from the in-memory one", c); + if (cases[c].route != AGG_ROUTE_NONE) + TEST_ASSERT_FMT(stats.routes[cases[c].route] >= 1, + "case %zu: expected route %d", c, (int)cases[c].route); + } + r = ray_eval_str("(set pfs_m 0)"); + if (r) ray_release(r); + (void)ray_test_rm_rf(PFS_ROOT); + PASS(); +} + +/* A filter the zone indexes say nothing about (an expression) may keep a + * handful of rows. The columns read only after it are then requested for + * the pages those rows fall on, not whole — judged on the final selection + * of an `and`, not its first conjunct; when it keeps most rows they are + * read whole. Results match the in-memory table either way. */ +static test_result_t test_select_read_ahead_sparse_filter(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + (void)ray_test_rm_rf(PFS_ROOT); + ray_t* r = ray_eval_str( + "(set pfs_i (til 400000))" + "(set pfs_t (table [u w s] (list (% (* pfs_i 7919) 1000003) (* pfs_i 3)" + " (as 'SYM (map (fn [k] (format \"s%\" (% k 10000))) pfs_i)))))" + "(.db.splayed.set \"" PFS_DIR "\" pfs_t)" + "(set pfs_m (.db.splayed.get \"" PFS_DIR "\"))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + if (!pfs_evict() || pfs_col_resident("w")) { + (void)ray_test_rm_rf(PFS_ROOT); + SKIP("page cache eviction has no effect here"); + } + static const struct { const char* q; bool whole; } cases[] = { + { "(select {from:X s:(sum w) c:(count w) where:(== (% u 100000) 42)})", false }, + /* an `and` runs as a chain of filters, the cheap dense one first */ + { "(select {from:X s:(sum w) c:(count w) where:(and (like s \"s1234\") (!= s \"s1\"))})", false }, + { "(select {from:X s:(sum w) c:(count w) where:(> (% u 10) 2)})", true }, + }; + for (size_t c = 0; c < sizeof(cases) / sizeof(cases[0]); c++) { + char qm[256], qt[256]; + const char* x = strstr(cases[c].q, "X"); + snprintf(qm, sizeof qm, "%.*spfs_m%s", (int)(x - cases[c].q), cases[c].q, x + 1); + snprintf(qt, sizeof qt, "%.*spfs_t%s", (int)(x - cases[c].q), cases[c].q, x + 1); + TEST_ASSERT_TRUE(pfs_evict()); + ray_t* got = ray_eval_str(qm); + bool resident = pfs_col_resident("w"); + ray_t* want = ray_eval_str(qt); + bool ok = got && !RAY_IS_ERR(got) && want && !RAY_IS_ERR(want); + if (ok) { + ray_t* fg = ray_fmt(got, 0); + ray_t* fw = ray_fmt(want, 0); + ok = fg && fw && ray_str_len(fg) == ray_str_len(fw) && + memcmp(ray_str_ptr(fg), ray_str_ptr(fw), ray_str_len(fw)) == 0; + if (fg) ray_release(fg); + if (fw) ray_release(fw); + } + if (got) { if (RAY_IS_ERR(got)) ray_error_free(got); else ray_release(got); } + if (want) { if (RAY_IS_ERR(want)) ray_error_free(want); else ray_release(want); } + TEST_ASSERT_FMT(ok, "case %zu: mapped result differs from the in-memory one", c); + TEST_ASSERT_FMT(resident == cases[c].whole, + "case %zu: column w %s after the query", c, + resident ? "read whole" : "not read whole"); + } + r = ray_eval_str("(set pfs_m 0)"); + if (r) ray_release(r); + (void)ray_test_rm_rf(PFS_ROOT); + PASS(); +} + +/* The route gate of a distinct count (#760) samples before the select + * runs: the rows a where: keeps (query_cd_gate_where_rows), the key and + * value columns at them (agg_group_card_sample), and a key column whole + * when the sample leaves its count open (ray_cd_two_pass_preferred). Over + * a mapped table whose pages were evicted each page read is asked for + * ahead, in parallel, as the select's own scan asks for its — the bytes + * asked for (ray_vm_willneed_bytes) cover what the step reads, and its + * major faults stay near zero where a fault per page read would be + * thousands. (The faults alone would not tell: the kernel's own + * read-ahead follows a sweep of pages in order, and most of its faults + * are then minor.) A step's columns are its own: pages a step faulted in + * stay mapped and cannot be evicted for the next. */ +static long cd_major_faults(void) { + struct rusage u; + getrusage(RUSAGE_SELF, &u); + return u.ru_majflt; +} + +static test_result_t test_cd_gate_read_ahead(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + (void)ray_test_rm_rf(PFS_ROOT); + enum { FAULTS_MAX = 64 }; + + /* w: 16 MB (4,096 pages); k, x, t: 32 MB each; t is the row number, + * sorted, with the chunk-zone index a splayed column carries */ + enum { N = 4194304 }; + ray_t* r = ray_eval_str( + "(set pfs_i (til 4194304))" + "(set pfs_t (table [w k x t] (list (as 'I32 (% pfs_i 977)) (% pfs_i 1000)" + " (% (* pfs_i 7919) 2000003) pfs_i)))" + "(.db.splayed.set \"" PFS_DIR "\" pfs_t)" + "(set pfs_m (.db.splayed.get \"" PFS_DIR "\"))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + if (!pfs_evict() || pfs_col_resident("w")) { + (void)ray_test_rm_rf(PFS_ROOT); + SKIP("page cache eviction has no effect here"); + } + ray_t* m = ray_eval_str("pfs_m"); + ray_t* pred = ray_eval_str("(quote (< w 100))"); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m) && pred && !RAY_IS_ERR(pred)); + ray_t* k = ray_table_get_col(m, ray_sym_intern("k", 1)); + ray_t* x = ray_table_get_col(m, ray_sym_intern("x", 1)); + TEST_ASSERT_TRUE(k && x && k->mmod == 1 && x->mmod == 1); + + /* the where: sample — 262,144 rows of w, 64 to a page: every page */ + const int64_t* rows = NULL; + int64_t nrows = 0, pop = 0; + long f0 = cd_major_faults(); + uint64_t b0 = ray_vm_willneed_bytes(); + ray_t* hdr = query_cd_gate_where_rows(m, pred, N, &rows, &nrows, &pop); + long f_where = cd_major_faults() - f0; + uint64_t b_where = ray_vm_willneed_bytes() - b0; + TEST_ASSERT_NOT_NULL(hdr); + TEST_ASSERT_FMT(nrows > 24000 && nrows < 30000, "where sample keeps %lld of 262,144", (long long)nrows); + TEST_ASSERT_FMT(b_where >= (uint64_t)N * 4, "where sample asked for %llu bytes, w is %llu", + (unsigned long long)b_where, (unsigned long long)N * 4); + TEST_ASSERT_FMT(f_where <= FAULTS_MAX, "where sample: %ld major faults", f_where); + + /* a slice of the sorted column: the zone gate rules out every chunk + * but the two (64 K rows each) the window falls in, so the sample is + * their rows — every survivor, the population exact — and reads a + * sixteenth of t at most, not the column */ + ray_t* pred_t = ray_eval_str("(quote (and (>= t 2000000) (< t 2040000)))"); + TEST_ASSERT_TRUE(pred_t && !RAY_IS_ERR(pred_t) && !pfs_col_resident("t")); + const int64_t* rows_t = NULL; + int64_t nrows_t = 0, pop_t = 0; + f0 = cd_major_faults(); + b0 = ray_vm_willneed_bytes(); + ray_t* hdr_t = query_cd_gate_where_rows(m, pred_t, N, &rows_t, &nrows_t, &pop_t); + long f_slice = cd_major_faults() - f0; + uint64_t b_slice = ray_vm_willneed_bytes() - b0; + TEST_ASSERT_NOT_NULL(hdr_t); + TEST_ASSERT_FMT(nrows_t == 40000 && pop_t == 40000, "slice sample keeps %lld for %lld", + (long long)nrows_t, (long long)pop_t); + TEST_ASSERT_FMT(b_slice >= (uint64_t)40000 * 8 && b_slice <= (uint64_t)N * 8 / 16, + "slice sample asked for %llu bytes of t's %llu", (unsigned long long)b_slice, + (unsigned long long)N * 8); + TEST_ASSERT_FMT(f_slice <= FAULTS_MAX, "slice sample: %ld major faults", f_slice); + scratch_free(hdr_t); + ray_release(pred_t); + + /* the estimate over a contiguous slice, 1% of the rows: the span the + * sampled rows cover is asked for — a row per page and more there — + * not the columns whole */ + TEST_ASSERT_TRUE(!pfs_col_resident("k") && !pfs_col_resident("x")); + ray_t* cols[2] = { k, x }; + int64_t est[2], kp = 0, kmax = 0, ka = 0; + enum { SLICE = N / 100 }; + int64_t* slice = malloc((size_t)SLICE * sizeof(int64_t)); + TEST_ASSERT_NOT_NULL(slice); + for (int64_t i = 0; i < SLICE; i++) slice[i] = N / 2 + i; + b0 = ray_vm_willneed_bytes(); + TEST_ASSERT_TRUE(agg_group_card_sample(cols, 2, 1, slice, SLICE, 0, est, &kp, &kmax, &ka)); + uint64_t b_span = ray_vm_willneed_bytes() - b0; + free(slice); + /* the span runs from the first sampled row to the last, a window short */ + TEST_ASSERT_FMT(b_span >= (uint64_t)SLICE * 16 * 9 / 10 && b_span <= (uint64_t)SLICE * 16 * 4, + "slice estimate asked for %llu bytes, the slice of k and x is %llu", + (unsigned long long)b_span, (unsigned long long)SLICE * 16); + + /* the estimate over the survivors: a tenth of the rows, 50 to a page + * of k and x — the columns are asked for whole */ + f0 = cd_major_faults(); + b0 = ray_vm_willneed_bytes(); + TEST_ASSERT_TRUE(agg_group_card_sample(cols, 2, 1, rows, nrows, pop, est, &kp, &kmax, &ka)); + long f_est = cd_major_faults() - f0; + uint64_t b_est = ray_vm_willneed_bytes() - b0; + scratch_free(hdr); + TEST_ASSERT_FMT(est[0] >= 900 && est[0] <= 1100, "k estimate %lld", (long long)est[0]); + /* the span from the first sampled row to the last: the columns but a few rows */ + TEST_ASSERT_FMT(b_est >= (uint64_t)N * 16 * 15 / 16, "estimate asked for %llu bytes, k and x are %llu", + (unsigned long long)b_est, (unsigned long long)N * 16); + TEST_ASSERT_FMT(f_est <= FAULTS_MAX, "estimate: %ld major faults", f_est); + ray_release(pred); + ray_release(m); + r = ray_eval_str("(set pfs_m 0)"); + if (r) ray_release(r); + (void)ray_test_rm_rf(PFS_ROOT); + + /* The gate over a selection sparser than a row per page: the pages of + * the sampled rows alone are asked for. k3 (272 MB, 66,406 pages; a + * million values) over 33,000 rows, one to every other page: 32,768 + * of them are sampled, read as distinct, and the estimate stands at + * the span, a million — past the sample's reach and short of the + * many-groups mark — so the count is confirmed in full, over the half + * of the column the estimate never touched. */ + enum { N3 = 34000000, SEL3 = 33000 }; + r = ray_eval_str( + "(set pfs_j (til 34000000))" + "(set pfs_t (table [k3 x3] (list (% (* pfs_j 7919) 1000000) (as 'U8 (% pfs_j 200)))))" + "(set pfs_j 0)" + "(.db.splayed.set \"" PFS_DIR "\" pfs_t)" + "(set pfs_t 0)" + "(set pfs_m (.db.splayed.get \"" PFS_DIR "\"))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + TEST_ASSERT_TRUE(pfs_evict() && !pfs_col_resident("k3")); + m = ray_eval_str("pfs_m"); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + ray_t* k3 = ray_table_get_col(m, ray_sym_intern("k3", 2)); + ray_t* x3 = ray_table_get_col(m, ray_sym_intern("x3", 2)); + TEST_ASSERT_TRUE(k3 && x3 && k3->mmod == 1 && (size_t)k3->len * 8 / 4096 > (size_t)SEL3); + int64_t* sel = malloc((size_t)SEL3 * sizeof(int64_t)); + TEST_ASSERT_NOT_NULL(sel); + for (int64_t i = 0; i < SEL3; i++) sel[i] = i * 1030; + f0 = cd_major_faults(); + b0 = ray_vm_willneed_bytes(); + bool two_pass = ray_cd_two_pass_preferred(&k3, 1, x3, sel, SEL3, 0, 4); + long f_gate = cd_major_faults() - f0; + uint64_t b_gate = ray_vm_willneed_bytes() - b0; + free(sel); + TEST_ASSERT_FALSE(two_pass); /* a million groups counted, not many: the slices */ + /* the sampled rows' pages of k3 (one each) for the estimate, and k3 + * whole for the count; x3 besides */ + const uint64_t b_need = (uint64_t)N3 * 8 + (uint64_t)SEL3 * 4096; + TEST_ASSERT_FMT(b_gate >= b_need, "gate asked for %llu bytes, needs %llu", + (unsigned long long)b_gate, (unsigned long long)b_need); + TEST_ASSERT_FMT(f_gate <= FAULTS_MAX, "gate: %ld major faults", f_gate); + + ray_release(m); + r = ray_eval_str("(set pfs_m 0)"); + if (r) ray_release(r); + (void)ray_test_rm_rf(PFS_ROOT); + PASS(); +} +#endif + +/* The planner's sampled cardinality estimates (agg_group_card_sample, + * agg_group_card_estimate; #760). 1,048,576 rows are sampled one row per + * window of 32, so a value filling one such window is a sampled singleton. */ +static test_result_t test_card_estimate(void) { + const int64_t N = 1048576; + ray_t* setup = ray_eval_str("(set cr (til 1048576))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); + ray_release(setup); + ray_t* c[3]; + int64_t est[3], kp = 0, ka = 0; + + /* every row distinct: the sample holds singletons only; the Chao1 + * correction raises its count (the sample size without it) past the + * span, which caps the estimate at the rows */ + c[0] = ray_eval_str("cr"); + { + int64_t all = agg_group_card_estimate(c, 1, N); /* the sampled span: a window short of N at each end */ + TEST_ASSERT_FMT(all >= N - 64 && all <= N, "every row distinct: %lld", (long long)all); + } + ray_release(c[0]); + + /* 45 values: no singletons, the count itself */ + c[0] = ray_eval_str("(% cr 45)"); + TEST_ASSERT_EQ_I(agg_group_card_estimate(c, 1, N), 45); + ray_release(c[0]); + + /* 1,000 values on one window of 32 rows each and one value elsewhere: + * Chao1 reads the 1,000 sampled singletons as half a million values; + * the span caps an integer key at the 1,001 it can hold, the domain's + * count a SYM key (the process-wide domain here, so at least 1,001 and + * far below the half million) */ + c[0] = ray_eval_str("(* (< cr 32000) (+ 1 (div cr 32)))"); + TEST_ASSERT_EQ_I(agg_group_card_estimate(c, 1, N), 1001); + /* the same key as a tuple beside a 2-value column: 2,002 tuples, which + * the tuple's Chao1 overstates as the key's was and the product of the + * two spans caps */ + c[1] = c[0]; + c[0] = ray_eval_str("(% cr 2)"); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 2, 2, NULL, N, 0, est, &kp, NULL, &ka)); + TEST_ASSERT_EQ_I(est[0], 2); + TEST_ASSERT_EQ_I(est[1], 1001); + TEST_ASSERT_EQ_I(kp, 2002); + TEST_ASSERT_EQ_I(ka, 2002); + ray_release(c[0]); ray_release(c[1]); + /* the same key as symbols new to the process, so their codes are + * contiguous: the span of the sampled codes caps it at the 1,001 as + * well, and a symbol interned afterwards (the domain is process-wide) + * leaves the estimate where it was */ + c[0] = ray_eval_str("(as 'SYM (+ 9000000 (* (< cr 32000) (+ 1 (div cr 32)))))"); + TEST_ASSERT_EQ_I(agg_group_card_estimate(c, 1, N), 1001); + { + int64_t dom = ray_sym_domain_count(ray_sym_vec_domain(c[0])); + ray_t* later = ray_eval_str("'interned_after_the_key_column"); + ray_release(later); + TEST_ASSERT_TRUE(ray_sym_domain_count(ray_sym_vec_domain(c[0])) > dom); + } + TEST_ASSERT_EQ_I(agg_group_card_estimate(c, 1, N), 1001); + ray_release(c[0]); + + /* keys that repeat with the row number: a period equal to the stride, + * which a fixed offset would read as one value */ + c[0] = ray_eval_str("(% cr 32)"); + TEST_ASSERT_EQ_I(agg_group_card_estimate(c, 1, N), 32); + ray_release(c[0]); + /* composites of periods 1,000 and 1,009 or 1,013 over 10 M rows, one + * row sampled per window of 305: 1,009,000 or 1,013,000 groups, each + * on ten rows, and beside a 50-value X (which 1,000 absorbs) as many + * (key, value) tuples as groups. An offset nearly linear in the window + * index keeps the sampled rows a progression and these keys at a nearly + * fixed phase: the first pair's tuples with X read as ten million (no + * tuple seen twice, the Chao1 at the cap), the second pair's groups as + * a tenth of them (too many seen twice). The hashed offset's + * collisions are a random sample's, and the Chao1 lands within a fifth + * of the count. */ + setup = ray_eval_str("(set c10 (til 10000000))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); + ray_release(setup); + c[0] = ray_eval_str("(% c10 1000)"); + c[1] = ray_eval_str("(% c10 1009)"); + c[2] = ray_eval_str("(% c10 50)"); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 3, 2, NULL, 10000000, 0, est, &kp, NULL, &ka)); + TEST_ASSERT_EQ_I(est[0], 1000); + TEST_ASSERT_EQ_I(est[1], 1009); + TEST_ASSERT_EQ_I(est[2], 50); + TEST_ASSERT_FMT(kp >= 800000 && kp <= 1009000, "1,000 x 1,009 groups: %lld", (long long)kp); + TEST_ASSERT_FMT(ka >= 800000 && ka <= 1250000, "1,000 x 1,009 x 50 tuples: %lld", (long long)ka); + ray_release(c[1]); + c[1] = ray_eval_str("(% c10 1013)"); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 3, 2, NULL, 10000000, 0, est, &kp, NULL, &ka)); + TEST_ASSERT_EQ_I(est[1], 1013); + TEST_ASSERT_FMT(kp >= 800000 && kp <= 1013000, "1,000 x 1,013 groups: %lld", (long long)kp); + TEST_ASSERT_FMT(ka >= 800000 && ka <= 1250000, "1,000 x 1,013 x 50 tuples: %lld", (long long)ka); + ray_release(c[0]); ray_release(c[1]); ray_release(c[2]); + /* a key that is a progression in the row number — (i x 7919) mod N, a + * permutation of the rows — is all distinct, and reads so */ + c[0] = ray_eval_str("(% (* cr 7919) 1048576)"); + { + int64_t all = agg_group_card_estimate(c, 1, N); + TEST_ASSERT_FMT(all >= 900000 && all <= N, "a permutation of the rows: %lld", (long long)all); + } + ray_release(c[0]); + + /* a composite whose first column follows from the second: the product + * of the columns says 1,024 groups, the tuple 256 */ + c[0] = ray_eval_str("(div (% (div cr 4096) 256) 64)"); + c[1] = ray_eval_str("(% (div cr 4096) 256)"); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 2, 2, NULL, N, 0, est, &kp, NULL, &ka)); + TEST_ASSERT_EQ_I(est[0], 4); + TEST_ASSERT_EQ_I(est[1], 256); + TEST_ASSERT_EQ_I(agg_group_card_estimate(c, 2, N), 1024); + TEST_ASSERT_EQ_I(kp, 256); + TEST_ASSERT_EQ_I(ka, 256); + ray_release(c[0]); ray_release(c[1]); + + /* a sorted composite in runs of 8 rows, below the stride: the stride + * sees every sample distinct and its Chao1 saturates at the rows; the + * blocks of adjacent rows read the runs — 131,072 groups — and, with a + * value alternating within each run, 262,144 (key, value) tuples */ + c[0] = ray_eval_str("(div cr 8192)"); + c[1] = ray_eval_str("(div cr 8)"); + c[2] = ray_eval_str("(% cr 2)"); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 3, 2, NULL, N, 0, est, &kp, NULL, &ka)); + TEST_ASSERT_FMT(est[1] >= 131070 && est[1] <= 131072, "runs of 8: span %lld", (long long)est[1]); + TEST_ASSERT_FMT(kp >= 120000 && kp <= 145000, "sorted prefix: %lld groups", (long long)kp); + TEST_ASSERT_FMT(ka >= 240000 && ka <= 290000, "sorted prefix: %lld tuples", (long long)ka); + /* 32 sorted groups of 32,768 rows: the stride is exact, and the blocks + * (one run each) do not override it */ + ray_release(c[0]); + c[0] = ray_eval_str("(div cr 32768)"); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 2, 1, NULL, N, 0, est, &kp, NULL, NULL)); + TEST_ASSERT_EQ_I(est[0], 32); + TEST_ASSERT_EQ_I(kp, 32); + ray_release(c[0]); ray_release(c[1]); ray_release(c[2]); + + /* the largest group's rows: 45 equal groups, and a key whose first + * value holds half the rows (2000 / (1 + j), j cycling through 2000) */ + int64_t kmax = 0; + c[0] = ray_eval_str("(% cr 45)"); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 1, 1, NULL, N, 0, est, &kp, &kmax, NULL)); + TEST_ASSERT_FMT(kmax >= N / 45 - N / 450 && kmax <= N / 45 + N / 450, + "45 equal groups: the largest holds %lld rows", (long long)kmax); + ray_release(c[0]); + c[0] = ray_eval_str("(div 2000 (+ 1 (% cr 2000)))"); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 1, 1, NULL, N, 0, est, &kp, &kmax, NULL)); + TEST_ASSERT_FMT(kmax >= N / 2 - N / 40 && kmax <= N / 2 + N / 40, + "a value on half the rows: the largest group holds %lld rows", (long long)kmax); + ray_release(c[0]); + + /* a selection's rows: a key that is 0 on 88 rows in 100 and one of + * 1,000 values on the rest. Over the table the zero is the + * largest group by far; over the rows a `where:` keeps, the 1,000 + * groups are equal and the Chao1 sees them exactly. */ + c[0] = ray_eval_str("(* (>= (% cr 100) 88) (+ 1 (% (div cr 100) 1000)))"); + { + const int64_t* kd = (const int64_t*)ray_data(c[0]); + int64_t* sel = malloc((size_t)N * sizeof(int64_t)); + TEST_ASSERT_NOT_NULL(sel); + int64_t nsel = 0; + for (int64_t i = 0; i < N; i++) if (kd[i] != 0) sel[nsel++] = i; + TEST_ASSERT_TRUE(nsel > N / 10 && nsel < N / 8); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 1, 1, NULL, N, 0, est, &kp, &kmax, NULL)); + TEST_ASSERT_FMT(kmax > N * 4 / 5, "over the table: the zero holds %lld rows", (long long)kmax); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 1, 1, sel, nsel, 0, est, &kp, &kmax, NULL)); + TEST_ASSERT_EQ_I(est[0], 1000); + TEST_ASSERT_EQ_I(kp, 1000); + TEST_ASSERT_FMT(kmax < nsel / 500, "over the selection: the largest group holds %lld of %lld rows", + (long long)kmax, (long long)nsel); + free(sel); + } + ray_release(c[0]); + + /* a list sampled from a larger population: 2,048 rows of `cr`, one per + * 512, describe the million rows they were drawn from — every one a + * singleton, and the Chao1 reaches for the population's span — and + * only themselves without the population */ + { + int64_t* sel = malloc(2048 * sizeof(int64_t)); + TEST_ASSERT_NOT_NULL(sel); + for (int64_t i = 0; i < 2048; i++) sel[i] = i * 512; + c[0] = ray_eval_str("cr"); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 1, 1, sel, 2048, N, est, NULL, NULL, NULL)); + TEST_ASSERT_FMT(est[0] > N / 2 && est[0] <= N, "2,048 of a million rows: %lld", (long long)est[0]); + TEST_ASSERT_TRUE(agg_group_card_sample(c, 1, 1, sel, 2048, 0, est, NULL, NULL, NULL)); + TEST_ASSERT_EQ_I(est[0], 2048); + ray_release(c[0]); + free(sel); + } + + /* a key type the estimate does not cover */ + c[0] = ray_eval_str("(as 'F64 cr)"); + TEST_ASSERT_FALSE(agg_group_card_sample(c, 1, 1, NULL, N, 0, est, NULL, NULL, NULL)); + TEST_ASSERT_EQ_I(agg_group_card_estimate(c, 1, N), -1); + ray_release(c[0]); + PASS(); +} + +/* The route gate for a grouped distinct count (ray_cd_two_pass_preferred, + * #756): the two-pass rewrite (true) against the slice dedup (false), from + * the estimates above over 1,048,576 rows. Each case turns on one rule. */ +static test_result_t test_cd_route(void) { + const int64_t N = 1048576; + ray_t* setup = ray_eval_str("(set cr (til 1048576))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); + ray_release(setup); + ray_t* k[2]; + ray_t* x; + + /* dense: 45 groups x 100 values pack within the rows */ + k[0] = ray_eval_str("(% cr 45)"); + x = ray_eval_str("(% cr 100)"); + TEST_ASSERT_TRUE(ray_cd_two_pass_preferred(k, 1, x, NULL, N, 0, 28)); + ray_release(x); + /* 45 groups x a million values: the (K, X) pass would be radix */ + x = ray_eval_str("cr"); + TEST_ASSERT_FALSE(ray_cd_two_pass_preferred(k, 1, x, NULL, N, 0, 28)); + ray_release(k[0]); ray_release(x); + + /* 100,000 groups, below the scatter's 256 K: the slices, though the + * (K, X) tuples (X determines K) would dedup to a fifth of the rows */ + k[0] = ray_eval_str("(% cr 100000)"); + x = ray_eval_str("(% cr 200000)"); + TEST_ASSERT_FALSE(ray_cd_two_pass_preferred(k, 1, x, NULL, N, 0, 28)); + ray_release(k[0]); ray_release(x); + + /* 524,288 groups of 19 rows over 10 M rows, within the band: the + * tuples decide — a twentieth of the rows (K determines X) take the + * rewrite, every row distinct the slices */ + setup = ray_eval_str("(set c10 (til 10000000))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); + ray_release(setup); + k[0] = ray_eval_str("(% c10 524288)"); + x = ray_eval_str("(% c10 262144)"); + TEST_ASSERT_TRUE(ray_cd_two_pass_preferred(k, 1, x, NULL, 10000000, 0, 28)); + ray_release(x); + x = ray_eval_str("c10"); + TEST_ASSERT_FALSE(ray_cd_two_pass_preferred(k, 1, x, NULL, 10000000, 0, 28)); + ray_release(k[0]); ray_release(x); + /* the same two over a sorted key, read through the blocks */ + k[0] = ray_eval_str("(div c10 19)"); + x = ray_eval_str("(div c10 38)"); + TEST_ASSERT_TRUE(ray_cd_two_pass_preferred(k, 1, x, NULL, 10000000, 0, 28)); + ray_release(x); + x = ray_eval_str("c10"); + TEST_ASSERT_FALSE(ray_cd_two_pass_preferred(k, 1, x, NULL, 10000000, 0, 28)); + ray_release(k[0]); ray_release(x); + /* a composite of periods 1,000 and 1,009 — 1,009,000 groups, within + * the band, whose tuples beside a 50-value X are the groups: the + * rewrite (the usual test data, which a sample at a fixed phase of the + * keys misread; see test_card_estimate) */ + k[0] = ray_eval_str("(% c10 1000)"); + k[1] = ray_eval_str("(% c10 1009)"); + x = ray_eval_str("(% c10 50)"); + TEST_ASSERT_TRUE(ray_cd_two_pass_preferred(k, 2, x, NULL, 10000000, 0, 28)); + ray_release(k[0]); ray_release(k[1]); ray_release(x); + + /* past a million groups: the rewrite whatever the tuples */ + setup = ray_eval_str("(set c2 (til 2097152))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); + ray_release(setup); + k[0] = ray_eval_str("c2"); + x = ray_eval_str("(% c2 2)"); + TEST_ASSERT_TRUE(ray_cd_two_pass_preferred(k, 1, x, NULL, 2 * N, 0, 28)); + ray_release(k[0]); ray_release(x); + + /* a dominant group: a key whose first value holds half the rows beside + * a million-value X takes the rewrite on 28 workers (the slice dedup + * would run that group on one), the slices on 2 (no parallel edge to + * lose); 2,000 equal groups take the slices */ + k[0] = ray_eval_str("(div 2000 (+ 1 (% cr 2000)))"); + x = ray_eval_str("cr"); + TEST_ASSERT_TRUE(ray_cd_two_pass_preferred(k, 1, x, NULL, N, 0, 28)); + TEST_ASSERT_FALSE(ray_cd_two_pass_preferred(k, 1, x, NULL, N, 0, 2)); + ray_release(k[0]); + k[0] = ray_eval_str("(% cr 2000)"); + TEST_ASSERT_FALSE(ray_cd_two_pass_preferred(k, 1, x, NULL, N, 0, 28)); + ray_release(k[0]); + /* the same key behind a `where:` that drops its dominant value: over + * the table the zero on 88 rows in 100 reads as a dominant group and + * takes the rewrite; over the rows the selection keeps, 1,000 equal + * groups take the slices */ + k[0] = ray_eval_str("(* (>= (% cr 100) 88) (+ 1 (% (div cr 100) 1000)))"); + TEST_ASSERT_TRUE(ray_cd_two_pass_preferred(k, 1, x, NULL, N, 0, 28)); + { + const int64_t* kd = (const int64_t*)ray_data(k[0]); + int64_t* sel = malloc((size_t)N * sizeof(int64_t)); + TEST_ASSERT_NOT_NULL(sel); + int64_t nsel = 0; + for (int64_t i = 0; i < N; i++) if (kd[i] != 0) sel[nsel++] = i; + TEST_ASSERT_FALSE(ray_cd_two_pass_preferred(k, 1, x, sel, nsel, 0, 28)); + free(sel); + } + ray_release(k[0]); ray_release(x); + + /* a heavy-tailed key: a value of its own on every even row (five + * million values) and one of 50,000 values, each on 100 rows, on the + * odd ones. The sample reads the even rows as singletons and the odd + * ones as the repeats of the whole tail, and its Chao1 lands around + * 100,000 — under the 256 K floor; the full approximate count says + * five million, and the rewrite is the route */ + k[0] = ray_eval_str("(+ (* (== (% c10 2) 0) (+ 20000000 c10)) (* (== (% c10 2) 1) (% (div c10 2) 50000)))"); + x = ray_eval_str("c10"); + { + int64_t kc = 0; + TEST_ASSERT_TRUE(agg_group_card_sample(k, 1, 1, NULL, 10000000, 0, NULL, &kc, NULL, NULL)); + TEST_ASSERT_FMT(kc > 32768 && kc < 1000000, "a heavy tail reads as %lld groups", (long long)kc); + } + TEST_ASSERT_TRUE(ray_cd_two_pass_preferred(k, 1, x, NULL, 10000000, 0, 28)); + ray_release(k[0]); ray_release(x); + + /* the rows a `where:` keeps, sampled (query_cd_gate_where_rows): the + * key above as a table column behind `(!= k 0)`. Of 262,144 sampled + * rows, 12 in 100 survive, every survivor has a nonzero key, and the + * population scales to the table's 12%; the gate over them takes the + * slices (1,000 equal groups), over the whole table the rewrite (the + * zero's share). A predicate keeping every row samples nothing. */ + setup = ray_eval_str("(set Tw (table [k x] (list (* (>= (% cr 100) 88) (+ 1 (% (div cr 100) 1000))) cr)))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); + ray_release(setup); + { + ray_t* tw = ray_eval_str("Tw"); + ray_t* w = ray_eval_str("(quote (!= k 0))"); + ray_t* kc = ray_eval_str("(at Tw 'k)"); + ray_t* xc = ray_eval_str("(at Tw 'x)"); + TEST_ASSERT_NOT_NULL(tw); TEST_ASSERT_NOT_NULL(w); TEST_ASSERT_NOT_NULL(kc); TEST_ASSERT_NOT_NULL(xc); + const int64_t* rows = NULL; + int64_t nrows = 0, pop = 0; + ray_t* hdr = query_cd_gate_where_rows(tw, w, N, &rows, &nrows, &pop); + TEST_ASSERT_NOT_NULL(hdr); + TEST_ASSERT_FMT(nrows > 262144 / 10 && nrows < 262144 / 7, "sampled survivors: %lld", (long long)nrows); + TEST_ASSERT_FMT(pop > N / 10 && pop < N / 7, "scaled population: %lld", (long long)pop); + const int64_t* kd = (const int64_t*)ray_data(kc); + int64_t zeros = 0; + for (int64_t j = 0; j < nrows; j++) if (kd[rows[j]] == 0) zeros++; + TEST_ASSERT_EQ_I(zeros, 0); + k[0] = kc; + TEST_ASSERT_FALSE(ray_cd_two_pass_preferred(k, 1, xc, rows, nrows, pop, 28)); + TEST_ASSERT_TRUE(ray_cd_two_pass_preferred(k, 1, xc, NULL, N, 0, 28)); + scratch_free(hdr); + ray_release(w); + w = ray_eval_str("(quote (>= k 0))"); + TEST_ASSERT_NULL(query_cd_gate_where_rows(tw, w, N, &rows, &nrows, &pop)); + TEST_ASSERT_EQ_I(nrows, N); + /* the sampled table and its filter leave nothing behind: eight + * rounds hold no more memory than none */ + ray_release(w); + w = ray_eval_str("(quote (!= k 0))"); + { + ray_mem_trace_t mt; + TEST_ASSERT_TRUE(ray_mem_trace_begin()); + for (int round = 0; round < 8; round++) { + ray_t* h = query_cd_gate_where_rows(tw, w, N, &rows, &nrows, &pop); + if (h) scratch_free(h); + } + ray_mem_trace_end(&mt); + TEST_ASSERT_FMT(mt.net_bytes < (1 << 20), "eight gate samples retain %lld bytes", (long long)mt.net_bytes); + } + ray_release(w); ray_release(kc); ray_release(xc); ray_release(tw); + } + /* the same key as a SYM column of narrow codes, as a mapped table's + * columns are (an in-memory one is 64-bit): the same codes written at + * 32 bits over the same domain. The gather keeps the source's width — + * a 64-bit vector took the narrow codes as bytes of garbage — and the + * survivors are the rows whose integer twin is nonzero. */ + { + ray_t* k64 = ray_eval_str("(as 'SYM (* (>= (% cr 100) 88) (+ 1 (% (div cr 100) 1000))))"); + ray_t* ki = ray_eval_str("(* (>= (% cr 100) 88) (+ 1 (% (div cr 100) 1000)))"); + ray_t* xc = ray_eval_str("cr"); + TEST_ASSERT_NOT_NULL(k64); TEST_ASSERT_NOT_NULL(ki); TEST_ASSERT_NOT_NULL(xc); + TEST_ASSERT_EQ_I(k64->type, RAY_SYM); + ray_t* k32 = ray_sym_vec_new(RAY_SYM_W32, N); + TEST_ASSERT_NOT_NULL(k32); TEST_ASSERT_FALSE(RAY_IS_ERR(k32)); + k32->len = N; + for (int64_t i = 0; i < N; i++) + ray_write_sym(ray_data(k32), i, (uint64_t)ray_read_sym(ray_data(k64), i, RAY_SYM, k64->attrs), + RAY_SYM, k32->attrs); + ray_sym_vec_adopt_domain(k32, k64); + TEST_ASSERT_EQ_I(k32->attrs & RAY_SYM_W_MASK, RAY_SYM_W32); + ray_t* ts = ray_table_new(0); + TEST_ASSERT_NOT_NULL(ts); TEST_ASSERT_FALSE(RAY_IS_ERR(ts)); + ts = ray_table_add_col(ts, ray_sym_intern("k", 1), k32); + ts = ray_table_add_col(ts, ray_sym_intern("x", 1), xc); + TEST_ASSERT_NOT_NULL(ts); TEST_ASSERT_FALSE(RAY_IS_ERR(ts)); + ray_t* w = ray_eval_str("(quote (!= k \"0\"))"); + TEST_ASSERT_NOT_NULL(w); + const int64_t* rows = NULL; + int64_t nrows = 0, pop = 0; + ray_t* hdr = query_cd_gate_where_rows(ts, w, N, &rows, &nrows, &pop); + TEST_ASSERT_NOT_NULL(hdr); + TEST_ASSERT_FMT(nrows > 262144 / 10 && nrows < 262144 / 7, "narrow SYM survivors: %lld", (long long)nrows); + const int64_t* kd = (const int64_t*)ray_data(ki); + int64_t zeros = 0; + for (int64_t j = 0; j < nrows; j++) if (kd[rows[j]] == 0) zeros++; + TEST_ASSERT_EQ_I(zeros, 0); + scratch_free(hdr); + ray_release(w); ray_release(ts); ray_release(k32); ray_release(xc); ray_release(ki); ray_release(k64); + } + + /* a key the estimate does not cover takes the rewrite; a value it does + * not cover the slices */ + k[0] = ray_eval_str("(as 'F64 cr)"); + x = ray_eval_str("(% cr 100)"); + TEST_ASSERT_TRUE(ray_cd_two_pass_preferred(k, 1, x, NULL, N, 0, 28)); + ray_release(k[0]); ray_release(x); + k[0] = ray_eval_str("(% cr 45)"); + x = ray_eval_str("(as 'F64 cr)"); + TEST_ASSERT_FALSE(ray_cd_two_pass_preferred(k, 1, x, NULL, N, 0, 28)); + ray_release(k[0]); ray_release(x); + PASS(); +} + const test_entry_t agg_contract_entries[] = { + { "agg_contract/card_estimate", test_card_estimate, contract_setup, contract_teardown }, + { "agg_contract/cd_route", test_cd_route, contract_setup, contract_teardown }, { "agg_contract/empty_inference_errors", test_empty_inference_errors, contract_setup, contract_teardown }, { "agg_contract/nth_bounds", test_nth_bounds, contract_setup, contract_teardown }, { "agg_contract/native_binary_output", test_native_binary_output, contract_setup, contract_teardown }, @@ -2191,5 +2941,10 @@ const test_entry_t agg_contract_entries[] = { { "agg_contract/parallel_native_gather", test_parallel_native_gather, contract_setup, contract_teardown }, { "agg_contract/parallel_dominant_consumers", test_parallel_dominant_consumers, contract_setup, contract_teardown }, { "agg_contract/cancelled_group", test_cancelled_group, contract_setup, contract_teardown }, +#if defined(__linux__) + { "agg_contract/select_read_ahead_mapped", test_select_read_ahead_mapped, contract_setup, contract_teardown }, + { "agg_contract/select_read_ahead_sparse_filter", test_select_read_ahead_sparse_filter, contract_setup, contract_teardown }, + { "agg_contract/cd_gate_read_ahead", test_cd_gate_read_ahead, contract_setup, contract_teardown }, +#endif { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_arena.c b/test/test_arena.c index 162cd430b..a57e35c31 100644 --- a/test/test_arena.c +++ b/test/test_arena.c @@ -424,6 +424,53 @@ static test_result_t test_arena_total_used_multi_chunk(void) { PASS(); } +/* ---- a large arena spills past the anonymous watermark (#712) ----------- * + * + * A domain's string arena starts with small chunks. Grown to 64 MiB under a + * watermark only 4 MiB above the current footprint, it must not hold that in + * anonymous RAM: its chunks grow until they are large enough to be mapped + * over spill files. Every string still reads back. */ +static test_result_t test_arena_spills_past_watermark(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + ray_heap_init(); + ray_heap_direct_cache_drain(); + int64_t base = ray_heap_anon_committed(); + int64_t previous = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(base + INT64_C(4) * 1024 * 1024); + + ray_arena_t* arena = ray_arena_new(64 * 1024); + char buf[200]; + memset(buf, 'x', sizeof(buf)); + const int n = 300000; /* 300K strings of 200 bytes: ~78 MiB of atoms */ + ray_t* first = NULL; + ray_t* last = NULL; + bool ok = arena != NULL; + for (int i = 0; i < n && ok; i++) { + int k = snprintf(buf, 16, "%d", i); + buf[k] = 'x'; + ray_t* a = ray_arena_str(arena, buf, sizeof(buf)); + if (!a) ok = false; + if (i == 0) first = a; + last = a; + } + int64_t grown = ray_heap_anon_committed() - base; + bool bounded = grown < INT64_C(8) * 1024 * 1024; + bool readable = ok && first && last && + memcmp(ray_str_ptr(first), "0x", 2) == 0 && + memcmp(ray_str_ptr(last), "299999x", 7) == 0 && + ray_str_len(last) == sizeof(buf); + ray_arena_destroy(arena); + bool back = ray_heap_anon_committed() == base; + ray_heap_set_anon_watermark(previous); + ray_heap_destroy(); + TEST_ASSERT_TRUE(ok && readable); + TEST_ASSERT_TRUE(bounded); + TEST_ASSERT_TRUE(back); + PASS(); +} + /* ---- ray_arena_reset NULL arena guard ----------------------------------- */ static test_result_t test_arena_reset_null(void) { @@ -452,6 +499,7 @@ const test_entry_t arena_entries[] = { { "arena/total_used_null", test_arena_total_used_null, NULL, NULL }, { "arena/total_used_multi_chunk", test_arena_total_used_multi_chunk, NULL, NULL }, { "arena/reset_null", test_arena_reset_null, NULL, NULL }, + { "arena/spills_past_watermark", test_arena_spills_past_watermark, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_domain.c b/test/test_domain.c index 3a80d850b..b9a042b14 100644 --- a/test/test_domain.c +++ b/test/test_domain.c @@ -1,3 +1,6 @@ +#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE) +#define _POSIX_C_SOURCE 200809L /* setenv / unsetenv: the import dictionary's trace flag */ +#endif /* * Copyright (c) 2025-2026 Anton Kundenko * All rights reserved. @@ -37,15 +40,20 @@ #include "mem/heap.h" #include "table/sym.h" #include "table/domain.h" +#include "table/symimp.h" /* ray_symimp_stats_t: the import dictionary's counts */ #include "store/col.h" #include "store/serde.h" #include "core/pool.h" /* the batch intern probes on the pool */ +#include "core/platform.h" /* ray_thread_create: lookups against a reservation */ +#include "core/profile.h" /* ray_profile_now_ns: their bounded wait */ #include "ops/hash.h" /* ray_hash_bytes: batch intern takes prehashed entries */ #include "mem/sys.h" #include "ops/ops.h" /* RAY_PARTED_BASE (parted-flatten adoption test) */ #include #include #include +#include /* setenv */ +#include #define TMP_DOM_SYM_PATH "/tmp/rayforce_test_domain_sym" #define TMP_DOM_COL_PATH "/tmp/rayforce_test_domain_col" @@ -2191,8 +2199,521 @@ static test_result_t test_domain_private(void) { ray_release(v); PASS(); } + +/* ray_sym_domain_flush_append: a symfile grown in three appends (the first + * creating it, the last with nothing new but syncing) holds exactly the + * bytes one ray_sym_domain_flush of the same vocabulary writes, reopens + * with every position, and a file changed behind the domain's back is + * refused as another writer. */ +static bool dom_file_bytes(const char* path, uint8_t** out, long* n) { + FILE* f = fopen(path, "rb"); + if (!f) return false; + fseek(f, 0, SEEK_END); *n = ftell(f); fseek(f, 0, SEEK_SET); + *out = (uint8_t*)ray_sys_alloc((size_t)*n + 1); + bool ok = *out && fread(*out, 1, (size_t)*n, f) == (size_t)*n; + fclose(f); + return ok; +} +static test_result_t test_domain_flush_append(void) { + const char* pa = TMP_DOM_SYM_PATH "_app"; + const char* pb = TMP_DOM_SYM_PATH "_one"; + char buf[64]; + for (int k = 0; k < 2; k++) { + const char* p = k ? pb : pa; + unlink(p); + snprintf(buf, sizeof(buf), "%s.lk", p); unlink(buf); + } + ray_sym_domain_t* a = ray_sym_domain_open_or_create(pa); + ray_sym_domain_t* b = ray_sym_domain_open_or_create(pb); + TEST_ASSERT_NOT_NULL(a); TEST_ASSERT_NOT_NULL(b); + for (int round = 0; round < 3; round++) { + int n = round == 2 ? 0 : 500 + 300 * round; + for (int i = 0; i < n; i++) { + int l = snprintf(buf, sizeof(buf), "r%d-%d%s", round, i, i % 7 ? "" : "-a-longer-string"); + TEST_ASSERT_TRUE(ray_sym_domain_intern(a, buf, (size_t)l) >= 0); + TEST_ASSERT_TRUE(ray_sym_domain_intern(b, buf, (size_t)l) >= 0); + } + TEST_ASSERT_EQ_I(ray_sym_domain_flush_append(a, round == 2), RAY_OK); + } + TEST_ASSERT_EQ_I(ray_sym_domain_flush(b, true), RAY_OK); + uint8_t *fa = NULL, *fb = NULL; long na = 0, nb = 0; + TEST_ASSERT_TRUE(dom_file_bytes(pa, &fa, &na)); + TEST_ASSERT_TRUE(dom_file_bytes(pb, &fb, &nb)); + TEST_ASSERT_EQ_I(na, nb); + TEST_ASSERT_EQ_I(memcmp(fa, fb, (size_t)na), 0); + ray_sys_free(fa); ray_sys_free(fb); + int64_t count = ray_sym_domain_count(a); + + /* another writer: the file is no longer the persisted prefix */ + FILE* f = fopen(pa, "ab"); + TEST_ASSERT_NOT_NULL(f); + fputc(0, f); fclose(f); + TEST_ASSERT_TRUE(ray_sym_domain_intern(a, "late", 4) >= 0); + TEST_ASSERT_EQ_I(ray_sym_domain_flush_append(a, false), RAY_ERR_CORRUPT); + ray_sym_domain_release(a); + ray_sym_domain_release(b); + + ray_sym_domain_t* re = ray_sym_domain_open(pb); + TEST_ASSERT_NOT_NULL(re); + TEST_ASSERT_EQ_I(ray_sym_domain_count(re), count); + TEST_ASSERT_EQ_I(ray_sym_domain_find(re, "r1-799", 6) >= 0, 1); + ray_sym_domain_release(re); + for (int k = 0; k < 2; k++) { + const char* p = k ? pb : pa; + unlink(p); + snprintf(buf, sizeof(buf), "%s.lk", p); unlink(buf); + } + PASS(); +} + +/* ray_sym_domain_create_import: on an 8-worker pool, 32 tasks intern the + * same 100K strings in the same order at once (every miss is raced), then + * each its own slice of 800K more, so shard tables and the mapped file both + * grow past their first size. A string gets one position whoever adds it, + * "" is position 0, the count is the distinct strings plus one, and after + * the durable flush the file reopens as an ordinary domain with every + * string at its position. */ +#define IMP_SHARED 100000 +#define IMP_OWN 800000 +#define IMP_N (IMP_SHARED + IMP_OWN) +#define IMP_TASKS 32 +typedef struct { ray_sym_domain_t* dom; int64_t* pos; _Atomic(int) bad; } imp_ctx_t; +static int imp_str(int64_t i, char* buf) { return snprintf(buf, 32, "import-%lld-%c", (long long)i, (char)('a' + i % 26)); } +static void imp_range(imp_ctx_t* c, int64_t s, int64_t e) { + enum { B = 512 }; + char bufs[B][32]; const char* strs[B]; size_t lens[B]; uint32_t hs[B]; int64_t out[B]; + for (int64_t i = s; i < e; i += B) { + int64_t n = e - i < B ? e - i : B; + for (int64_t j = 0; j < n; j++) { + lens[j] = (size_t)imp_str(i + j, bufs[j]); strs[j] = bufs[j]; + hs[j] = (uint32_t)ray_hash_bytes(strs[j], lens[j]); + } + if (!ray_sym_domain_intern_batch(c->dom, n, strs, lens, hs, out)) { atomic_store(&c->bad, 1); return; } + for (int64_t j = 0; j < n; j++) { + int64_t prev = 0; + if (!atomic_compare_exchange_strong((_Atomic(int64_t)*)&c->pos[i + j], &prev, out[j]) && prev != out[j]) + atomic_store(&c->bad, 1); + } + } +} +static void imp_task(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; (void)end; + imp_ctx_t* c = (imp_ctx_t*)raw; + imp_range(c, 0, IMP_SHARED); + int64_t per = IMP_OWN / IMP_TASKS; + imp_range(c, IMP_SHARED + start * per, IMP_SHARED + (start + 1) * per); +} +static test_result_t test_domain_import_dict(void) { + const char* p = TMP_DOM_SYM_PATH "_imp"; + unlink(p); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(8), RAY_OK); + ray_pool_t* pool = ray_pool_get(); + ray_sym_domain_t* dom = ray_sym_domain_create_import(p); + if (!dom) { ray_pool_destroy(); SKIP("import dictionary unsupported here"); } + TEST_ASSERT_EQ_I(ray_sym_domain_count(dom), 1); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "", 0), 0); + imp_ctx_t ctx = { dom, (int64_t*)ray_sys_alloc((size_t)IMP_N * sizeof(int64_t)), 0 }; + TEST_ASSERT_NOT_NULL(ctx.pos); + memset(ctx.pos, 0, (size_t)IMP_N * sizeof(int64_t)); + if (pool && pool->n_workers > 0) ray_pool_dispatch_n(pool, imp_task, &ctx, IMP_TASKS); + else for (int t = 0; t < IMP_TASKS; t++) imp_task(&ctx, 0, t, t + 1); + TEST_ASSERT_EQ_I(atomic_load(&ctx.bad), 0); + TEST_ASSERT_EQ_I(ray_sym_domain_count(dom), IMP_N + 1); + /* one more append and its single-string intern agree */ + int64_t z = ray_sym_domain_intern(dom, "late-one", 8); + TEST_ASSERT_EQ_I(z, IMP_N + 1); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "late-one", 8), z); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(dom, true), RAY_OK); + ray_sym_domain_release(dom); + + ray_sym_domain_t* re = ray_sym_domain_open(p); + TEST_ASSERT_NOT_NULL(re); + TEST_ASSERT_EQ_I(ray_sym_domain_count(re), IMP_N + 2); + int64_t bad = 0; + char buf[32]; + for (int64_t i = 0; i < IMP_N; i += 997) { + int l = imp_str(i, buf); + ray_t* s = ray_sym_domain_str(re, ctx.pos[i]); + if (!s || ray_str_len(s) != (size_t)l || memcmp(ray_str_ptr(s), buf, (size_t)l)) bad++; + if (ray_sym_domain_find(re, buf, (size_t)l) != ctx.pos[i]) bad++; + } + TEST_ASSERT_EQ_I(bad, 0); + TEST_ASSERT_EQ_I(ray_sym_domain_find(re, "", 0), 0); + TEST_ASSERT_EQ_I(ray_sym_domain_find(re, "late-one", 8), IMP_N + 1); + ray_sym_domain_release(re); + ray_sys_free(ctx.pos); + ray_pool_destroy(); + unlink(p); + unlink(TMP_DOM_SYM_PATH "_imp.lk"); + PASS(); +} +/* The import dictionary frees a shard table it replaced once no lookup can + * hold it. Serially, 300K strings leave every one of the 1024 shard tables + * at its first size, and 900K at twice that (a shard's share of 900K stays + * under the next growth); between the two, committed memory grows by the + * new tables less the old ones, not by the new tables whole. A table is + * cap 8-byte slots plus a header, counted in 4 KiB units as ray_sys_get_stat + * counts every allocation whatever the page size. */ +static int64_t imp_tab_bytes(int64_t cap) { + return (cap * 8 + 64 + 4095) / 4096 * 4096; +} +static bool imp_intern_serial(ray_sym_domain_t* dom, int64_t lo, int64_t hi) { + imp_ctx_t c = { dom, NULL, 0 }; + enum { B = 512 }; + char bufs[B][32]; const char* strs[B]; size_t lens[B]; uint32_t hs[B]; int64_t out[B]; + for (int64_t i = lo; i < hi; i += B) { + int64_t n = hi - i < B ? hi - i : B; + for (int64_t j = 0; j < n; j++) { + lens[j] = (size_t)imp_str(i + j, bufs[j]); strs[j] = bufs[j]; + hs[j] = (uint32_t)ray_hash_bytes(strs[j], lens[j]); + } + if (!ray_sym_domain_intern_batch(c.dom, n, strs, lens, hs, out)) return false; + } + return true; +} +static test_result_t test_domain_import_dict_reclaim(void) { + const char* p = TMP_DOM_SYM_PATH "_impr"; + unlink(p); + ray_sym_domain_t* dom = ray_sym_domain_create_import(p); + if (!dom) SKIP("import dictionary unsupported here"); + TEST_ASSERT_TRUE(imp_intern_serial(dom, 0, 300000)); + /* one more new string: the last batch's replaced tables are freed by + * the next batch that adds */ + TEST_ASSERT_TRUE(ray_sym_domain_intern(dom, "flush-a", 7) > 0); + int64_t a = 0, b = 0; + ray_sys_get_stat(&a, NULL); + TEST_ASSERT_TRUE(imp_intern_serial(dom, 300000, 900000)); + TEST_ASSERT_TRUE(ray_sym_domain_intern(dom, "flush-b", 7) > 0); + ray_sys_get_stat(&b, NULL); + int64_t grew = b - a, small = imp_tab_bytes(1024), big = imp_tab_bytes(2048); + TEST_ASSERT_TRUE(grew >= 1024 * (big - small) - (1 << 20)); /* every shard grew */ + TEST_ASSERT_TRUE(grew < 1024 * (big - small / 2)); /* and gave its old table back */ + TEST_ASSERT_EQ_I(ray_sym_domain_count(dom), 900003); + ray_sym_domain_release(dom); + unlink(p); + unlink(TMP_DOM_SYM_PATH "_impr.lk"); + PASS(); +} +/* The import dictionary takes the shard from the 64-bit hash's top bits and + * keeps its low 32 as the slot tag. Crafted hashes (the dictionary trusts + * the caller's): 1024 strings whose hashes share the low 32 bits but not + * the top 10 land in 1024 shards, and are added and found again without a + * single tag matching another string; 64 strings sharing one whole hash all + * get positions of their own and are found by their bytes. Every position + * survives a re-intern, and the 32-bit entry point, which hashes again, + * finds strings the 64-bit one added under their real hashes. The counts + * are kept for a dictionary made under the converters' trace (RAY_CSV_TRACE + * at create, set here for it); one made without it keeps none, its + * positions the same. */ +static void imp_trace_env(bool on) { +#if defined(_WIN32) + _putenv_s("RAY_CSV_TRACE", on ? "1" : ""); +#else + if (on) setenv("RAY_CSV_TRACE", "1", 1); else unsetenv("RAY_CSV_TRACE"); +#endif +} +#define IMP_SPREAD 1024 +#define IMP_SAME 64 +static test_result_t test_domain_import_dict_tags(void) { + const char* p = TMP_DOM_SYM_PATH "_impt"; + unlink(p); + imp_trace_env(true); + ray_sym_domain_t* dom = ray_sym_domain_create_import(p); + imp_trace_env(false); + if (!dom) SKIP("import dictionary unsupported here"); + enum { N = IMP_SPREAD + IMP_SAME }; + static char bufs[N][32]; + const char* strs[N]; size_t lens[N]; uint64_t hs[N]; int64_t pos[N], again[N]; + for (int i = 0; i < N; i++) { + lens[i] = (size_t)snprintf(bufs[i], sizeof(bufs[i]), "tag-%d", i); strs[i] = bufs[i]; + hs[i] = i < IMP_SPREAD ? ((uint64_t)i << 54) | UINT64_C(0x5a5a5a5a) + : UINT64_C(0x0123456789abcdef); + } + ray_symimp_stats_t st; + ray_sym_domain_import_stats(dom, &st); /* from zero */ + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch64(dom, IMP_SPREAD, strs, lens, hs, pos)); + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch64(dom, IMP_SPREAD, strs, lens, hs, again)); + TEST_ASSERT_TRUE(ray_sym_domain_import_stats(dom, &st)); + TEST_ASSERT_EQ_I(st.added, IMP_SPREAD); + TEST_ASSERT_EQ_I(st.hits, IMP_SPREAD); + TEST_ASSERT_EQ_I(st.false_tags, 0); + /* one at a time, so each is looked up in the shard the others fill */ + for (int i = IMP_SPREAD; i < N; i++) + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch64(dom, 1, strs + i, lens + i, hs + i, pos + i)); + for (int i = IMP_SPREAD; i < N; i++) + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch64(dom, 1, strs + i, lens + i, hs + i, again + i)); + TEST_ASSERT_TRUE(ray_sym_domain_import_stats(dom, &st)); + TEST_ASSERT_EQ_I(st.added, IMP_SAME); + TEST_ASSERT_TRUE(st.false_tags > 0); + for (int i = 0; i < N; i++) { + TEST_ASSERT_EQ_I(pos[i], i + 1); /* "" is position 0 */ + TEST_ASSERT_EQ_I(again[i], pos[i]); + } + TEST_ASSERT_EQ_I(ray_sym_domain_count(dom), N + 1); + /* real hashes: added through the 64-bit entry, found through the 32-bit */ + const char* real = "a real hash"; + size_t rl = strlen(real); + uint64_t rh = ray_hash_bytes(real, rl); + uint32_t rh32 = (uint32_t)rh; + int64_t r64 = -1, r32 = -2; + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch64(dom, 1, &real, &rl, &rh, &r64)); + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch(dom, 1, &real, &rl, &rh32, &r32)); + TEST_ASSERT_EQ_I(r64, N + 1); + TEST_ASSERT_EQ_I(r32, r64); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, real, rl), r64); + ray_sym_domain_release(dom); + unlink(p); + unlink(TMP_DOM_SYM_PATH "_impt.lk"); + /* made without the trace: the same positions, no counts */ + dom = ray_sym_domain_create_import(p); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch64(dom, IMP_SPREAD, strs, lens, hs, again)); + for (int i = IMP_SPREAD; i < N; i++) + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch64(dom, 1, strs + i, lens + i, hs + i, again + i)); + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch64(dom, N, strs, lens, hs, again)); + for (int i = 0; i < N; i++) TEST_ASSERT_EQ_I(again[i], pos[i]); + TEST_ASSERT_TRUE(ray_sym_domain_import_stats(dom, &st)); + TEST_ASSERT_EQ_I(st.strings + st.probes + st.hits + st.added + st.slots + st.false_tags + st.grows, 0); + TEST_ASSERT_EQ_I(st.count, N + 1); + ray_sym_domain_release(dom); + unlink(p); + unlink(TMP_DOM_SYM_PATH "_impt.lk"); + PASS(); +} +/* The first reservation (ray_symimp_reserve: the grouped import's records) + * ends the dictionary's interning: from it on a lookup is refused and no + * string is added, and the shard tables go back at once unless a lookup is + * in flight (which keeps them to the end). Serially: the tables go, the + * counts and the index bytes read none, the reserved positions follow the + * interned ones, and a lookup is refused. Then rounds of lookup threads + * against a reservation the main thread makes once every thread has got a + * batch through: 64K strings already there, found batch after batch (eight + * chunks, between which a thread holds no table), on one thread and on + * four; and on two, the same with one new string a chunk (a lookup of the + * chunk then adds it under the lock). Every batch gets every position + * right or is refused; none reads a table freed under it (a reservation + * that frees regardless of a lookup in flight, or a lookup that reads the + * reservation before it registers, faults here) and none adds a string past + * the reservation (as an add that does not check it under the lock does). */ +#define IMPR_N 65536 +#define IMPR_EVERY 8192 /* the new strings' spacing: one a chunk (SI_BATCH) */ +typedef struct { + ray_symimp_t* imp; + const char* const* strs; const size_t* lens; const uint64_t* hs; const int64_t* want; + int fresh; /* 0: the known strings; else this thread's tag for its new ones */ + char (*buf)[32]; const char** fs; size_t* fl; uint64_t* fh; /* fresh: the batch */ + int64_t* out; + _Atomic(int64_t) found; /* batches got through */ + _Atomic(int) done, bad; +} impr_ctx_t; +static void impr_lookups(void* raw) { + impr_ctx_t* c = (impr_ctx_t*)raw; + const char* const* s = c->strs; const size_t* l = c->lens; const uint64_t* h = c->hs; + if (c->fresh) { + memcpy(c->fs, c->strs, (size_t)IMPR_N * sizeof(char*)); + memcpy(c->fl, c->lens, (size_t)IMPR_N * sizeof(size_t)); + memcpy(c->fh, c->hs, (size_t)IMPR_N * sizeof(uint64_t)); + s = c->fs; l = c->fl; h = c->fh; + } + for (int64_t k = 0;; k++) { + for (int64_t i = 0; c->fresh && i < IMPR_N; i += IMPR_EVERY) { + char* b = c->buf[i / IMPR_EVERY]; + c->fl[i] = (size_t)snprintf(b, 32, "fresh-%d-%lld", c->fresh, (long long)(k * IMPR_N + i)); + c->fs[i] = b; + c->fh[i] = ray_hash_bytes(b, c->fl[i]); + } + if (!ray_symimp_intern_batch(c->imp, IMPR_N, s, l, h, c->out)) break; + for (int64_t i = 0; i < IMPR_N; i++) { + bool ok = c->out[i] == c->want[i]; + if (c->fresh && i % IMPR_EVERY == 0) { + uint32_t len = 0; + const char* r = ray_symimp_get(c->imp, c->out[i], &len); + ok = len == l[i] && !memcmp(r, s[i], len); + } + if (!ok) { atomic_store(&c->bad, 1); break; } + } + atomic_fetch_add(&c->found, 1); + } + atomic_store(&c->done, 1); +} +static test_result_t test_domain_import_dict_reserve(void) { + const char* p = TMP_DOM_SYM_PATH "_imps"; + char (*bufs)[32] = (char (*)[32])ray_sys_alloc((size_t)IMPR_N * 32); + const char** strs = (const char**)ray_sys_alloc((size_t)IMPR_N * sizeof(char*)); + size_t* lens = (size_t*)ray_sys_alloc((size_t)IMPR_N * sizeof(size_t)); + uint64_t* hs = (uint64_t*)ray_sys_alloc((size_t)IMPR_N * sizeof(uint64_t)); + int64_t* want = (int64_t*)ray_sys_alloc((size_t)IMPR_N * sizeof(int64_t)); + int64_t* outs = (int64_t*)ray_sys_alloc((size_t)4 * IMPR_N * sizeof(int64_t)); + char (*fbuf)[32] = (char (*)[32])ray_sys_alloc((size_t)2 * (IMPR_N / IMPR_EVERY) * 32); + const char** fs = (const char**)ray_sys_alloc((size_t)2 * IMPR_N * sizeof(char*)); + size_t* fl = (size_t*)ray_sys_alloc((size_t)2 * IMPR_N * sizeof(size_t)); + uint64_t* fh = (uint64_t*)ray_sys_alloc((size_t)2 * IMPR_N * sizeof(uint64_t)); + TEST_ASSERT_TRUE(bufs && strs && lens && hs && want && outs && fbuf && fs && fl && fh); + for (int64_t i = 0; i < IMPR_N; i++) { + lens[i] = (size_t)imp_str(i, bufs[i]); strs[i] = bufs[i]; + hs[i] = ray_hash_bytes(strs[i], lens[i]); + } + /* round 0 serial; 1-8 one thread finding, 9-12 four, 13-16 two adding too */ + int timeouts = 0, bad = 0; + for (int round = 0; round <= 16; round++) { + unlink(p); + ray_sym_domain_t* dom = ray_sym_domain_create_import(p); + if (!dom) { + ray_sys_free(bufs); ray_sys_free(strs); ray_sys_free(lens); ray_sys_free(hs); ray_sys_free(want); + ray_sys_free(outs); ray_sys_free(fbuf); ray_sys_free(fs); ray_sys_free(fl); ray_sys_free(fh); + SKIP("import dictionary unsupported here"); + } + ray_symimp_t* imp = ray_sym_domain_import(dom); + TEST_ASSERT_NOT_NULL(imp); + TEST_ASSERT_TRUE(ray_symimp_intern_batch(imp, IMPR_N, strs, lens, hs, want)); + int64_t count = ray_symimp_count(imp), p0 = -1, o0 = -1, again = -1; + TEST_ASSERT_EQ_I(count, IMPR_N + 1); /* "" is position 0 */ + if (round == 0) { + TEST_ASSERT_TRUE(ray_symimp_index_bytes(imp) > 0); + TEST_ASSERT_TRUE(ray_symimp_reserve(imp, 2, 16, &p0, &o0)); + TEST_ASSERT_EQ_I(p0, count); + TEST_ASSERT_EQ_I(ray_symimp_count(imp), count + 2); + TEST_ASSERT_EQ_I(ray_symimp_index_bytes(imp), 0); + ray_symimp_stats_t st; + ray_symimp_stats(imp, &st); + TEST_ASSERT_EQ_I(st.tab_bytes, 0); + TEST_ASSERT_EQ_I(st.count, count + 2); + TEST_ASSERT_FALSE(ray_symimp_intern_batch(imp, 1, strs, lens, hs, &again)); + ray_symimp_put(imp, p0, o0, "res0", 4); ray_symimp_put(imp, p0 + 1, o0 + 8, "res1", 4); + TEST_ASSERT_TRUE(ray_symimp_reserve(imp, 1, 8, &p0, &o0)); /* a later one: nothing more to free */ + TEST_ASSERT_EQ_I(p0, count + 2); + ray_symimp_put(imp, p0, o0, "res2", 4); + } else { + int nt = round <= 8 ? 1 : round <= 12 ? 4 : 2, fresh = round > 12; + impr_ctx_t ctx[4]; + ray_thread_t th[4]; + int started = 0; + for (int t = 0; t < nt; t++) { + ctx[t] = (impr_ctx_t){ imp, strs, lens, hs, want, fresh ? t + 1 : 0, + fbuf + t * (IMPR_N / IMPR_EVERY), fs + (int64_t)t * IMPR_N, fl + (int64_t)t * IMPR_N, fh + (int64_t)t * IMPR_N, + outs + (int64_t)t * IMPR_N, 0, 0, 0 }; + if (ray_thread_create(&th[t], impr_lookups, &ctx[t]) == RAY_OK) started++; + else break; + } + /* every thread through a batch (or out), within a bound */ + int64_t until = ray_profile_now_ns() + (int64_t)30 * 1000000000; + for (int t = 0; t < started; t++) + while (!atomic_load(&ctx[t].found) && !atomic_load(&ctx[t].done)) { + if (ray_profile_now_ns() > until) { timeouts++; break; } + RAY_CPU_RELAX(); + } + bool reserved = ray_symimp_reserve(imp, 1, 8, &p0, &o0); + for (int t = 0; t < started; t++) ray_thread_join(th[t]); + TEST_ASSERT_EQ_I(started, nt); + TEST_ASSERT_TRUE(reserved); + for (int t = 0; t < nt; t++) { + if (atomic_load(&ctx[t].bad) || !atomic_load(&ctx[t].found)) bad++; + } + /* nothing added past the reservation */ + if (ray_symimp_count(imp) != p0 + 1) { + fprintf(stderr, " reserve round %d: %lld strings, the reservation at %lld\n", round, + (long long)ray_symimp_count(imp), (long long)p0); + bad++; + } + TEST_ASSERT_FALSE(ray_symimp_intern_batch(imp, 1, strs, lens, hs, &again)); + ray_symimp_put(imp, p0, o0, "res0", 4); + } + ray_sym_domain_release(dom); + unlink(p); + unlink(TMP_DOM_SYM_PATH "_imps.lk"); + } + ray_sys_free(bufs); ray_sys_free(strs); ray_sys_free(lens); ray_sys_free(hs); ray_sys_free(want); + ray_sys_free(outs); ray_sys_free(fbuf); ray_sys_free(fs); ray_sys_free(fl); ray_sys_free(fh); + TEST_ASSERT_EQ_I(timeouts, 0); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +} +/* Skeptic probe (pqio round 4). Rounds of the reservation against lookups + * in flight (two threads finding the 64K strings batch after batch), as in + * import_dict_reserve: how often the reservation kept the shard tables (a + * lookup was in flight, so ray_symimp_index_bytes still reads them right + * after it), and that a kept set goes back with the dictionary: the + * committed memory (ray_heap_anon_committed, which every ray_sys_alloc + * counts) the same after a round as before it. The tables are 1024 + * mappings of 12 KB each: a kept set never freed shows as 12 MB. */ +static test_result_t test_domain_sk4_reserve_kept_freed(void) { + const char* p = TMP_DOM_SYM_PATH "_imk"; + char (*bufs)[32] = (char (*)[32])ray_sys_alloc((size_t)IMPR_N * 32); + const char** strs = (const char**)ray_sys_alloc((size_t)IMPR_N * sizeof(char*)); + size_t* lens = (size_t*)ray_sys_alloc((size_t)IMPR_N * sizeof(size_t)); + uint64_t* hs = (uint64_t*)ray_sys_alloc((size_t)IMPR_N * sizeof(uint64_t)); + int64_t* want = (int64_t*)ray_sys_alloc((size_t)IMPR_N * sizeof(int64_t)); + int64_t* outs = (int64_t*)ray_sys_alloc((size_t)2 * IMPR_N * sizeof(int64_t)); + TEST_ASSERT_TRUE(bufs && strs && lens && hs && want && outs); + for (int64_t i = 0; i < IMPR_N; i++) { + lens[i] = (size_t)imp_str(i, bufs[i]); strs[i] = bufs[i]; + hs[i] = ray_hash_bytes(strs[i], lens[i]); + } + int kept = 0, freed = 0, leaks = 0, timeouts = 0, bad = 0, measured = 0; + for (int round = 0; round < 17; round++) { + unlink(p); + int64_t c0 = ray_heap_anon_committed(); + ray_sym_domain_t* dom = ray_sym_domain_create_import(p); + if (!dom) { + ray_sys_free(bufs); ray_sys_free(strs); ray_sys_free(lens); ray_sys_free(hs); ray_sys_free(want); ray_sys_free(outs); + SKIP("import dictionary unsupported here"); + } + ray_symimp_t* imp = ray_sym_domain_import(dom); + TEST_ASSERT_NOT_NULL(imp); + TEST_ASSERT_TRUE(ray_symimp_intern_batch(imp, IMPR_N, strs, lens, hs, want)); + impr_ctx_t ctx[2]; + ray_thread_t th[2]; + int started = 0; + for (int t = 0; t < 2; t++) { + ctx[t] = (impr_ctx_t){ imp, strs, lens, hs, want, 0, NULL, NULL, NULL, NULL, outs + (int64_t)t * IMPR_N, 0, 0, 0 }; + if (ray_thread_create(&th[t], impr_lookups, &ctx[t]) == RAY_OK) started++; + else break; + } + int64_t until = ray_profile_now_ns() + (int64_t)30 * 1000000000; + for (int t = 0; t < started; t++) + while (!atomic_load(&ctx[t].found) && !atomic_load(&ctx[t].done)) { + if (ray_profile_now_ns() > until) { timeouts++; break; } + RAY_CPU_RELAX(); + } + int64_t p0 = -1, o0 = -1; + bool reserved = ray_symimp_reserve(imp, 1, 8, &p0, &o0); + int64_t ib = ray_symimp_index_bytes(imp); + for (int t = 0; t < started; t++) ray_thread_join(th[t]); + TEST_ASSERT_EQ_I(started, 2); + TEST_ASSERT_TRUE(reserved); + for (int t = 0; t < 2; t++) if (atomic_load(&ctx[t].bad) || !atomic_load(&ctx[t].found)) bad++; + if (ib > 0) kept++; else freed++; + ray_symimp_put(imp, p0, o0, "res0", 4); + ray_sym_domain_release(dom); + unlink(p); + unlink(TMP_DOM_SYM_PATH "_imk.lk"); + int64_t c1 = ray_heap_anon_committed(); + if (round > 0) { /* the first warms whatever stays */ + measured++; + if (c1 - c0 >= ((int64_t)8 << 20)) { + leaks++; + fprintf(stderr, " sk4 reserve round %d (%s): %lld bytes more committed after the dictionary went\n", round, + ib > 0 ? "kept" : "freed", (long long)(c1 - c0)); + } + } + } + fprintf(stderr, " sk4 reserve: tables kept (a lookup in flight) in %d rounds, freed at once in %d; %d of %d measured rounds leaked\n", + kept, freed, leaks, measured); + ray_sys_free(bufs); ray_sys_free(strs); ray_sys_free(lens); ray_sys_free(hs); ray_sys_free(want); ray_sys_free(outs); + TEST_ASSERT_EQ_I(timeouts, 0); + TEST_ASSERT_EQ_I(bad, 0); + TEST_ASSERT_EQ_I(leaks, 0); + PASS(); +} const test_entry_t domain_entries[] = { { "domain/private", test_domain_private, domain_setup, domain_teardown }, + { "domain/flush_append", test_domain_flush_append, domain_setup, domain_teardown }, + { "domain/import_dict", test_domain_import_dict, domain_setup, domain_teardown }, + { "domain/import_dict_reclaim", test_domain_import_dict_reclaim, domain_setup, domain_teardown }, + { "domain/import_dict_tags", test_domain_import_dict_tags, domain_setup, domain_teardown }, + { "domain/import_dict_reserve", test_domain_import_dict_reserve, domain_setup, domain_teardown }, + { "domain/sk4_reserve_kept_freed", test_domain_sk4_reserve_kept_freed, 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 }, diff --git a/test/test_exec.c b/test/test_exec.c index 4712b5e28..cf5f7d719 100644 --- a/test/test_exec.c +++ b/test/test_exec.c @@ -3022,6 +3022,39 @@ static test_result_t test_exec_str_replace(void) { PASS(); } +/* The low-level text kernel accepts equal-length vectors only, including + * empty vectors. Query collection concat is routed elsewhere. */ +static test_result_t test_exec_str_concat_lengths(void) { + ray_heap_init(); + (void)ray_sym_init(); + const int lens[] = { 0, 1, 3 }; + for (int ai = 0; ai < 3; ai++) for (int bi = 0; bi < 3; bi++) { + ray_t* a = ray_vec_new(RAY_STR, lens[ai]); + ray_t* b = ray_vec_new(RAY_STR, lens[bi]); + for (int i = 0; i < lens[ai]; i++) a = ray_str_vec_append(a, "abcdefghijklmnop", 16); + for (int i = 0; i < lens[bi]; i++) b = ray_str_vec_append(b, "qrstuvwxyz", 10); + ray_graph_t* g = ray_graph_new(NULL); + ray_op_t* args[2] = { ray_const_vec(g, a), ray_const_vec(g, b) }; + ray_op_t* op = ray_concat(g, args, 2); + ray_t* result = ray_execute(g, op); + TEST_ASSERT_NOT_NULL(result); + if (lens[ai] == lens[bi]) { + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(result->len, lens[ai]); + ray_release(result); + } else { + TEST_ASSERT_TRUE(RAY_IS_ERR(result)); + TEST_ASSERT_TRUE(strcmp(ray_err_code(result), "length") == 0); + ray_error_free(result); + } + ray_graph_free(g); + ray_release(a); ray_release(b); + } + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + static test_result_t test_exec_str_concat(void) { ray_heap_init(); (void)ray_sym_init(); @@ -12037,7 +12070,7 @@ static test_result_t test_expr_sym_w32_fast_eq_ne(void) { ray_release(result); ray_graph_free(g); - /* s < "baz" — W32 SYM LT ordering, hits BR_FAST(uint32_t) at line 1698 */ + /* s < "baz" — lexical ordering through the vocabulary LUT (#738). */ g = ray_graph_new(tbl); sc = ray_scan(g, "s"); lit = ray_const_str(g, "baz", 3); @@ -12045,10 +12078,8 @@ static test_result_t test_expr_sym_w32_fast_eq_ne(void) { cnt = ray_sum(g, lt); result = ray_execute(g, cnt); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - /* Ordering compares intern IDs numerically. - * id1=foo, id2=bar, id3=baz are interned in that order: id1i64, 4); + /* Only the two "bar" rows precede "baz", regardless of intern order. */ + TEST_ASSERT_EQ_I(result->i64, 2); ray_release(result); ray_graph_free(g); @@ -12274,7 +12305,7 @@ static test_result_t test_expr_sym_w64_fast_scalar(void) { ray_release(result); ray_graph_free(g); - /* animal < "dog" — W64 SYM LT (intern ID ordering) */ + /* animal < "dog" — W64 SYM lexical ordering (#738). */ g = ray_graph_new(tbl); ac = ray_scan(g, "animal"); lit = ray_const_str(g, "dog", 3); @@ -12282,8 +12313,8 @@ static test_result_t test_expr_sym_w64_fast_scalar(void) { cnt = ray_sum(g, lt); result = ray_execute(g, cnt); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - /* id1=dog(first), id2=cat, id3=bird. id1i64, 0); + /* "cat" and "bird" precede "dog". */ + TEST_ASSERT_EQ_I(result->i64, 2); ray_release(result); ray_graph_free(g); @@ -17601,6 +17632,7 @@ const test_entry_t exec_entries[] = { { "exec/str_substr", test_exec_str_substr, NULL, NULL }, { "exec/str_replace", test_exec_str_replace, NULL, NULL }, { "exec/str_concat", test_exec_str_concat, NULL, NULL }, + { "exec/str_concat_lengths", test_exec_str_concat_lengths, NULL, NULL }, { "exec/str_if", test_exec_str_if, NULL, NULL }, { "exec/str_if_scalar", test_exec_str_if_scalar, NULL, NULL }, { "exec/str_eq_len1_broadcast", test_exec_str_eq_len1_broadcast, NULL, NULL }, diff --git a/test/test_expr_null.c b/test/test_expr_null.c index 7a2601fe7..a7f3911b4 100644 --- a/test/test_expr_null.c +++ b/test/test_expr_null.c @@ -29,6 +29,7 @@ #include "ops/internal.h" #include "mem/heap.h" #include "table/sym.h" +#include "table/domain.h" #include "ops/idxop.h" #include "ops/fused_pred.h" #include @@ -1404,8 +1405,9 @@ static test_result_t test_diff_f64_andor_chokes(void) { * A null SYM is id 0, below every real intern id, and the fallback treats a * null SYM as "smaller than everything" in all six comparisons (null == null, * null != x, null < x are true; null == x, x < null are false). Raw id - * compares in the fused lane give the same table, so the per-query null scan - * is unnecessary for those shapes. Consumers that read the lane as a value + * equality compares in the fused lane give the same table. Ordered compares + * must use lexical ranks (#738), so they now take the vocabulary-LUT path. + * Consumers that read the lane as a value * (ISNULL, CAST, arithmetic) still need the proof and must bail. */ /* SYM column at the given width: "a","b",NULL,"a","c",NULL,"b","a","c" */ @@ -1474,7 +1476,7 @@ static test_result_t test_diff_sym_nulls_cmp_const(void) { }; test_result_t r = { TEST_PASS, NULL }; for (size_t i = 0; i < sizeof(builders) / sizeof(builders[0]) && r.status == TEST_PASS; i++) - r = diff_run(tbl, builders[i], true); + r = diff_run(tbl, builders[i], i < 2 || i == 6); ray_release(tbl); ray_sym_destroy(); ray_heap_destroy(); return r; } @@ -1628,7 +1630,221 @@ static test_result_t test_zone_skip_keeps_nulls_fused_pred(void) { PASS(); } +/* #738: vocabularies deliberately disagree with lexical order and with + * each other. Check actual lexical answers, not just fused/fallback parity. */ +static ray_t* sym_order_test_vec(ray_sym_domain_t* dom, uint8_t width, + int64_t n, bool right) { + const char* left_names[] = {"zz", "mm", "", "aa", "mm"}; + const char* right_names[] = {"mm", "zz", "", "mm", "aa"}; + const char** names = right ? right_names : left_names; + ray_t* v = ray_sym_vec_new(width, n); + if (!v || RAY_IS_ERR(v)) return v; + ray_sym_domain_retain(dom); + v->sym_domain = dom; + v->len = n; + for (int64_t i = 0; i < n; i++) { + int64_t id = ray_sym_domain_find(dom, names[i % 5], strlen(names[i % 5])); + ray_write_sym(ray_data(v), i, id, RAY_SYM, width); + if (id == 0) ray_vec_set_null(v, i, true); + } + return v; +} + +static test_result_t test_sym_ordered_domains_widths(void) { + ray_heap_init(); (void)ray_sym_init(); + ray_sym_domain_t* d1 = ray_sym_domain_new(); + ray_sym_domain_t* d2 = ray_sym_domain_new(); + TEST_ASSERT(d1 && d2, "private domains"); + const char* a[] = {"zz", "mm", "aa"}; + const char* b[] = {"aa", "zz", "mm"}; + for (int i = 0; i < 3; i++) { + TEST_ASSERT(ray_sym_intern(a[i], 2) >= 0, "runtime intern"); + TEST_ASSERT(ray_sym_domain_intern(d1, a[i], 2) >= 0, "left intern"); + TEST_ASSERT(ray_sym_domain_intern(d2, b[i], 2) >= 0, "right intern"); + } + typedef ray_op_t* (*cmp_ctor_t)(ray_graph_t*, ray_op_t*, ray_op_t*); + const cmp_ctor_t ctors[] = {ray_lt, ray_le, ray_gt, ray_ge}; + const int lr[] = {3, 2, 0, 1, 2}, rr[] = {2, 3, 0, 2, 1}; + for (int domains = 0; domains < 3; domains++) { + ray_sym_domain_t* ld = domains == 0 ? ray_sym_runtime_domain() : d1; + ray_sym_domain_t* rd = domains == 2 ? d2 : ld; + for (uint8_t width = RAY_SYM_W8; width <= RAY_SYM_W64; width++) { + int64_t n = domains == 2 && width == RAY_SYM_W16 ? 50000 : 5; + ray_t* l = sym_order_test_vec(ld, width, n, false); + ray_t* r = sym_order_test_vec(rd, RAY_SYM_W64, n, true); + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("s", 1), l); + tbl = ray_table_add_col(tbl, ray_sym_intern("t", 1), r); + TEST_ASSERT(tbl && !RAY_IS_ERR(tbl), "symbol table"); + for (int k = 0; k < 4; k++) { + /* Column, present string, absent string, null string, + * and a length-one SYM vector from another domain. */ + for (int mode = 0; mode < 5; mode++) { + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* rhs; + ray_t* one = NULL; + if (mode == 0) rhs = ray_scan(g, "t"); + else if (mode == 4) { + one = sym_order_test_vec(rd, RAY_SYM_W32, 1, true); + rhs = ray_const_vec(g, one); + } else { + const char* lit = mode == 1 ? "mm" : mode == 2 ? "nn" : ""; + rhs = ray_const_str(g, lit, strlen(lit)); + } + ray_op_t* pred = ctors[k](g, ray_scan(g, "s"), rhs); + ray_t* out = ray_execute(g, pred); + TEST_ASSERT(out && !RAY_IS_ERR(out), "ordered result"); + TEST_ASSERT_EQ_I(out->type, RAY_BOOL); + TEST_ASSERT_EQ_I(out->len, n); + for (int64_t i = 0; i < n; i++) { + int left = lr[i % 5] * 2; + int right = mode == 0 ? rr[i % 5] * 2 : + mode == 2 ? 5 : mode == 3 ? 0 : 4; + bool want = k == 0 ? left < right : k == 1 ? left <= right : + k == 2 ? left > right : left >= right; + TEST_ASSERT_FMT(((bool*)ray_data(out))[i] == want, + "domain=%d width=%u op=%d mode=%d row=%lld", + domains, width, k, mode, (long long)i); + } + ray_release(out); + ray_graph_free(g); + ray_release(one); + } + } + ray_release(l); ray_release(r); ray_release(tbl); + } + } + ray_sym_domain_release(d1); ray_sym_domain_release(d2); + ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + +/* Ordered partition keys must not prune segments by raw intern id. Also + * exercise a parted SYM data column with a different width per segment. */ +static test_result_t test_sym_ordered_partitions(void) { + ray_heap_init(); (void)ray_sym_init(); + (void)ray_sym_intern("zz", 2); + int64_t mm = ray_sym_intern("mm", 2); + (void)ray_sym_intern("aa", 2); + ray_t* keys = sym_order_test_vec(ray_sym_runtime_domain(), RAY_SYM_W64, 5, false); + int64_t counts[] = {2, 2, 2, 2, 2}; + ray_t* mc = ray_alloc(2 * sizeof(ray_t*)); + mc->type = RAY_MAPCOMMON; mc->len = 2; + ((ray_t**)ray_data(mc))[0] = keys; + ((ray_t**)ray_data(mc))[1] = ray_vec_from_raw(RAY_I64, counts, 5); + ray_t* vals = ray_alloc(5 * sizeof(ray_t*)); + vals->type = RAY_PARTED_BASE + RAY_I64; vals->len = 5; + ray_t* syms = ray_alloc(5 * sizeof(ray_t*)); + syms->type = RAY_PARTED_BASE + RAY_SYM; syms->len = 5; + for (int i = 0; i < 5; i++) { + int64_t rows[] = {2 * i, 2 * i + 1}; + ((ray_t**)ray_data(vals))[i] = ray_vec_from_raw(RAY_I64, rows, 2); + uint8_t width = (uint8_t)(i % 4); + ray_t* seg = ray_sym_vec_new(width, 2); + seg->len = 2; + int64_t id = ray_read_sym(ray_data(keys), i, RAY_SYM, keys->attrs); + ray_write_sym(ray_data(seg), 0, id, RAY_SYM, width); + ray_write_sym(ray_data(seg), 1, id, RAY_SYM, width); + if (id == 0) { ray_vec_set_null(seg, 0, true); ray_vec_set_null(seg, 1, true); } + ((ray_t**)ray_data(syms))[i] = seg; + } + ray_t* tbl = ray_table_new(3); + tbl = ray_table_add_col(tbl, ray_sym_intern("pkey", 4), mc); + tbl = ray_table_add_col(tbl, ray_sym_intern("val", 3), vals); + tbl = ray_table_add_col(tbl, ray_sym_intern("s", 1), syms); + ray_t* lit = ray_sym(mm); + for (int key = 0; key < 2; key++) { + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* pred = ray_lt(g, ray_scan(g, key ? "pkey" : "s"), ray_const_atom(g, lit)); + ray_op_t* root = ray_filter(g, ray_scan(g, "val"), pred); + ray_op_t* opt = ray_optimize(g, root); + for (uint32_t i = 0; i < g->ext_count; i++) + TEST_ASSERT(!g->ext_nodes[i] || !g->ext_nodes[i]->seg_mask, + "symbol ordering cannot prune by numeric id"); + ray_t* out = ray_execute(g, opt); + TEST_ASSERT(out && !RAY_IS_ERR(out), "parted ordering"); + TEST_ASSERT_EQ_I(out->type, RAY_I64); + TEST_ASSERT_EQ_I(out->len, 4); + for (int i = 0; i < 4; i++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(out))[i], i + 4); + ray_release(out); ray_graph_free(g); + } + ray_release(lit); ray_release(mc); ray_release(vals); ray_release(syms); ray_release(tbl); + ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + +/* A few used ids spread across a much larger domain exercise sparse-map + * growth, union ranking, and scalar broadcasts without runtime interning. */ +static test_result_t test_sym_ordered_sparse_no_intern(void) { + ray_heap_init(); (void)ray_sym_init(); + ray_sym_domain_t* dom[2] = {ray_sym_domain_new(), ray_sym_domain_new()}; + TEST_ASSERT(dom[0] && dom[1], "domains"); + enum { VOCAB = 70001, PERIOD = 257, N = 50003 }; + char buf[64]; + for (int side = 0; side < 2; side++) { + for (int i = 0; i < VOCAB; i++) { + int value = side ? VOCAB - 1 - i : i; + int len = snprintf(buf, sizeof(buf), "common-prefix-%05d", value); + TEST_ASSERT(ray_sym_domain_intern(dom[side], buf, (size_t)len) >= 0, "intern fixture"); + } + } + ray_t* col[2]; + int values[2][N]; + for (int side = 0; side < 2; side++) { + col[side] = ray_sym_vec_new(side ? RAY_SYM_W64 : RAY_SYM_W32, N); + TEST_ASSERT(col[side] && !RAY_IS_ERR(col[side]), "column"); + col[side]->len = N; + ray_sym_domain_retain(dom[side]); col[side]->sym_domain = dom[side]; + for (int i = 0; i < N; i++) { + int j = i % PERIOD; + int value = j % 31 == 0 ? -1 : (j * (side ? 521 : 271)) % VOCAB; + values[side][i] = value; + int64_t id = value < 0 ? 0 : side ? VOCAB - value : value + 1; + ray_write_sym(ray_data(col[side]), i, id, RAY_SYM, col[side]->attrs); + } + } + uint32_t before = ray_sym_count(); + const uint16_t ops[] = {OP_LT, OP_LE, OP_GT, OP_GE}; + for (int k = 0; k < 4; k++) { + ray_t* out = exec_sym_order(ops[k], col[0], col[1], false, false); + TEST_ASSERT(out && !RAY_IS_ERR(out), "sparse union ranks"); + for (int i = 0; i < N; i++) { + int l = values[0][i], r = values[1][i]; + bool want = k == 0 ? l < r : k == 1 ? l <= r : k == 2 ? l > r : l >= r; + TEST_ASSERT_EQ_I(((bool*)ray_data(out))[i], want); + } + ray_release(out); + } + for (int q = 0; q < 64; q++) { + int value = 30000 + q; + int len = snprintf(buf, sizeof(buf), "common-prefix-%05d-extra", value); + ray_t* lit = ray_str(buf, (size_t)len); + ray_t* out = exec_sym_order(OP_LT, col[0], lit, false, true); + TEST_ASSERT(out && !RAY_IS_ERR(out), "sparse literal verdicts"); + for (int i = 0; i < N; i++) + TEST_ASSERT_EQ_I(((bool*)ray_data(out))[i], values[0][i] <= value); + ray_release(out); ray_release(lit); + } + /* A scalar from a FILE-like domain must not translate its vocabulary + * into runtime ids just to obtain the literal's bytes. */ + ray_t* one = ray_vec_slice(col[1], 1, 1); + ray_t* out = exec_sym_order(OP_GT, one, col[0], true, false); + TEST_ASSERT(out && !RAY_IS_ERR(out), "domain scalar broadcast"); + for (int i = 0; i < N; i++) + TEST_ASSERT_EQ_I(((bool*)ray_data(out))[i], values[1][1] > values[0][i]); + TEST_ASSERT_EQ_I(ray_sym_count(), before); + ray_release(out); ray_release(one); + for (int side = 0; side < 2; side++) { + ray_release(col[side]); ray_sym_domain_release(dom[side]); + } + ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + const test_entry_t expr_null_entries[] = { + { "expr_null/sym_ordered_sparse_no_intern", test_sym_ordered_sparse_no_intern, NULL, NULL }, + { "expr_null/sym_ordered_partitions", test_sym_ordered_partitions, NULL, NULL }, + { "expr_null/sym_ordered_domains_widths", test_sym_ordered_domains_widths, NULL, NULL }, { "expr_null/bail_counter", test_expr_bail_counter_nulls, NULL, NULL }, { "expr_null/nullfree_invariance", test_nullfree_stream_unchanged, NULL, NULL }, { "expr_null/diff_i64_add", test_diff_i64_add_nullable_prelanding, NULL, NULL }, diff --git a/test/test_group_extra.c b/test/test_group_extra.c index 6160c460e..98b033d42 100644 --- a/test/test_group_extra.c +++ b/test/test_group_extra.c @@ -48,6 +48,7 @@ #include "ops/internal.h" #include "ops/hll.h" #include "ops/cdfuse.h" +#include "ops/rowsel.h" #include "table/sym.h" #include #include @@ -263,15 +264,9 @@ static test_result_t test_scalar_prod_i64_parallel(void) { * Triggers scalar_accum_row FIRST branch (L1729-1732) and LAST (L1733-1734) * and the OP_FIRST / OP_LAST merge paths (group.c L2698-2703). * - * In the n_keys=0 parallel path, task ranges are assigned dynamically — - * worker_id=0 (main thread) does not guarantee processing row 0. The - * merge checks m->count[0]==0 to pick FIRST from another worker, but - * worker 0 always has count>0, so the merge for FIRST/LAST is unreliable - * when row 0 is processed by a background worker. - * - * To make the assertions deterministic regardless of scheduling, we use a - * constant column (all values = 42). FIRST and LAST both return 42 no - * matter which worker processes which row. + * A constant column (all values = 42): FIRST and LAST both return 42. + * Distinct values, nulls spanning whole chunks and every pool size are + * covered by reduction_bits_any_pool below. * -------------------------------------------------------------------------- */ static test_result_t test_scalar_first_last_parallel(void) { ray_heap_init(); @@ -822,6 +817,279 @@ static test_result_t test_reduction_var_i64_parallel(void) { PASS(); } +/* -------------------------------------------------------------------------- + * Test 12b: keyless reductions give the same bits at any pool size, run + * after run + * + * Pooled keyless reductions — exec_reduction and exec_group's n_keys==0 + * scan — kept one accumulator per worker. Under dynamic dispatch the rows + * a worker claimed changed from run to run, so a float sum associated + * differently on every call: on values whose partial sums overflow or + * cancel, (sum p) came out 3.2, 0 or 0Nf. Partials now belong to chunks + * whose shape depends on the row count alone and fold in chunk order, so + * every pool size, the serial one included, gives the same bits. The + * keyless scan's FIRST/LAST follow the same chunk order (they used to force + * a serial scan), so their values are checked as well. + * + * Columns: + * p MAX, -MAX, 3.2 repeating partial sums overflow + * c 1e16, 1, -1e16 repeating partial sums cancel + * a 2^53, then 1s a 1 is lost next to 2^53, not + * next to other 1s: the sum moves + * with every split of the rows + * z +0 / -0 on even rows, i on odd min is a signed-zero tie + * w -z max is a signed-zero tie + * f null on the first and last RD_EDGE rows (several chunks), i + 0.5 + * q I64 3i + 1, no nulls (FIRST/LAST without non-null counters) + * -------------------------------------------------------------------------- */ +#define RD_N 131073 /* 17 chunks of 8192 rows */ +#define RD_WIDE 8400001 /* past 1024 chunks: 16384-row chunks */ +#define RD_EDGE 20000 +#define RD_MAX 64 + +static ray_t* rd_add_f64(ray_t* tbl, const char* name, int64_t n) { + static const double pp[3] = { DBL_MAX, -DBL_MAX, 3.2 }; + static const double cc[3] = { 1e16, 1.0, -1e16 }; + ray_t* v = ray_vec_new(RAY_F64, n); + if (!v || RAY_IS_ERR(v)) return NULL; + v->len = n; + double* d = (double*)ray_data(v); + for (int64_t i = 0; i < n; i++) { + double zi = (i & 1) ? (double)i : ((i & 2) ? -0.0 : 0.0); + switch (name[0]) { + case 'p': d[i] = pp[i % 3]; break; + case 'c': d[i] = cc[i % 3]; break; + case 'a': d[i] = i ? 1.0 : 9007199254740992.0; break; + case 'z': d[i] = zi; break; + case 'w': d[i] = -zi; break; + default: d[i] = (i < RD_EDGE || i >= n - RD_EDGE) ? NAN : (double)i + 0.5; break; + } + } + if (name[0] == 'f') v->attrs |= RAY_ATTR_HAS_NULLS; + tbl = ray_table_add_col(tbl, ray_sym_intern(name, 1), v); + ray_release(v); + return tbl; +} + +/* p, c and a; unless narrow, also z, w, f and q */ +static ray_t* rd_make_table(int64_t n, bool narrow) { + ray_t* tbl = ray_table_new(7); + const char* cols[] = { "p", "c", "a", "z", "w", "f" }; + for (int c = 0; c < (narrow ? 3 : 6) && tbl; c++) tbl = rd_add_f64(tbl, cols[c], n); + if (narrow || !tbl) return tbl; + ray_t* q = ray_vec_new(RAY_I64, n); + if (!q || RAY_IS_ERR(q)) return NULL; + q->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(q))[i] = 3 * i + 1; + tbl = ray_table_add_col(tbl, ray_sym_intern("q", 1), q); + ray_release(q); + return tbl; +} + +/* Rows a where: keeps — drops every fifth row and every fourth 8192-row + * stretch whole. */ +static bool rd_pass(int64_t i) { return i % 5 != 2 && (i / 8192) % 4 != 1; } + +static ray_t* rd_make_sel(int64_t n) { + ray_t* pred = ray_vec_new(RAY_BOOL, n); + if (!pred || RAY_IS_ERR(pred)) return NULL; + pred->len = n; + for (int64_t i = 0; i < n; i++) ((uint8_t*)ray_data(pred))[i] = rd_pass(i); + ray_t* sel = ray_rowsel_from_pred(pred); + ray_release(pred); + return sel; +} + +/* (op col), through the DAG; with sel, exec_reduction under that where: */ +static ray_t* rd_reduce(ray_t* tbl, const char* col, uint16_t opc, ray_t* sel) { + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return NULL; + ray_op_t* in = ray_scan(g, col); + ray_op_t* op = opc == OP_SUM ? ray_sum(g, in) : opc == OP_AVG ? ray_avg(g, in) + : opc == OP_VAR_POP ? ray_var_pop(g, in) : opc == OP_MIN ? ray_min_op(g, in) + : opc == OP_MAX ? ray_max_op(g, in) : opc == OP_FIRST ? ray_first(g, in) + : ray_last(g, in); + ray_t* out; + if (sel) { + g->selection = sel; + out = exec_reduction(g, op, ray_table_get_col(tbl, ray_sym_intern(col, 1))); + g->selection = NULL; + } else { + out = ray_execute(g, op); + } + if (out && !RAY_IS_ERR(out) && ray_is_lazy(out)) out = ray_lazy_materialize(out); + ray_graph_free(g); + return out; +} + +/* select {a0:(op0 col0) a1:(op1 col1) ...} with no by:, optionally under sel */ +static ray_t* rd_keyless(ray_t* tbl, const char* cols, const uint16_t* ops, + uint32_t n_aggs, ray_t* sel) { + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return NULL; + ray_op_t* ins[8]; + uint16_t o[8]; + for (uint32_t a = 0; a < n_aggs; a++) { + char name[2] = { cols[a], 0 }; + ins[a] = ray_scan(g, name); + o[a] = ops[a]; + } + ray_op_t* grp = ray_group(g, NULL, 0, o, ins, n_aggs); + ray_t* out; + if (sel) { + g->selection = sel; + out = exec_group(g, grp, tbl, 0); + g->selection = NULL; + } else { + out = ray_execute(g, grp); + } + if (out && !RAY_IS_ERR(out) && ray_is_lazy(out)) out = ray_lazy_materialize(out); + ray_graph_free(g); + return out; +} + +/* Append the bits of an atom, or of every cell of a 1-row table, to out; + * the new count, or -1 for an error result. */ +static int rd_put(ray_t* r, uint64_t* out, int k) { + if (k < 0 || !r || RAY_IS_ERR(r)) return -1; + if (r->type == RAY_TABLE) { + int64_t nc = ray_table_ncols(r); + if (ray_table_nrows(r) != 1 || k + nc > RD_MAX) { ray_release(r); return -1; } + for (int64_t c = 0; c < nc; c++) + memcpy(&out[k++], ray_data(ray_table_get_col_idx(r, c)), sizeof(uint64_t)); + } else { + if (k >= RD_MAX) { ray_release(r); return -1; } + memcpy(&out[k++], &r->i64, sizeof(uint64_t)); + } + ray_release(r); + return k; +} + +static double rd_f64(uint64_t bits) { double d; memcpy(&d, &bits, sizeof d); return d; } + +/* Every reduction under test, in a fixed order, into out[0 .. *n_out); + * the order-defined ones (first/last, signed-zero extrema) are checked + * against their values. */ +static test_result_t rd_collect(ray_t* tbl, ray_t* sel, int64_t n, bool narrow, + uint64_t* out, int* n_out) { + static const uint16_t sums[] = { OP_SUM, OP_AVG, OP_VAR_POP }; + int k = 0; + if (narrow) { /* the single-pass kernels only: big inputs */ + k = rd_put(rd_reduce(tbl, "p", OP_SUM, NULL), out, k); + k = rd_put(rd_reduce(tbl, "a", OP_SUM, NULL), out, k); + k = rd_put(rd_reduce(tbl, "c", OP_AVG, NULL), out, k); + k = rd_put(rd_keyless(tbl, "a", (const uint16_t[]){ OP_SUM }, 1, NULL), out, k); + k = rd_put(rd_reduce(tbl, "a", OP_SUM, sel), out, k); + TEST_ASSERT(k > 0, "keyless reduction failed"); + *n_out = k; + PASS(); + } + for (int c = 0; c < 3; c++) + for (int o = 0; o < 3; o++) + k = rd_put(rd_reduce(tbl, c == 0 ? "p" : c == 1 ? "c" : "a", sums[o], NULL), out, k); + k = rd_put(rd_keyless(tbl, "p", (const uint16_t[]){ OP_SUM }, 1, NULL), out, k); + k = rd_put(rd_keyless(tbl, "a", (const uint16_t[]){ OP_SUM }, 1, NULL), out, k); + k = rd_put(rd_keyless(tbl, "ccaa", (const uint16_t[]){ OP_SUM, OP_VAR_POP, OP_SUM, OP_AVG }, 4, NULL), out, k); + k = rd_put(rd_reduce(tbl, "c", OP_SUM, sel), out, k); + k = rd_put(rd_reduce(tbl, "a", OP_SUM, sel), out, k); + k = rd_put(rd_keyless(tbl, "pca", (const uint16_t[]){ OP_SUM, OP_SUM, OP_VAR_POP }, 3, sel), out, k); + TEST_ASSERT(k > 0, "keyless reduction failed"); + + int kv = k; /* order-defined results start here */ + static const uint16_t ord[] = { OP_MIN, OP_MAX, OP_FIRST, OP_LAST, OP_FIRST, OP_LAST }; + static const char ord_cols[] = "zwffqq"; + for (int o = 0; o < 6; o++) { + char col[2] = { ord_cols[o], 0 }; + k = rd_put(rd_reduce(tbl, col, ord[o], NULL), out, k); + } + k = rd_put(rd_keyless(tbl, ord_cols, ord, 6, NULL), out, k); + k = rd_put(rd_keyless(tbl, "qqp", (const uint16_t[]){ OP_FIRST, OP_LAST, OP_SUM }, 3, NULL), out, k); + k = rd_put(rd_keyless(tbl, "zffp", (const uint16_t[]){ OP_MIN, OP_FIRST, OP_LAST, OP_SUM }, 4, sel), out, k); + TEST_ASSERT(k > 0, "keyless reduction failed"); + + int64_t f_first = RD_EDGE, f_last = n - RD_EDGE - 1; + int64_t s_first = f_first, s_last = f_last; + while (!rd_pass(s_first)) s_first++; + while (!rd_pass(s_last)) s_last--; + for (int set = 0; set < 2; set++) { /* the vector forms, then the keyless scan */ + const uint64_t* v = out + kv + 6 * set; + TEST_ASSERT_FMT(rd_f64(v[0]) == 0.0 && rd_f64(v[1]) == 0.0, + "set %d: min/max of a signed-zero tie gave %g / %g", + set, rd_f64(v[0]), rd_f64(v[1])); + TEST_ASSERT_FMT(rd_f64(v[2]) == (double)f_first + 0.5 && rd_f64(v[3]) == (double)f_last + 0.5, + "set %d: first/last f gave %.1f / %.1f", set, rd_f64(v[2]), rd_f64(v[3])); + TEST_ASSERT_FMT((int64_t)v[4] == 1 && (int64_t)v[5] == 3 * (n - 1) + 1, + "set %d: first/last q gave %lld / %lld", + set, (long long)v[4], (long long)v[5]); + } + const uint64_t* v = out + kv + 12; + TEST_ASSERT_FMT((int64_t)v[0] == 1 && (int64_t)v[1] == 3 * (n - 1) + 1, + "keyless first/last q (no non-null counters) gave %lld / %lld", + (long long)v[0], (long long)v[1]); + v = out + kv + 15; + TEST_ASSERT_FMT(rd_f64(v[0]) == 0.0, "selected min z gave %g", rd_f64(v[0])); + TEST_ASSERT_FMT(rd_f64(v[1]) == (double)s_first + 0.5 && rd_f64(v[2]) == (double)s_last + 0.5, + "selected first/last f gave %.1f / %.1f, expected %.1f / %.1f", + rd_f64(v[1]), rd_f64(v[2]), (double)s_first + 0.5, (double)s_last + 0.5); + *n_out = k; + PASS(); +} + +static test_result_t rd_check_pools(int64_t n, bool narrow, const uint32_t* pools, + int n_pools, int reps) { + ray_heap_init(); + (void)ray_sym_init(); + uint32_t cores = ray_pool_total_workers(ray_pool_get()); + ray_t* tbl = rd_make_table(n, narrow); + ray_t* sel = rd_make_sel(n); + test_result_t res = { TEST_PASS, NULL }; + if (!tbl || RAY_IS_ERR(tbl) || !sel) res = (test_result_t){ TEST_FAIL, "fixture" }; + uint64_t ref[RD_MAX], got[RD_MAX]; + int n_ref = 0, n_got = 0; + for (int p = 0; p < n_pools && res.status == TEST_PASS; p++) { + ray_pool_destroy(); + ray_pool_init_total(pools[p]); + for (int rep = 0; rep < reps && res.status == TEST_PASS; rep++) { + bool first_run = p == 0 && rep == 0; + res = rd_collect(tbl, sel, n, narrow, first_run ? ref : got, + first_run ? &n_ref : &n_got); + if (res.status != TEST_PASS || first_run) continue; + for (int i = 0; i < n_ref; i++) { + if (n_got == n_ref && got[i] == ref[i]) continue; + snprintf(ray_test_fail_buf, sizeof ray_test_fail_buf, + "%lld rows, pool %u run %d: result %d is %016llx (%.17g), " + "pool %u run 0 gave %016llx (%.17g)", + (long long)n, pools[p], rep, i, (unsigned long long)got[i], + rd_f64(got[i]), pools[0], (unsigned long long)ref[i], rd_f64(ref[i])); + res = (test_result_t){ TEST_FAIL, ray_test_fail_buf }; + break; + } + } + } + ray_pool_destroy(); + ray_pool_init_total(cores); + if (sel) ray_rowsel_release(sel); + if (tbl && !RAY_IS_ERR(tbl)) ray_release(tbl); + /* The wide columns' freed mappings would otherwise sit in the direct + * reuse cache and serve later tests' size-matched requests. */ + ray_heap_direct_cache_drain(); + ray_sym_destroy(); + ray_heap_destroy(); + return res; +} + +static test_result_t test_reduction_bits_any_pool(void) { + static const uint32_t pools[] = { 1, 2, 5, 8 }; + return rd_check_pools(RD_N, false, pools, 4, 2); +} + +/* The same past 1024 chunks, where each chunk spans several 8192-row + * blocks. */ +static test_result_t test_reduction_bits_wide_chunks(void) { + static const uint32_t pools[] = { 1, 5 }; + return rd_check_pools(RD_WIDE, true, pools, 2, 2); +} + /* -------------------------------------------------------------------------- * Test 13: count_distinct parallel path runs on every flat numeric type * @@ -2747,6 +3015,8 @@ const test_entry_t group_extra_entries[] = { { "group_extra/count_distinct_small_types", test_count_distinct_small_types, NULL, NULL }, { "group_extra/reduction_prod_parallel", test_reduction_prod_parallel, NULL, NULL }, { "group_extra/reduction_var_i64_parallel", test_reduction_var_i64_parallel, NULL, NULL }, + { "group_extra/reduction_bits_any_pool", test_reduction_bits_any_pool, NULL, NULL }, + { "group_extra/reduction_bits_wide_chunks", test_reduction_bits_wide_chunks, NULL, NULL }, { "group_extra/count_distinct_parallel_types", test_count_distinct_parallel_types, NULL, NULL }, { "group_extra/count_distinct_per_group_parallel", test_count_distinct_per_group_parallel, NULL, NULL }, { "group_extra/i16_group_top_count_emit_filter", test_i16_group_top_count_emit_filter, NULL, NULL }, diff --git a/test/test_heap.c b/test/test_heap.c index 0b7149a42..c7fb16a13 100644 --- a/test/test_heap.c +++ b/test/test_heap.c @@ -41,8 +41,12 @@ #include "test.h" #include #include "mem/heap.h" +#include "mem/sys.h" /* ray_sys_alloc: off-heap blocks and the watermark */ #include "core/platform.h" #include "core/pool.h" +#include "core/runtime.h" /* __RUNTIME->mem_cg: the cgroup files read */ +#include "lang/internal.h" /* ray_gc_fn: (.sys.gc) is a statement boundary */ +#include "core/timer.h" /* ray_time_now_ms: the far-visit limit */ /* Restore the shipped policy after a test drives it. */ #define RAY_HEAP_DECAY_MS_TEST_DEFAULT 10000 @@ -79,6 +83,9 @@ static int munmap(void* p, size_t len) { #include #include /* fstat: spill-file link count */ #endif +#if defined(__linux__) +#include /* IN_ACCESS: when the cgroup files are read */ +#endif #include #include @@ -1424,7 +1431,7 @@ static test_result_t test_alloc_copy_dict_block(void) { * Test: exercise ray_release_owned_refs LAMBDA branch by building a * properly-sized LAMBDA block and releasing it. */ -#include "lang/eval.h" /* LAMBDA_NFO, LAMBDA_DBG */ +#include "lang/eval.h" /* LAMBDA_SLOTS, LAMBDA_NFO, LAMBDA_DBG */ static test_result_t test_release_lambda_owned_refs(void) { /* Lambda data layout: 7 ray_t* slots. @@ -1433,11 +1440,12 @@ static test_result_t test_release_lambda_owned_refs(void) { * data[5] = NFO (ray_t*) * data[6] = DBG (ray_t*) * - * Alloc enough for 7 pointers. ray_alloc_copy treats lambda as atom + * Alloc the full LAMBDA_SLOTS layout (the heap walks every pointer + * slot on free). ray_alloc_copy treats lambda as atom * (data_size=0) so we can't use it here. Instead: alloc, set type, * give children rc=2 so they survive one release, then ray_free(lam) * which calls ray_release_owned_refs → LAMBDA branch. */ - size_t lam_data = 7 * sizeof(ray_t*); + size_t lam_data = LAMBDA_SLOTS * sizeof(ray_t*); ray_t* lam = ray_alloc(lam_data); TEST_ASSERT_NOT_NULL(lam); lam->type = RAY_LAMBDA; @@ -1931,7 +1939,7 @@ static test_result_t test_retain_owned_refs_lambda_null_slots(void) { /* LAMBDA branch (L611-619): mix of NULL and live child slots exercises * both sides of the `slots[i] && !RAY_IS_ERR(slots[i])` guard and the * `if (LAMBDA_NFO/DBG)` NULL guards. */ - size_t lam_data = 7 * sizeof(ray_t*); + size_t lam_data = LAMBDA_SLOTS * sizeof(ray_t*); ray_t* lam = ray_alloc(lam_data); TEST_ASSERT_NOT_NULL(lam); lam->type = RAY_LAMBDA; @@ -2618,6 +2626,2410 @@ static test_result_t test_direct_cache_replaces_old_blocks(void) { PASS(); } +/* Allocations off the per-thread heaps (ray_sys_alloc: the symbol and domain + * string arenas, index-build scratch) count toward the anonymous watermark, + * and a large one that would cross it is backed by a spill file (#712): it + * reads zero and holds data like any other block, without adding to the + * anonymous footprint. Small ones stay anonymous so tiny blocks never get a + * file each. */ +static test_result_t test_sys_alloc_watermark(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + const size_t big = 8u * 1024 * 1024; + ray_heap_direct_cache_drain(); + int64_t base = ray_heap_anon_committed(); + int64_t previous = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(base + INT64_C(64) * 1024 * 1024); + + uint64_t* a = (uint64_t*)ray_sys_alloc(big); + int64_t with_a = ray_heap_anon_committed(); + bool counted = a && with_a == base + (int64_t)big + 4096; + char* s = (char*)ray_sys_alloc(100); + bool small_counted = s && ray_heap_anon_committed() == with_a + 4096; + ray_sys_free(s); + + ray_heap_set_anon_watermark(with_a + 1024 * 1024); + uint64_t* b = (uint64_t*)ray_sys_alloc(big); + bool spilled = b && ray_heap_anon_committed() == with_a; + bool zero = b != NULL; + if (b) { + for (size_t i = 0; i < big / 8; i += 512) zero = zero && b[i] == 0; + b[big / 8 - 1] = 7; + } + char* t = (char*)ray_sys_alloc(100); + bool small_anon = t && ray_heap_anon_committed() == with_a + 4096; + ray_sys_free(t); + b = (uint64_t*)ray_sys_realloc(b, 2 * big); + bool kept = b && b[big / 8 - 1] == 7 && ray_heap_anon_committed() == with_a; + ray_sys_free(b); + ray_sys_free(a); + bool back = ray_heap_anon_committed() == base; + ray_heap_set_anon_watermark(previous); + TEST_ASSERT_TRUE(counted && small_counted); + TEST_ASSERT_TRUE(spilled && zero && small_anon); + TEST_ASSERT_TRUE(kept && back); + PASS(); +} + +/* ray_sys_alloc memory reads zero in every byte (mem/sys.h; the import + * dictionary's shard tables are not cleared): a small block, a large + * anonymous one and a large spilled one, each also right after a block of + * its size was written all over and freed. */ +static test_result_t test_sys_alloc_zero_fill(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + const size_t sizes[3] = { 8192 + 16, 4u * 1024 * 1024, 4u * 1024 * 1024 }; + int64_t previous = ray_heap_anon_watermark(); + int64_t nonzero = 0, wrong_path = 0; + for (int k = 0; k < 3; k++) { + bool spill = k == 2; + ray_heap_direct_cache_drain(); + int64_t base = ray_heap_anon_committed(); + ray_heap_set_anon_watermark(base + (spill ? INT64_C(1) << 20 : INT64_C(64) << 20)); + for (int round = 0; round < 2; round++) { + uint64_t* p = (uint64_t*)ray_sys_alloc(sizes[k]); + TEST_ASSERT_NOT_NULL(p); + if ((ray_heap_anon_committed() == base) != spill) wrong_path++; + for (size_t i = 0; i < sizes[k] / 8; i++) if (p[i]) nonzero++; + memset(p, 0xa5, sizes[k]); + ray_sys_free(p); + } + } + ray_heap_set_anon_watermark(previous); + TEST_ASSERT_EQ_I(wrong_path, 0); + TEST_ASSERT_EQ_I(nonzero, 0); + PASS(); +} + +/* ray_raw_discard punches out of a spilled block's file the whole pages + * that lie in the range reported — they read zero after — and nothing else: + * not the first page (it holds the headers: the block still frees as a + * direct block), not a page the range only reaches into (it goes with the + * report that covers it), nothing past the block. An anonymous block (the + * direct-block cache keeps it for its next use) and a small one are left as + * they are, and so is everything where the platform cannot punch a mapped + * range (no MADV_REMOVE: macOS) or the spill directory's filesystem cannot + * (NFS, ext3) — the call says whether it did, and the pages read zero + * exactly when it says so. Whether the spill directory can is asked of it + * first (a scratch file there punched with fallocate, which MADV_REMOVE + * does on a mapping): where it can, a spilled block's discard must punch. */ +static bool raw_discard_dir_punches(void) { +#if defined(__linux__) && defined(MADV_REMOVE) && defined(FALLOC_FL_PUNCH_HOLE) + /* the spill directory as ray_heap_init takes it */ + const char* env = getenv("RAY_HEAP_SWAP"); + if (!(env && *env)) env = getenv("TMPDIR"); + const char* dir = env && *env ? env : "/tmp"; + char path[4096]; + if ((size_t)snprintf(path, sizeof(path), "%s/rf_punch_probe_XXXXXX", dir) >= sizeof(path)) return false; + int fd = mkstemp(path); + if (fd < 0) return false; + unlink(path); + long ps = sysconf(_SC_PAGESIZE); + off_t pg = ps > 0 ? (off_t)ps : 4096; + bool ok = fallocate(fd, 0, 0, 4 * pg) == 0 && + fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, pg, 2 * pg) == 0; + close(fd); + return ok; +#else + return false; +#endif +} +static test_result_t test_raw_discard(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + const size_t big = 40u * 1024 * 1024; /* past the pool order: a direct block */ + long ps = sysconf(_SC_PAGESIZE); + size_t pg = ps > 0 ? (size_t)ps : 4096; + int64_t previous = ray_heap_anon_watermark(); + int64_t bad = 0; + bool can_punch = raw_discard_dir_punches(); + for (int k = 0; k < 2; k++) { + bool spill = k == 1; + ray_heap_direct_cache_drain(); + int64_t base = ray_heap_anon_committed(); + ray_mem_stats_t s0; + ray_mem_stats(&s0); + ray_heap_set_anon_watermark(base + (spill ? INT64_C(1) << 20 : INT64_C(256) << 20)); + /* a neighbour mapped first: mappings grow down, so the block maps + * right below it and a report past the block's end would reach it */ + uint8_t* g = (uint8_t*)ray_alloc_raw(big); + TEST_ASSERT_NOT_NULL(g); + memset(g, 0x77, big); + uint8_t* p = (uint8_t*)ray_alloc_raw(big); + TEST_ASSERT_NOT_NULL(p); + ray_t* v = (ray_t*)(p - 32); + if (!ray_is_direct(v) || ray_direct_file_backed(v) != spill) bad++; + memset(p, 0xa5, big); + size_t head = (size_t)((((uintptr_t)p + pg - 1) & ~(uintptr_t)(pg - 1)) - (uintptr_t)p); + /* three and a half pages past the first page boundary: three go */ + size_t upto = head + 3 * pg + pg / 2; + bool punched = ray_raw_discard(p, 0, upto); + if (punched && !spill) bad++; /* an anonymous block is never punched */ + if (spill && can_punch && !punched) { /* the directory punches: so must the discard */ + fprintf(stderr, " raw_discard: the spill directory punches a scratch file, the discard did not\n"); + bad++; + } + for (size_t i = 0; i < big; i += 64) + if ((p[i] == 0) != (punched && i >= head && i < head + 3 * pg)) { bad++; break; } + /* the next report takes the page the first one reached into */ + if (ray_raw_discard(p, upto, head + 6 * pg) != punched) bad++; + for (size_t i = 0; i < big; i += 64) + if ((p[i] == 0) != (punched && i >= head && i < head + 6 * pg)) { bad++; break; } + /* a report past the end stops at the block */ + if (ray_raw_discard(p, head + 6 * pg, big + big / 2) != punched) bad++; + for (size_t i = 0; i < big; i += 64) + if ((p[i] == 0) != (punched && i >= head)) { bad++; break; } + for (size_t i = 0; i < big; i += 64) if (g[i] != 0x77) { bad++; break; } + if (v->type != RAY_U8 || v->len != (int64_t)big) bad++; + ray_free_raw(p); + ray_free_raw(g); + ray_heap_direct_cache_drain(); + if (ray_heap_anon_committed() != base) bad++; + ray_mem_stats_t s1; /* both freed as direct blocks, their mappings gone */ + ray_mem_stats(&s1); + if (s1.direct_bytes != s0.direct_bytes || s1.direct_count != s0.direct_count) bad++; + } + ray_heap_set_anon_watermark(previous); + uint8_t* s = (uint8_t*)ray_alloc_raw(64 * 1024); /* a buddy block: left alone */ + TEST_ASSERT_NOT_NULL(s); + memset(s, 0x5a, 64 * 1024); + if (ray_raw_discard(s, 0, 64 * 1024)) bad++; + for (size_t i = 0; i < 64 * 1024; i++) if (s[i] != 0x5a) { bad++; break; } + ray_free_raw(s); + TEST_ASSERT_EQ_I(bad, 0); + /* Everything above held; but where the spill directory cannot punch (no + * MADV_REMOVE, or a filesystem such as NFS or ext3: its probe failed) + * the pages that should go were only checked to stay. */ + if (!can_punch) SKIP("spill directory cannot punch a mapped range: the zeroing was not checked"); + PASS(); +} + +/* ---- Statement-boundary relief (ray_heap_relieve) ---------------------- + * + * The relief works on the calling thread's heap and the parked pool + * workers'. Each test below runs on a heap of its own with no pools, so it + * knows where its blocks land: in a fresh heap an order-24 block is the + * right half of a pool of its own (the only free order-24 block a pool has), + * and a smaller block comes from the cascade of the pool mapped last. */ + +#define RELIEVE_MB (INT64_C(1) << 20) +#define RELIEVE_POOL ((int64_t)BSIZEOF(RAY_HEAP_POOL_ORDER)) +#define RELIEVE_HALF ((16u << 20) - 4096) /* order 24: half a pool */ + +typedef struct { + ray_heap_t* base; /* the test thread's own heap */ + ray_heap_t* parked[32]; /* abandoned heaps taken off the idle list */ + int n; + int64_t wm; /* the watermark to restore */ + ray_runtime_t* rt; /* the runtime to restore (heap tests run without) */ + ray_runtime_t saved; /* and its cgroup directory */ + char cg[64]; /* the cgroup directory relieve_cgroup fakes */ +} relieve_env_t; + +/* Make a new heap with no pools current, or return NULL. ray_heap_init + * hands out an abandoned heap before it maps a new one, so those are taken + * off the idle list on the way and put back by relieve_env_end. */ +static ray_heap_t* relieve_heap_new(relieve_env_t* e) { + for (;;) { + ray_tl_heap = NULL; + ray_heap_init(); + ray_heap_t* h = ray_tl_heap; + if (!h || h->pool_count == 0) return h; + if (e->n == 32) { ray_heap_abandon(); return NULL; } + e->parked[e->n++] = h; + } +} + +static bool relieve_pool_is_backed(ray_heap_t* h, const void* blk) { + int p = heap_find_pool(h, blk); + return p >= 0 && h->pools[p].backed; +} + +/* A spill that is none of the current heap's: a pool mapped past the + * watermark — lowered for it, then put back — by a heap of its own, made and + * destroyed here. The relief acts only after a spill (ray_heap_relieve), + * and a large block's spill would not do: before it spills it drains the + * direct-block cache and the caller's empty pools (heap_make_room). True + * if the pool spilled. */ +static bool relieve_spill_elsewhere(relieve_env_t* e) { + ray_heap_t* cur = ray_tl_heap; + int64_t wm = ray_heap_anon_watermark(); + ray_heap_t* s = relieve_heap_new(e); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_t* b = s ? ray_alloc(RELIEVE_HALF) : NULL; + bool spilled = b && relieve_pool_is_backed(s, b); + if (s) ray_heap_destroy(); + ray_heap_set_anon_watermark(wm); + ray_tl_heap = cur; + return spilled; +} + +/* Start from a known room: no cached direct blocks, and no empty pool left + * in a worker heap beyond its last (a relief that finds one hands it back + * here, so later room comes only from what the test builds). The + * watermark is unbounded until the test sets one. */ +static void relieve_env_begin(relieve_env_t* e) { + e->base = ray_tl_heap; + e->n = 0; + e->wm = ray_heap_anon_watermark(); + static ray_runtime_t bare; /* no cgroup directory */ + e->rt = __RUNTIME; + if (!__RUNTIME) __RUNTIME = &bare; + e->saved = *__RUNTIME; + snprintf(e->cg, sizeof(e->cg), "/tmp/rayforce_relieve_%d", (int)getpid()); + ray_heap_direct_cache_drain(); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + relieve_spill_elsewhere(e); + ray_heap_relieve(); + ray_heap_direct_cache_drain(); + ray_heap_set_anon_watermark(INT64_C(1) << 40); +} + +#if defined(__linux__) +static void relieve_write(const char* path, const char* text) { + int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (fd < 0) return; + ssize_t n = write(fd, text, strlen(text)); + (void)n; + close(fd); +} +#endif + +#if defined(__linux__) +/* A cgroup directory of the test's own, with a memory.stat, where the + * runtime is pointed (ray_sys_mem_flush). relieve_cgroup_ok, or + * relieve_env_end, puts the runtime back. */ +static void relieve_cgroup(relieve_env_t* e) { +#if !defined(_WIN32) + char path[128]; + mkdir(e->cg, 0700); + snprintf(path, sizeof(path), "%s/memory.stat", e->cg); + relieve_write(path, "anon 1\nfile 0\n"); +#endif + snprintf(__RUNTIME->mem_cg, sizeof(__RUNTIME->mem_cg), "%s", e->cg); +} +#endif +/* A boundary far from the watermark that visits the heaps: one does at most + * every so often (ray_heap_relieve), or at the first after the watermark is + * set, as here. */ +static void relieve_far(void) { + ray_heap_set_anon_watermark(ray_heap_anon_watermark()); + ray_heap_relieve(); +} +static void relieve_cgroup_ok(relieve_env_t* e) { + memcpy(__RUNTIME->mem_cg, e->saved.mem_cg, sizeof(e->saved.mem_cg)); +} +static void relieve_cgroup_clean(relieve_env_t* e) { +#if !defined(_WIN32) + char path[128]; + snprintf(path, sizeof(path), "%s/memory.stat", e->cg); + unlink(path); + rmdir(e->cg); +#else + (void)e; +#endif +} +/* Destroy the test's heaps (current first), then put the parked ones back. */ +static void relieve_env_end(relieve_env_t* e, ray_heap_t* h1, ray_heap_t* h2) { + if (h1) { ray_tl_heap = h1; ray_heap_destroy(); } + if (h2) { ray_tl_heap = h2; ray_heap_destroy(); } + for (int i = e->n; i-- > 0; ) { + ray_tl_heap = e->parked[i]; + ray_heap_abandon(); + } + ray_tl_heap = e->base; + relieve_cgroup_ok(e); + relieve_cgroup_clean(e); + ray_heap_set_anon_watermark(e->wm); + __RUNTIME = e->rt; +} + +/* Pressure the relief can act on: the next pool would cross the watermark, + * and `room` bytes given back bring it under again. */ +static void relieve_pressure(int64_t room) { + ray_heap_set_anon_watermark(ray_heap_anon_committed() - room + RELIEVE_POOL); +} + +static int relieve_backed_pools(ray_heap_t* h) { + int n = 0; + for (uint32_t p = 0; p < h->pool_count; p++) n += h->pools[p].backed; + return n; +} + +/* The parked pools of h: -1 if the count disagrees with the flags. */ +static int relieve_parked(ray_heap_t* h) { + uint32_t n = 0; + for (uint32_t p = 0; p < h->pool_count; p++) n += h->pools[p].parked; + return n == h->parked ? (int)n : -1; +} + +/* 1 if the page holding p is resident, 0 if not, -1 if this platform cannot + * tell (macOS releases with MADV_FREE, which leaves pages resident until the + * kernel wants them). */ +static int relieve_resident(const void* p) { +#if defined(__linux__) + long ps = sysconf(_SC_PAGESIZE); + uintptr_t a = (uintptr_t)p & ~(uintptr_t)(ps - 1); + unsigned char v = 0; + if (mincore((void*)a, (size_t)ps, &v) != 0) return -1; + return v & 1; +#else + (void)p; + return -1; +#endif +} + +/* Whether residency can be read here at all (mincore): the checks of it + * are skipped where it cannot be — never because the page looked at is + * gone, which reads as -1 and fails them. */ +static bool relieve_mincore(void) { + static char page[8192]; + return relieve_resident(page + 4096) >= 0; +} + +/* A query that needed several pools leaves them mapped and counted after it + * frees everything, so the next one sees the watermark reached. Pressure + * alone parks the empty pools — all but the heap's last, mapped and + * counted still; once a statement has spilled, a boundary unmaps them. + * Below the watermark it leaves them for reuse. */ +static test_result_t test_relieve_under_pressure(void) { +#if defined(_WIN32) + SKIP("no file spill, so no relief: the watermark decides nothing"); +#endif + enum { N = 64 }; + const size_t sz = 1u << 20; /* order 21: 15 to a pool */ + ray_t* blocks[N] = {0}; + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + for (int i = 0; i < N; i++) blocks[i] = ray_alloc(sz); + for (int i = 0; i < N; i++) if (blocks[i]) ray_free(blocks[i]); + uint32_t pools = h->pool_count; + int64_t kept = ray_heap_anon_committed(); + + /* No pressure: nothing is handed back or parked. */ + int64_t r0 = ray_heap_relieve(); + bool idle = r0 == 0 && ray_heap_anon_committed() == kept + && h->pool_count == pools && relieve_parked(h) == 0; + + /* Pressure, no spill: every pool but the last is parked. */ + relieve_pressure(RELIEVE_POOL); + ray_heap_relieve(); + bool parked = h->pool_count == pools && ray_heap_anon_committed() == kept + && relieve_parked(h) == (int)pools - 1; + + /* A spill: every pool but the last goes. */ + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); + bool shrank = h->pool_count == 1 && relieve_parked(h) == 0 + && ray_heap_anon_committed() == kept - (int64_t)(pools - 1) * RELIEVE_POOL; + + /* The heap still allocates after its pools went away. */ + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_t* again = ray_alloc(sz); + bool usable = again != NULL; + if (again) { memset(ray_data(again), 7, sz); ray_free(again); } + relieve_env_end(&e, h, NULL); + if (!spill) SKIP("no spill file"); + TEST_ASSERT(pools >= 4, "64 blocks of 2 MB took several pools"); + TEST_ASSERT(idle, "no pressure, nothing handed back"); + TEST_ASSERT(parked, "pressure alone parked every empty pool but the last"); + TEST_ASSERT(shrank, "after a spill every empty pool but the last went"); + TEST_ASSERT_TRUE(usable); + PASS(); +} + +/* When live data holds the footprint past the watermark, the next statement + * spills whatever the boundary gives back, so giving it back only makes that + * statement map and fault it all again. Then the boundary does nothing, + * spill or not: the direct-block cache keeps its blocks and free blocks keep + * their pages. The same memory goes once handing it back makes room. */ +static test_result_t test_relieve_needs_room(void) { +#if defined(_WIN32) + SKIP("no file spill, so no relief: the watermark decides nothing"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + /* Pool 1 holds x; pool 2 holds s and a free order-24 block, its pages + * faulted in. No pool is empty. */ + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* f = ray_alloc(RELIEVE_HALF); + ray_t* s = ray_alloc(16); + if (!x || !f || !s) { + if (x) ray_free(x); + if (f) ray_free(f); + if (s) ray_free(s); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + bool layout = h->pool_count == 2 && heap_find_pool(h, f) == heap_find_pool(h, s); + memset(ray_data(f), 0xA5, RELIEVE_HALF); + const char* probe = (const char*)f + (4u << 20); + ray_free(f); + + /* A direct block in the reuse cache: room, as far as the watermark goes. */ + int64_t c0 = ray_heap_anon_committed(); + ray_t* d = ray_alloc((size_t)40 << 20); + if (d) { memset(ray_data(d), 1, 4096); ray_free(d); } + int64_t cached = ray_heap_anon_committed() - c0; + + /* After a spill, giving back the cache would still leave the next pool + * over the line. */ + ray_heap_set_anon_watermark(c0); + int64_t before = ray_heap_anon_committed(); + int res0 = relieve_resident(probe); + bool spill = relieve_spill_elsewhere(&e); + int64_t r = ray_heap_relieve(); + bool idle = r == 0 && ray_heap_anon_committed() == before + && relieve_resident(probe) == res0; + + /* With room for a pool after it, the same boundary hands it all back. */ + ray_heap_set_anon_watermark(c0 + RELIEVE_POOL); + spill = relieve_spill_elsewhere(&e) && spill; + r = ray_heap_relieve(); + bool drained = ray_heap_anon_committed() == c0; + int res1 = relieve_resident(probe); + + ray_free(s); + ray_free(x); + relieve_env_end(&e, h, NULL); + if (!spill) SKIP("no spill file"); + TEST_ASSERT(layout, "two pools, the free block next to a live one"); + TEST_ASSERT(cached >= (int64_t)40 << 20, "the direct block was cached"); + TEST_ASSERT(idle, "no room to make, nothing handed back"); + if (relieve_mincore()) { + TEST_ASSERT(res0 == 1, "the free block's pages were resident"); + TEST_ASSERT(res1 == 0, "and were released once there was room"); + } + TEST_ASSERT(drained, "room to make: the cache was drained"); + TEST_ASSERT(r >= 1, "and free blocks were released"); + PASS(); +} + +/* A pool is empty only once the blocks freed to it from another thread are + * taken back and its slab cache is folded in, so the boundary does both + * before it looks: here the last block of a pool sits on the heap's foreign + * list and another in its slab cache. */ +static test_result_t test_relieve_drains_and_flushes(void) { +#if defined(_WIN32) + SKIP("no file spill, so no relief: the watermark decides nothing"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + /* x is the right half of pool 1 and s, of a slab order, comes from its + * cascade; y takes a second pool so pool 1 is not the heap's last. */ + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* s = ray_alloc((64u << 10) - 64); + ray_t* y = ray_alloc(RELIEVE_HALF); + if (!x || !s || !y) { + if (x) ray_free(x); + if (s) ray_free(s); + if (y) ray_free(y); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + bool layout = h->pool_count == 2 && heap_find_pool(h, s) == heap_find_pool(h, x) + && heap_find_pool(h, y) != heap_find_pool(h, x); + ray_free(s); /* into h's slab cache */ + bool cached = h->slabs[SLAB_INDEX(s->order)].count == 1; + ray_tl_heap = e.base; + ray_free(x); /* onto h's foreign list */ + ray_tl_heap = h; + bool queued = atomic_load(&h->foreign) == x; + + relieve_pressure(RELIEVE_POOL); + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); + bool gone = h->pool_count == 1 && heap_find_pool(h, x) < 0 + && heap_find_pool(h, y) >= 0; + + ray_free(y); + relieve_env_end(&e, h, NULL); + if (!spill) SKIP("no spill file"); + TEST_ASSERT(layout && cached && queued, "pool 1 held only queued blocks"); + TEST_ASSERT(gone, "the pool was found empty and unmapped"); + PASS(); +} + +/* One walk of a heap's freelists settles every pool: of eight pools, the + * two that are empty go and the rest — one of them cut into many small free + * blocks — stay, with nothing of the unmapped ones left on a freelist. */ +static test_result_t test_relieve_many_pools(void) { +#if defined(_WIN32) + SKIP("no file spill, so no relief: the watermark decides nothing"); +#endif + enum { P = 8, S = 4000 }; + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + /* Every other one of S small blocks freed: a long freelist of blocks + * that cannot coalesce, all in the first pool, which the first + * half-pool block then completes. */ + ray_t* sm = ray_alloc(S * sizeof(ray_t*)); + ray_t** small = sm ? (ray_t**)ray_data(sm) : NULL; + bool ok = small != NULL; + for (int i = 0; ok && i < S; i++) ok = (small[i] = ray_alloc(16)) != NULL; + ray_t* x[P] = {0}; + for (int i = 0; ok && i < P; i++) ok = (x[i] = ray_alloc(RELIEVE_HALF)) != NULL; + if (!ok) { + for (int i = 0; i < P; i++) if (x[i]) ray_free(x[i]); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + for (int i = 1; i < S; i += 2) ray_free(small[i]); + bool layout = h->pool_count == P; + uintptr_t gone3 = (uintptr_t)h->pools[heap_find_pool(h, x[3])].base; + uintptr_t gone5 = (uintptr_t)h->pools[heap_find_pool(h, x[5])].base; + ray_free(x[3]); + ray_free(x[5]); + x[3] = x[5] = NULL; + + relieve_pressure(RELIEVE_POOL); + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); + bool two = h->pool_count == P - 2; + bool rest = true; + for (int i = 0; i < P; i++) + if (x[i]) rest = rest && heap_find_pool(h, x[i]) >= 0; + + /* No freelist may still lead into an unmapped pool (compared, never + * followed, once it does). */ + bool clean = true; + for (int k = RAY_ORDER_MIN; clean && k < RAY_HEAP_FL_SIZE; k++) { + ray_fl_head_t* fh = &h->freelist[k]; + for (ray_t* b = fh->fl_next; b != (ray_t*)fh; b = b->fl_next) { + uintptr_t a = (uintptr_t)b; + if ((a >= gone3 && a < gone3 + (uintptr_t)RELIEVE_POOL) || + (a >= gone5 && a < gone5 + (uintptr_t)RELIEVE_POOL)) { + clean = false; + break; + } + } + } + for (int i = 0; i < S; i += 2) ray_free(small[i]); + ray_free(sm); + for (int i = 0; i < P; i++) if (x[i]) ray_free(x[i]); + relieve_env_end(&e, h, NULL); + if (!spill) SKIP("no spill file"); + TEST_ASSERT(layout, "one pool per half-pool block"); + TEST_ASSERT(two && rest, "exactly the two empty pools went"); + TEST_ASSERT(clean, "nothing of them was left on a freelist"); + PASS(); +} + +/* A block another thread is freeing reads rc 0 before it reaches the + * owner's list, so a pool can look empty while one of its blocks is in + * flight. The boundary counts what is on the freelists, and keeps it. */ +static test_result_t test_relieve_inflight_free(void) { +#if defined(_WIN32) + SKIP("no file spill, so no relief: the watermark decides nothing"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + /* z, an eighth of a pool, comes from the cascade of pool 2, whose right + * half y then frees: pool 2 is all free but z. */ + const size_t eighth = (8u << 20) - 4096; + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* y = ray_alloc(RELIEVE_HALF); + ray_t* z = ray_alloc(eighth); + if (!x || !y || !z) { + if (x) ray_free(x); + if (y) ray_free(y); + if (z) ray_free(z); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + bool layout = h->pool_count == 2 && heap_find_pool(h, z) == heap_find_pool(h, y); + ray_free(y); + ray_atomic_store(&z->rc, 0); /* mid-free, not yet on a list */ + relieve_pressure(RELIEVE_POOL); + ray_heap_relieve(); /* parks what is empty */ + bool unparked = relieve_parked(h) == 0; + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); /* unmaps what is empty */ + bool kept = heap_find_pool(h, z) >= 0 && h->pool_count == 2; + if (kept) { + ray_atomic_store(&z->rc, 1); + memset(ray_data(z), 9, eighth); + ray_free(z); + } + ray_free(x); + relieve_env_end(&e, h, NULL); + if (!spill) SKIP("no spill file"); + TEST_ASSERT(layout, "pool 2 held z and a free right half"); + TEST_ASSERT(unparked, "a pool with a block in flight is not parked"); + TEST_ASSERT(kept, "a pool with a block in flight stays mapped"); + PASS(); +} + +/* Two anonymous pools, then two spill pools, all four empty again; s1's + * pages faulted in (*probe is inside them), and s2's if probe2 is not NULL + * (*probe2). False if the blocks or a spill file were unavailable. */ +static bool relieve_spill_layout(ray_heap_t* h, const char** probe, const char** probe2) { + ray_t* a1 = ray_alloc(RELIEVE_HALF); + ray_t* a2 = ray_alloc(RELIEVE_HALF); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_t* s1 = ray_alloc(RELIEVE_HALF); + ray_t* s2 = ray_alloc(RELIEVE_HALF); + bool ok = a1 && a2 && s1 && s2 && h->pool_count == 4 + && !relieve_pool_is_backed(h, a1) && !relieve_pool_is_backed(h, a2) + && relieve_pool_is_backed(h, s1) && relieve_pool_is_backed(h, s2); + if (s1) { + memset(ray_data(s1), 0xA5, RELIEVE_HALF); + *probe = (const char*)s1 + (4u << 20); + } + if (s2 && probe2) { + memset(ray_data(s2), 0xB6, RELIEVE_HALF); + *probe2 = (const char*)s2 + (4u << 20); + } + if (s1) ray_free(s1); + if (s2) ray_free(s2); + if (a2) ray_free(a2); + if (a1) ray_free(a1); + return ok; +} + +/* Empty spill pools stay mapped while memory stays held, their pages + * discarded: a statement that reuses one creates no file anew, and their + * files keep their disk blocks. A heap that spilled a pool keeps its + * anonymous pools too — it ran out of its own — and every empty pool is + * parked but the last. After a spill that is not its own, the relief acts, + * and the empty pools go, spill ones with the anonymous ones, but the last. + * .sys.gc is a boundary too. */ +static test_result_t test_relieve_spill_pools(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + const char* probe = NULL; + if (!relieve_spill_layout(h, &probe, NULL)) { + relieve_env_end(&e, h, NULL); + SKIP("blocks or spill file unavailable"); + } + + /* The spill was this heap's own: nothing for the relief to act on. */ + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_t* rc = ray_gc_fn(NULL, 0); + if (rc) ray_release(rc); + bool disc = ray_heap_spill_discards(); + bool kept = disc ? h->pool_count == 4 && relieve_backed_pools(h) == 2 + : h->pool_count == 2 && relieve_backed_pools(h) == 0; + kept = kept && relieve_parked(h) == (disc ? 3 : 1); + int res = relieve_resident(probe); + + /* A spill elsewhere: the relief acts, and the empty pools go. */ + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); + bool gone = h->pool_count == 1 && relieve_backed_pools(h) == 0; + + relieve_env_end(&e, h, NULL); + if (!spill) SKIP("no spill file"); + TEST_ASSERT(kept, disc ? "(.sys.gc) kept all four pools, three parked" + : "(.sys.gc) without discard: unmapped the spill pools, one anonymous parked"); + if (disc && relieve_mincore()) TEST_ASSERT(res == 0, "the spill pool's pages were discarded"); + TEST_ASSERT(gone, "a relief that acted unmapped the spill pools with the anonymous ones, but the last"); + PASS(); +} + +#if defined(__linux__) +/* This thread's cancelled_write_bytes (/proc/thread-self/io): dirty pages it + * dropped from the page cache unwritten; -1 where it cannot be read. */ +static int64_t relieve_cancelled(void) { +#if defined(__linux__) + char buf[1024]; + int fd = open("/proc/thread-self/io", O_RDONLY); + if (fd < 0) return -1; + ssize_t n = read(fd, buf, sizeof(buf) - 1); + close(fd); + if (n <= 0) return -1; + buf[n] = 0; + const char* p = strstr(buf, "cancelled_write_bytes:"); + return p ? strtoll(p + 22, NULL, 10) : -1; +#else + return -1; +#endif +} +#endif + +/* An empty spill pool parked at a boundary keeps its file and its mapping + * for the next statement that spills, but its pages — dead data — are + * discarded: punched out of the file, the dirty ones unwritten (the + * thread's cancelled writes count them), then reserved again, so the file + * keeps its disk blocks. A spill pool still in use keeps its data. Taken + * back, the pool serves blocks anew, no pool mapped for them. An idle event + * loop does not wake for a parked pool (ray_heap_decay_due_ms). */ +static test_result_t test_relieve_spill_discard(void) { +#if !defined(__linux__) + SKIP("pages are discarded on Linux only"); +#else + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + ray_t* a1 = ray_alloc(RELIEVE_HALF); + ray_t* a2 = ray_alloc(RELIEVE_HALF); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_t* s1 = ray_alloc(RELIEVE_HALF); /* live through the boundary */ + ray_t* s2 = ray_alloc(RELIEVE_HALF); /* freed before it */ + bool layout = a1 && a2 && s1 && s2 && h->pool_count == 4 + && relieve_pool_is_backed(h, s1) && relieve_pool_is_backed(h, s2); + const char* probe = NULL; + int fd = -1; + if (layout) { + memset(ray_data(s1), 0x5A, RELIEVE_HALF); + memset(ray_data(s2), 0xA5, RELIEVE_HALF); + probe = (const char*)s2 + (4u << 20); + fd = h->pools[heap_find_pool(h, s2)].swap_fd; + } + if (s2) ray_free(s2); + + int64_t c0 = relieve_cancelled(); + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_relieve(); /* its own spill: no relief */ + int64_t cw = c0 >= 0 ? relieve_cancelled() - c0 : -1; + int64_t n1 = ray_heap_spill_discard_count(); + relieve_far(); /* the pool still parked */ + bool once = ray_heap_spill_discard_count() == n1; + int i2 = probe ? heap_find_pool(h, probe) : -1; + bool kept = i2 >= 0 && h->pools[i2].parked && h->pools[i2].backed + && h->pool_count == 4; + int res = probe ? relieve_resident(probe) : -1; + struct stat st; + bool reserved = fd >= 0 && fstat(fd, &st) == 0 + && (int64_t)st.st_blocks * 512 >= (int64_t)st.st_size; + bool live = s1 != NULL; + for (size_t i = 0; s1 && i < RELIEVE_HALF; i += 4096) + live = live && ((const unsigned char*)ray_data(s1))[i] == 0x5A; + ray_heap_note_activity(); + int64_t due = ray_heap_decay_due_ms(); + + ray_t* s3 = ray_alloc(RELIEVE_HALF); + bool reused = s3 && h->pool_count == 4 && heap_find_pool(h, s3) == i2; + if (s3) { + memset(ray_data(s3), 0x3C, RELIEVE_HALF); + reused = reused && ((const unsigned char*)ray_data(s3))[RELIEVE_HALF / 2] == 0x3C; + ray_free(s3); + } + + if (s1) ray_free(s1); + if (a2) ray_free(a2); + if (a1) ray_free(a1); + relieve_env_end(&e, h, NULL); + if (!layout) SKIP("blocks or spill file unavailable"); + if (i2 < 0) SKIP("the spill directory cannot punch holes"); + TEST_ASSERT(kept, "the emptied spill pool was parked, file and mapping kept"); + if (relieve_mincore()) TEST_ASSERT(res == 0, "its pages were discarded"); + if (cw >= 0) TEST_ASSERT(cw >= (int64_t)RELIEVE_HALF, "the dirty ones unwritten"); + TEST_ASSERT(reserved, "its file keeps its disk blocks"); + TEST_ASSERT(live, "the spill pool in use kept its data"); + TEST_ASSERT(due > 0, "an idle event loop does not wake for the parked pool"); + TEST_ASSERT(once, "discarded once: a later boundary left it alone"); + TEST_ASSERT(reused, "taken back, it served a block, no pool mapped"); + PASS(); +#endif +} + +/* Where pages cannot be discarded — forced here, as on a platform without a + * way to punch a mapped range — an empty spill pool is unmapped at the + * boundary that would park it. */ +static test_result_t test_relieve_spill_fallback(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + const char* probe = NULL; + if (!relieve_spill_layout(h, &probe, NULL)) { + relieve_env_end(&e, h, NULL); + SKIP("blocks or spill file unavailable"); + } + bool was = ray_heap_set_spill_discard(false); + bool off = !ray_heap_spill_discards(); + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_relieve(); /* its own spill: no relief */ + (void)ray_heap_set_spill_discard(was); + bool unmapped = h->pool_count == 2 && relieve_backed_pools(h) == 0 + && relieve_parked(h) == 1; + relieve_env_end(&e, h, NULL); + TEST_ASSERT(was, "discarding is on by default"); + TEST_ASSERT(off, "and off once the setting says so"); + TEST_ASSERT(unmapped, "both spill pools unmapped, the anonymous ones kept, one parked"); + PASS(); +} + +#if defined(__linux__) +/* The open spill files of this process, or of a child it starts (popen, as + * .sys.exec): `who` is "$PPID" — popen's shell is our child — or "self". */ +static int relieve_spill_fds(const char* who) { + char cmd[128]; + snprintf(cmd, sizeof(cmd), + "ls -l /proc/%s/fd 2>/dev/null | grep -cE 'rayheap_|raydirect_|raysys_'", who); + FILE* f = popen(cmd, "r"); + if (!f) return -1; + int n = -1; + if (fscanf(f, "%d", &n) != 1) n = -1; + pclose(f); + return n; +} +#endif + +/* Every spill file is close-on-exec: a child the process starts (.sys.exec) + * holds none of the files of its spill pools or spilled large or off-heap + * blocks, which would keep them — and their dirty pages, written back — + * past their unmapping, for as long as the child runs. (An off-heap + * block's file is closed as soon as it is mapped: only a fork racing that + * window could inherit it.) */ +static test_result_t test_relieve_spill_cloexec(void) { +#if !defined(__linux__) + SKIP("/proc//fd is Linux-only"); +#else + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + ray_t* a = ray_alloc(RELIEVE_HALF); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_t* s = ray_alloc(RELIEVE_HALF); /* a spill pool */ + ray_t* d = ray_alloc((size_t)48 << 20); /* a spilled large block */ + int64_t c0 = ray_heap_anon_committed(); + void* sb = ray_sys_alloc((size_t)48 << 20); /* a spilled off-heap block */ + bool sys = sb && ray_heap_anon_committed() == c0; + bool spilled = s && relieve_pool_is_backed(h, s) && d && ray_direct_file_backed(d); + int ours = relieve_spill_fds("$PPID"); + int child = relieve_spill_fds("self"); + if (sb) ray_sys_free(sb); + if (d) ray_free(d); + if (s) ray_free(s); + if (a) ray_free(a); + relieve_env_end(&e, h, NULL); + if (!spilled || !sys) SKIP("no spill file"); + if (ours < 0 || child < 0) SKIP("no shell to look with"); + TEST_ASSERT(ours >= 2, "the pool's and the block's files are open here"); + TEST_ASSERT_EQ_I(child, 0); + PASS(); +#endif +} + +/* An idle process gives back pages through the decay — but a spill pool's + * pages are page cache that releasing does not free, so the decay unmaps + * empty spill pools instead. Anon pools stay. */ +static test_result_t test_decay_unmaps_spill_pools(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + ray_t* a1 = ray_alloc(RELIEVE_HALF); + ray_t* a2 = ray_alloc(RELIEVE_HALF); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_t* s1 = ray_alloc(RELIEVE_HALF); + ray_heap_set_anon_watermark(INT64_C(1) << 40); + if (!a1 || !a2 || !s1) { + if (a1) ray_free(a1); + if (a2) ray_free(a2); + if (s1) ray_free(s1); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + bool layout = h->pool_count == 3 && relieve_pool_is_backed(h, s1); + ray_free(s1); + ray_free(a2); + + ray_heap_set_decay_ms(0); + ray_heap_note_activity(); + int64_t swept = ray_heap_decay(); + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + bool gone = h->pool_count == 2 && relieve_backed_pools(h) == 0; + + ray_free(a1); + relieve_env_end(&e, h, NULL); + TEST_ASSERT(layout, "two anon pools and a spill pool"); + TEST_ASSERT(swept >= 0, "the decay swept"); + TEST_ASSERT(gone, "the empty spill pool went, the empty anon one stayed"); + PASS(); +} + +/* The registry also holds the heaps of other live threads — an embedding's + * own, a host-driven poll loop's — whose freelists only their owner may + * touch. Neither the boundary relief nor the idle decay goes near them: an + * empty pool of such a heap stays, and so do the blocks queued for it. */ +static test_result_t test_relieve_skips_other_heaps(void) { +#if defined(_WIN32) + SKIP("no file spill, so no relief: the watermark decides nothing"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* other = relieve_heap_new(&e); + ray_t* o1 = other ? ray_alloc(RELIEVE_HALF) : NULL; + ray_t* o3 = other ? ray_alloc(64) : NULL; /* pool 1, with o1 */ + ray_t* o2 = other ? ray_alloc(RELIEVE_HALF) : NULL; + if (o2) ray_free(o2); /* other's pool 2: empty */ + ray_heap_t* h = other ? relieve_heap_new(&e) : NULL; + ray_t* x = h ? ray_alloc(RELIEVE_HALF) : NULL; + ray_t* y = h ? ray_alloc(RELIEVE_HALF) : NULL; + if (!other || !h || !o1 || !o3 || !x || !y) { + if (x) ray_free(x); + if (y) ray_free(y); + if (other) { ray_tl_heap = other; if (o1) ray_free(o1); if (o3) ray_free(o3); } + relieve_env_end(&e, h, other); + SKIP("heaps unavailable"); + } + ray_free(o3); /* onto other's foreign list */ + ray_free(y); /* h's pool 2: empty */ + uint32_t other_pools = other->pool_count; + + relieve_pressure(RELIEVE_POOL); + ray_heap_relieve(); /* parks */ + bool parked = relieve_parked(h) == 1 && relieve_parked(other) == 0 + && atomic_load(&other->foreign) == o3; + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); /* unmaps */ + bool relieved = h->pool_count == 1; + bool spared = other->pool_count == other_pools + && atomic_load(&other->foreign) == o3; + + ray_heap_set_decay_ms(0); + ray_heap_note_activity(); + ray_heap_decay(); + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + bool spared_decay = other->pool_count == other_pools + && atomic_load(&other->foreign) == o3; + + ray_free(x); + ray_tl_heap = other; + ray_free(o1); + relieve_env_end(&e, h, other); + if (!spill) SKIP("no spill file"); + TEST_ASSERT(other_pools == 2, "the other heap had an empty pool"); + TEST_ASSERT(parked, "the caller's empty pool was parked, the other heap's not"); + TEST_ASSERT(relieved, "the caller's own empty pool went"); + TEST_ASSERT(spared, "the relief left the other heap alone"); + TEST_ASSERT(spared_decay, "and so did the decay"); + PASS(); +} + +/* A footprint a pool short of the watermark is not pressure by itself. Each + * light statement here takes one pool more than the live data and frees it, + * which fits; unmapping that pool at every boundary only made the next + * statement map and fault it again (#750). The boundary parks it and the + * next statement takes it back: nothing is unmapped and nothing is mapped + * anew — half a pool under the watermark and exactly at it, where the pool + * still fits. */ +static test_result_t relieve_steady_state_at(int64_t slack) { + enum { N = 8 }; + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + int64_t base = ray_heap_anon_committed(); + ray_t* x = ray_alloc(RELIEVE_HALF); /* the live data: pool 1 */ + if (!x) { relieve_env_end(&e, h, NULL); SKIP("blocks unavailable"); } + ray_heap_set_anon_watermark(base + 2 * RELIEVE_POOL + slack); + int changed = 0, parked = 0; + for (int i = 0; i < N; i++) { + ray_t* y = ray_alloc(RELIEVE_HALF); + if (y) { memset(ray_data(y), 3, 4096); ray_free(y); } + ray_heap_relieve(); + changed += h->pool_count != 2 + || ray_heap_anon_committed() != base + 2 * RELIEVE_POOL; + parked += relieve_parked(h) == 1; + } + ray_free(x); + relieve_env_end(&e, h, NULL); + TEST_ASSERT_EQ_I(changed, 0); + TEST_ASSERT_EQ_I(parked, N); + PASS(); +} +static test_result_t test_relieve_steady_state(void) { +#if defined(_WIN32) + SKIP("no file spill, so no relief: the watermark decides nothing"); +#endif + test_result_t r = relieve_steady_state_at(RELIEVE_POOL / 2); + if (r.status != TEST_PASS) return r; + return relieve_steady_state_at(0); +} + +/* Without a spill a boundary unmaps nothing, however close to the watermark + * and however far the footprint grows; it parks. A spill relieves — when it + * hands back at least a pool, and that makes room for the next pool under + * the watermark; an off-heap block's spill as much as a pool's. */ +static test_result_t test_relieve_needs_spill(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + enum { G = 4 }; + const size_t eighth = (8u << 20) - 4096; + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + /* x holds pool 1, y pool 2, and f, from pool 2's cascade, is freed with + * its pages faulted in. */ + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* y = ray_alloc(RELIEVE_HALF); + ray_t* f = ray_alloc(eighth); + if (!x || !y || !f) { + if (x) ray_free(x); + if (y) ray_free(y); + if (f) ray_free(f); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + memset(ray_data(f), 0xA5, eighth); + const char* probe = (const char*)f + (4u << 20); + ray_free(f); + + /* A spill with less than a pool to hand back changes nothing. */ + bool spill = relieve_spill_elsewhere(&e); + int res0 = relieve_resident(probe); + ray_heap_relieve(); + int res1 = relieve_resident(probe); + + /* Now pool 2 is empty. */ + ray_free(y); + int64_t c0 = ray_heap_anon_committed(); + ray_heap_set_anon_watermark(c0 + 3 * RELIEVE_POOL / 4); + + /* Statements that grow the footprint by off-heap blocks, no spill. */ + void* g[G] = {0}; + bool kept = true; + for (int i = 0; i < G; i++) { + g[i] = ray_sys_alloc((size_t)2 << 20); + ray_heap_relieve(); + kept = kept && g[i] && h->pool_count == 2 && relieve_parked(h) == 1; + } + bool grew = ray_heap_anon_committed() > c0; + for (int i = 0; i < G; i++) if (g[i]) ray_sys_free(g[i]); + + /* A spill, but the room is short of a pool under the watermark. */ + ray_heap_set_anon_watermark(c0 - RELIEVE_POOL / 2); + spill = relieve_spill_elsewhere(&e) && spill; + ray_heap_relieve(); + bool short_room = h->pool_count == 2; + + /* An off-heap block spills — mapped with no heap on the thread, so that + * nothing is handed back for it — and there is room. */ + ray_heap_set_anon_watermark(c0 + 3 * RELIEVE_POOL / 4); + ray_tl_heap = NULL; + int64_t c1 = ray_heap_anon_committed(); + void* s = ray_sys_alloc((size_t)24 << 20); + bool sys = s && ray_heap_anon_committed() == c1; + if (s) ray_sys_free(s); + ray_tl_heap = h; + ray_heap_relieve(); + bool relieved = h->pool_count == 1 && relieve_parked(h) == 0; + + ray_free(x); + relieve_env_end(&e, h, NULL); + if (!spill || !sys) SKIP("no spill file"); + if (relieve_mincore()) { + TEST_ASSERT(res0 == 1, "the free block's pages were resident"); + TEST_ASSERT(res1 == 1, "a spill with less than a pool to give left them"); + } + TEST_ASSERT(kept, "no spill: the empty pool was parked, never unmapped"); + TEST_ASSERT(grew, "while the footprint grew"); + TEST_ASSERT(short_room, "a spill without room for a pool unmapped nothing"); + TEST_ASSERT(relieved, "an off-heap block's spill with room unmapped the empty pool"); + PASS(); +} + +/* A heap keeps its last pool, so with every pool empty it can give one pool + * less: two empty pools give one, short of the room the watermark wants + * here, and nothing is unmapped; with room for one, one goes. */ +static test_result_t test_relieve_last_pool(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* y = ray_alloc(RELIEVE_HALF); + if (x) ray_free(x); + if (y) ray_free(y); + int64_t c = ray_heap_anon_committed(); + ray_heap_set_anon_watermark(c - RELIEVE_POOL / 2); + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); + bool kept = h->pool_count == 2; + ray_heap_set_anon_watermark(c); + spill = relieve_spill_elsewhere(&e) && spill; + ray_heap_relieve(); + bool one = h->pool_count == 1; + relieve_env_end(&e, h, NULL); + if (!x || !y) SKIP("blocks unavailable"); + if (!spill) SKIP("no spill file"); + TEST_ASSERT(kept, "one pool's room was short: nothing went"); + TEST_ASSERT(one, "with room for one, one went"); + PASS(); +} + +/* With no spill file to be had, a pool or a large block past the watermark + * goes to RAM — a spill all the same, and its boundary relieves. */ +static test_result_t test_relieve_no_spill_file(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* y = ray_alloc(RELIEVE_HALF); + if (!x || !y) { + if (x) ray_free(x); + if (y) ray_free(y); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + ray_free(y); /* pool 2: empty */ + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + + /* Another heap without a spill directory maps a pool past it. */ + ray_heap_t* s = relieve_heap_new(&e); + bool ram = false; + if (s) { + snprintf(s->swap_path, sizeof(s->swap_path), "/nonexistent-rayforce-spill/"); + ray_t* b = ray_alloc(RELIEVE_HALF); + ram = b && heap_find_pool(s, b) >= 0 && !relieve_pool_is_backed(s, b); + ray_heap_destroy(); + } + ray_tl_heap = h; + ray_heap_relieve(); + bool pool = h->pool_count == 1; + + /* And a large block: an empty pool again, then the block past the + * watermark from a heap without a spill directory. */ + y = ray_alloc(RELIEVE_HALF); + if (y) ray_free(y); + s = relieve_heap_new(&e); + bool ram2 = false; + if (s) { + snprintf(s->swap_path, sizeof(s->swap_path), "/nonexistent-rayforce-spill/"); + ray_t* d = ray_alloc((size_t)48 << 20); + ram2 = d && !ray_direct_file_backed(d); + if (d) ray_free(d); + ray_heap_destroy(); + } + ray_tl_heap = h; + ray_heap_direct_cache_drain(); + ray_heap_relieve(); + bool large = h->pool_count == 1; + + /* And an off-heap block, the spill directory gone for it (it is read + * from the environment), mapped with no heap on the thread. */ + bool ram3 = true, sys = true; +#if !defined(_WIN32) + y = ray_alloc(RELIEVE_HALF); + if (y) ray_free(y); + const char* old = getenv("RAY_HEAP_SWAP"); + char saved[256] = {0}; + bool had = old && strlen(old) < sizeof(saved); + if (had) memcpy(saved, old, strlen(old) + 1); + setenv("RAY_HEAP_SWAP", "/nonexistent-rayforce-spill/", 1); + ray_tl_heap = NULL; + int64_t c2 = ray_heap_anon_committed(); + void* sb = ray_sys_alloc((size_t)40 << 20); + ram3 = sb && ray_heap_anon_committed() > c2; + if (sb) ray_sys_free(sb); + ray_tl_heap = h; + if (had) setenv("RAY_HEAP_SWAP", saved, 1); + else unsetenv("RAY_HEAP_SWAP"); + ray_heap_relieve(); + sys = h->pool_count == 1; +#endif + + ray_free(x); + relieve_env_end(&e, h, NULL); + if (!s) SKIP("no fresh heap"); + TEST_ASSERT(ram, "the pool went to RAM past the watermark"); + TEST_ASSERT(pool, "and its boundary relieved"); + TEST_ASSERT(ram2, "the large block went to RAM past the watermark"); + TEST_ASSERT(large, "and its boundary relieved"); + TEST_ASSERT(ram3, "the off-heap block went to RAM past the watermark"); + TEST_ASSERT(sys, "and its boundary relieved"); + PASS(); +} + +/* A large block's spill in a heap of its own, as relieve_spill_elsewhere. */ +static bool relieve_large_spill_elsewhere(relieve_env_t* e) { + ray_heap_t* cur = ray_tl_heap; + int64_t wm = ray_heap_anon_watermark(); + ray_heap_t* s = relieve_heap_new(e); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_t* d = s ? ray_alloc((size_t)48 << 20) : NULL; + bool spilled = d && ray_direct_file_backed(d); + if (d) ray_free(d); + if (s) ray_heap_destroy(); + ray_heap_set_anon_watermark(wm); + ray_tl_heap = cur; + return spilled; +} + +/* A parked spill pool that no statement takes back for the idle decay's + * threshold is unmapped at a boundary, its file closed: the decay + * pool by pool, for a process never idle that long. Even far from the + * watermark with nothing spilled — a boundary visits the heaps while a spill + * pool is mapped, and parks the empty spill pools then, the anonymous ones + * not. A pool parked at a boundary is not aged by it, and with the decay + * disabled nothing is. */ +static test_result_t test_relieve_spill_age(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + const char* probe = NULL; + const char* probe2 = NULL; + if (!relieve_spill_layout(h, &probe, &probe2)) { + relieve_env_end(&e, h, NULL); + SKIP("blocks or spill file unavailable"); + } + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_relieve(); /* sees the spill: parks */ + int i1 = heap_find_pool(h, probe); + bool parked = i1 >= 0 && h->pools[i1].parked && relieve_parked(h) == 3; + if (!ray_heap_spill_discards()) { /* the empty spill pools unmapped */ + bool unmapped = h->pool_count == 2 && relieve_backed_pools(h) == 0; + relieve_env_end(&e, h, NULL); + TEST_ASSERT(unmapped, "no discard: the empty spill pools were unmapped"); + PASS(); + } + + /* s1 and the parked anonymous pool parked an hour before s2; the decay + * disabled: all stay. */ + int ia = -1; + for (uint32_t p = 0; p < h->pool_count; p++) + if (h->pools[p].parked && !h->pools[p].backed) ia = (int)p; + if (i1 >= 0) ((ray_pool_hdr_t*)h->pools[i1].base)->parked_ms -= 3600u * 1000u; + if (ia >= 0) ((ray_pool_hdr_t*)h->pools[ia].base)->parked_ms -= 3600u * 1000u; + ray_heap_set_decay_ms(-1); + relieve_far(); + bool disabled = relieve_backed_pools(h) == 2; + + /* Half an hour: s1 goes, s2 stays, and so does the anonymous pool — + * only spill pools age. */ + ray_heap_set_decay_ms(1800 * 1000); + relieve_far(); + bool aged = relieve_backed_pools(h) == 1 && heap_find_pool(h, probe) < 0 + && heap_find_pool(h, probe2) >= 0; + bool anon_kept = ia >= 0 && h->pool_count == 3 && relieve_parked(h) == 2; + + /* No threshold at all: s2 is taken back, and parked again by the + * boundary — which leaves it, and the emptied anonymous pool on the + * lists; the next boundary unmaps it. */ + ray_heap_set_decay_ms(0); + ray_t* b[3] = {0}; + bool took = true; + for (int i = 0; i < 3; i++) took = took && (b[i] = ray_alloc(RELIEVE_HALF)) != NULL; + took = took && relieve_pool_is_backed(h, b[2]) && relieve_parked(h) == 0; + for (int i = 0; i < 3; i++) if (b[i]) ray_free(b[i]); + relieve_far(); + bool again = relieve_backed_pools(h) == 1 && relieve_parked(h) == 1; + relieve_far(); + bool gone = relieve_backed_pools(h) == 0 && h->pool_count == 2; + + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + relieve_env_end(&e, h, NULL); + TEST_ASSERT(parked, "the empty spill pools were parked"); + TEST_ASSERT(disabled, "with the decay disabled they stayed"); + TEST_ASSERT(aged, "the one parked past the threshold went"); + TEST_ASSERT(anon_kept, "the anonymous pool parked as long stayed"); + TEST_ASSERT(took, "the other was taken back"); + TEST_ASSERT(again, "parked again, it outlived that boundary, and only it was parked"); + TEST_ASSERT(gone, "and went at the next"); + PASS(); +} + +/* Far from the watermark a boundary visits the heaps at most every + * RAY_FAR_VISIT_MS (heap.c): a stream of small statements would otherwise + * walk every worker heap each time. Spill pools aged past the threshold + * wait for the next visit — checked only where the boundaries came within + * that time of the last one. */ +static test_result_t test_relieve_far_visit(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + const char* probe = NULL; + if (!relieve_spill_layout(h, &probe, NULL)) { + relieve_env_end(&e, h, NULL); + SKIP("blocks or spill file unavailable"); + } + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_relieve(); /* sees the spill: parks */ + if (!ray_heap_spill_discards()) { /* the empty spill pools unmapped */ + bool unmapped = h->pool_count == 2 && relieve_backed_pools(h) == 0; + relieve_env_end(&e, h, NULL); + TEST_ASSERT(unmapped, "no discard: the empty spill pools were unmapped"); + PASS(); + } + int64_t t0 = ray_time_now_ms(); + relieve_far(); /* a visit */ + ray_heap_set_decay_ms(0); + ray_heap_relieve(); + bool within = ray_time_now_ms() - t0 < 100; + bool waited = relieve_backed_pools(h) == 2; + relieve_far(); + bool aged = relieve_backed_pools(h) == 0; + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + relieve_env_end(&e, h, NULL); + if (within) TEST_ASSERT(waited, "a boundary right after a visit did not visit"); + TEST_ASSERT(aged, "the next visit aged them"); + PASS(); +} + +/* A parked spill pool is no room for the relief: unmapping it would take + * nothing off the anonymous footprint. Here the direct-block cache is the + * only room, short of bringing the next pool under the watermark — with the + * spill pool counted it would — and the boundary after a spill leaves the + * cache alone. */ +static test_result_t test_relieve_spill_not_room(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_t* s = ray_alloc(RELIEVE_HALF); + bool layout = x && s && h->pool_count == 2 && relieve_pool_is_backed(h, s); + if (s) ray_free(s); + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_relieve(); /* this heap's spill: parked */ + bool parked = relieve_parked(h) == 1; + if (layout && !ray_heap_spill_discards()) { /* the empty spill pool unmapped */ + bool unmapped = h->pool_count == 1 && relieve_backed_pools(h) == 0; + ray_free(x); + relieve_env_end(&e, h, NULL); + TEST_ASSERT(unmapped, "no discard: the empty spill pool was unmapped"); + PASS(); + } + + int64_t c0 = ray_heap_anon_committed(); + ray_t* d = ray_alloc((size_t)40 << 20); + if (d) { memset(ray_data(d), 1, 4096); ray_free(d); } + int64_t cached = ray_heap_anon_committed() - c0; + int64_t c1 = ray_heap_anon_committed(); + ray_heap_set_anon_watermark(c1 - cached + RELIEVE_POOL - RELIEVE_MB); + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); + bool kept = ray_heap_anon_committed() == c1 && relieve_backed_pools(h) == 1; + + if (x) ray_free(x); + relieve_env_end(&e, h, NULL); + if (!layout || !spill) SKIP("blocks or spill file unavailable"); + TEST_ASSERT(parked, "the spill pool was parked"); + TEST_ASSERT(cached >= (int64_t)40 << 20, "the direct block was cached"); + TEST_ASSERT(kept, "no relief: the cache and the spill pool stayed"); + PASS(); +} + +/* A heap whose thread leaves it (ray_heap_abandon) is visited by no boundary, + * so its empty spill pools could never age: they go then. Its anonymous + * pools stay for the thread that adopts it. */ +static test_result_t test_relieve_abandon_spill(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + const char* probe = NULL; + if (!relieve_spill_layout(h, &probe, NULL)) { + relieve_env_end(&e, h, NULL); + SKIP("blocks or spill file unavailable"); + } + ray_heap_abandon(); + bool gone = h->pool_count == 2 && relieve_backed_pools(h) == 0; + ray_heap_init(); /* adopts it back */ + bool back = ray_tl_heap == h; + relieve_env_end(&e, back ? h : NULL, NULL); + if (!back) FAIL("the abandoned heap was not adopted back"); + TEST_ASSERT(gone, "the empty spill pools went, the anonymous ones stayed"); + PASS(); +} + +/* A heap keeps a pool, even when all its pools are parked spill pools — as + * after a large block took its anonymous ones (heap_make_room): the aging + * does not take the last, and the heap serves blocks from it, its pages + * discarded before and zero-filled anew. */ +static test_result_t test_relieve_spill_last_pool(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + const char* probe = NULL; + if (!relieve_spill_layout(h, &probe, NULL)) { + relieve_env_end(&e, h, NULL); + SKIP("blocks or spill file unavailable"); + } + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_relieve(); /* three parked, one not */ + if (!ray_heap_spill_discards()) { /* the empty spill pools unmapped */ + bool unmapped = h->pool_count == 2 && relieve_backed_pools(h) == 0; + relieve_env_end(&e, h, NULL); + TEST_ASSERT(unmapped, "no discard: the empty spill pools were unmapped"); + PASS(); + } + ray_heap_set_anon_watermark(ray_heap_anon_committed() + 24 * RELIEVE_MB); + ray_t* d = ray_alloc((size_t)48 << 20); + bool spill_only = d && h->pool_count == 2 && relieve_parked(h) == 2; + if (d) ray_free(d); + ray_heap_direct_cache_drain(); + + /* Both spill pools aged past a threshold of nothing: one stays. */ + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_set_decay_ms(0); + ray_heap_relieve(); + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + bool aged = h->pool_count == 1; + + ray_t* x = ray_alloc(RELIEVE_HALF); + bool serves = x && h->pool_count == 1 && relieve_pool_is_backed(h, x); + if (x) { + memset(ray_data(x), 0x6B, RELIEVE_HALF); + serves = serves && ((unsigned char*)ray_data(x))[RELIEVE_HALF - 1] == 0x6B; + ray_free(x); + } + + relieve_env_end(&e, h, NULL); + TEST_ASSERT(spill_only, "the large block took the anonymous pools"); + TEST_ASSERT(aged, "the aging kept the last pool"); + TEST_ASSERT(serves, "and the heap serves blocks from it"); + PASS(); +} + +#if defined(__linux__) +/* The files of the cgroup read since the last call: inotify events. */ +static int relieve_reads(int fd) { + int n = 0; + char ev[4096] __attribute__((aligned(__alignof__(struct inotify_event)))); + for (ssize_t r; fd >= 0 && (r = read(fd, ev, sizeof(ev))) > 0; ) + for (char* p = ev; p < ev + r; p += sizeof(struct inotify_event) + ((struct inotify_event*)p)->len) + n++; + return n; +} +#endif + +/* A cgroup's memory.stat is read — which flushes its statistics — only + * after spill pages are dropped, a parked pool's discarded or a pool + * unmapped: not at a boundary that drops nothing, nor before a large block. */ +static test_result_t test_relieve_spill_reads(void) { +#if !defined(__linux__) + SKIP("cgroup statistics are flushed on Linux only"); +#else + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + const char* probe = NULL; + const char* probe2 = NULL; + if (!relieve_spill_layout(h, &probe, &probe2)) { + relieve_env_end(&e, h, NULL); + SKIP("blocks or spill file unavailable"); + } + ray_heap_set_anon_watermark(INT64_C(1) << 40); + relieve_cgroup(&e); + int fd = inotify_init1(IN_NONBLOCK); + bool watch = fd >= 0 && inotify_add_watch(fd, e.cg, IN_ACCESS) >= 0; + + /* The spill pools' pages dropped: memory.stat read. */ + ray_heap_relieve(); + int dropped = relieve_reads(fd); + + /* Nothing dropped: a boundary and a large block read nothing. */ + relieve_far(); + void* sb = ray_sys_alloc((size_t)48 << 20); + if (sb) ray_sys_free(sb); + int none = relieve_reads(fd); + + /* A spill pool taken back, used and emptied: read again. */ + ray_t* b[3] = {0}; + for (int i = 0; i < 3; i++) b[i] = ray_alloc(RELIEVE_HALF); + bool used = b[2] && relieve_pool_is_backed(h, b[2]); + if (used) memset(ray_data(b[2]), 0x77, RELIEVE_HALF); + for (int i = 0; i < 3; i++) if (b[i]) ray_free(b[i]); + relieve_far(); + int again = relieve_reads(fd); + if (fd >= 0) close(fd); + + relieve_env_end(&e, h, NULL); + if (!watch) SKIP("inotify unavailable"); + TEST_ASSERT(dropped == 1, "pages dropped: the boundary read the cgroup's memory.stat"); + TEST_ASSERT(none == 0, "nothing dropped: nothing read"); + if (used) TEST_ASSERT(again == 1, "used and emptied again: read again"); + PASS(); +#endif +} + +/* A light statement: a half-pool temporary, touched and freed. */ +static void relieve_light(void) { + ray_t* y = ray_alloc(RELIEVE_HALF); + if (y) { memset(ray_data(y), 3, 4096); ray_free(y); } +} + +/* A relief is futile when the next statement that maps anything spills + * again with the room it made gone to pools, the kind of memory it came + * from: more relief would only refault it. Then the boundary does not + * relieve until a statement maps without spilling or the watermark moves. + * A statement that maps nothing does not count. Nor is a spill futile + * when the room went to a large block, which the pools could not give. The + * statements' spill pools stay parked until a relief acts. */ +static test_result_t test_relieve_futile(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + /* x holds pool 1, pool 2 is empty; the watermark half a pool above. */ + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* y = ray_alloc(RELIEVE_HALF); + if (!x || !y) { + if (x) ray_free(x); + if (y) ray_free(y); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + ray_free(y); + int64_t wm = ray_heap_anon_committed() + RELIEVE_POOL / 2; + ray_heap_set_anon_watermark(wm); + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); + bool relieved = h->pool_count == 1; + + /* A statement that maps nothing that counts: a small off-heap block, + * which could not spill. */ + void* t = ray_sys_alloc((size_t)64 << 10); + if (t) ray_sys_free(t); + ray_heap_relieve(); + + /* Two temporaries: one pool fits, the next spills. Futile: the empty + * anonymous pool is parked. */ + ray_t* y1 = ray_alloc(RELIEVE_HALF); + ray_t* y2 = ray_alloc(RELIEVE_HALF); + bool spilled = y1 && y2 && !relieve_pool_is_backed(h, y1) + && relieve_pool_is_backed(h, y2); + if (y1) ray_free(y1); + if (y2) ray_free(y2); + ray_heap_relieve(); + bool disc = ray_heap_spill_discards(); /* else the spill pool unmapped */ + bool futile = h->pool_count == (disc ? 3u : 2u) + && relieve_backed_pools(h) == (disc ? 1 : 0) + && relieve_parked(h) == (disc ? 2 : 1); + + /* A spill elsewhere: still no relief. */ + spill = relieve_spill_elsewhere(&e) && spill; + ray_heap_relieve(); + bool held = h->pool_count == (disc ? 3u : 2u) + && relieve_backed_pools(h) == (disc ? 1 : 0); + + /* A statement maps without spilling; the next spill relieves. */ + void* s = ray_sys_alloc((size_t)2 << 20); + if (s) ray_sys_free(s); + ray_heap_relieve(); + spill = relieve_spill_elsewhere(&e) && spill; + ray_heap_relieve(); + bool again = h->pool_count == 1; + + /* Right after that relief, a statement maps a large off-heap block and a + * pool and spills: not futile, so its boundary relieves. */ + int64_t cl = ray_heap_anon_committed(); + void* sb = ray_sys_alloc((size_t)40 << 20); + bool large = sb && ray_heap_anon_committed() >= cl + ((int64_t)40 << 20); + if (sb) ray_sys_free(sb); + ray_t* p1 = ray_alloc(RELIEVE_HALF); /* a new anonymous pool */ + bool mapped = p1 && h->pool_count == 2 && !relieve_pool_is_backed(h, p1); + if (p1) ray_free(p1); + spill = relieve_spill_elsewhere(&e) && spill; + ray_heap_relieve(); + bool not_futile = h->pool_count == 1; + + /* After a futile relief a moved watermark relieves again: z1 takes a new + * pool that fits, z2 and z3 spill. */ + relieve_light(); + ray_t* z1 = ray_alloc(RELIEVE_HALF); + ray_t* z2 = ray_alloc(RELIEVE_HALF); + ray_t* z3 = ray_alloc(RELIEVE_HALF); + bool futile2 = z1 && z2 && z3 && !relieve_pool_is_backed(h, z1) + && relieve_pool_is_backed(h, z3); + if (z1) ray_free(z1); + if (z2) ray_free(z2); + if (z3) ray_free(z3); + ray_heap_relieve(); + futile2 = futile2 && h->pool_count == (disc ? 4u : 2u) + && relieve_backed_pools(h) == (disc ? 2 : 0) + && relieve_parked(h) == (disc ? 3 : 1); + ray_heap_set_anon_watermark(wm + RELIEVE_MB); + spill = relieve_spill_elsewhere(&e) && spill; + ray_heap_relieve(); + bool moved = h->pool_count == 1; + + ray_free(x); + relieve_env_end(&e, h, NULL); + if (!spill || !spilled) SKIP("no spill file"); + TEST_ASSERT(relieved, "a spill relieved"); + TEST_ASSERT(futile, "the next statement spilled with its pools: parked only, the spill pool too"); + TEST_ASSERT(held, "a later spill did not relieve"); + TEST_ASSERT(again, "after a statement that mapped without spilling, a spill relieved, the spill pool with it"); + TEST_ASSERT(large && mapped, "a large block and a pool were mapped in RAM"); + TEST_ASSERT(not_futile, "a spill after room went to a large block relieved"); + TEST_ASSERT(futile2, "futile again"); + TEST_ASSERT(moved, "a moved watermark relieved after a futile relief"); + PASS(); +} + +/* A spill makes a boundary visit the heaps and park their empty pools when + * nothing else would: after a futile relief, with the next pool clear of the + * watermark and no spill pool mapped. */ +static test_result_t test_relieve_spill_parks(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_set_decay_ms(0); /* no empty spill pool left */ + ray_heap_note_activity(); + ray_heap_decay(); + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* y = ray_alloc(RELIEVE_HALF); + if (!x || !y) { + if (x) ray_free(x); + if (y) ray_free(y); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + ray_free(y); + + /* A spill relieves pool 2, leaving room for two pools. */ + ray_heap_set_anon_watermark(ray_heap_anon_committed() + RELIEVE_POOL); + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); + bool relieved = h->pool_count == 1; + + /* A new pool, emptied, while a large block spills elsewhere: futile. */ + y = ray_alloc(RELIEVE_HALF); + bool mapped = y && h->pool_count == 2 && !relieve_pool_is_backed(h, y); + if (y) ray_free(y); + bool large = relieve_large_spill_elsewhere(&e); + ray_heap_relieve(); + bool parked = h->pool_count == 2 && relieve_parked(h) == 1; + + ray_free(x); + relieve_env_end(&e, h, NULL); + if (!spill || !large) SKIP("no spill file"); + TEST_ASSERT(relieved && mapped, "a spill relieved, a new pool fit"); + TEST_ASSERT(parked, "after the next spill its empty pool was parked"); + PASS(); +} + +/* A statement whose only mapping went to a spill file mapped all the same: + * right after a relief it makes the relief futile, as a pool's spill would, + * and a later spill does not relieve, though room went to a large block + * then. */ +static test_result_t test_relieve_spill_only(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* y = ray_alloc(RELIEVE_HALF); + if (!x || !y) { + if (x) ray_free(x); + if (y) ray_free(y); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + ray_free(y); + ray_heap_set_anon_watermark(ray_heap_anon_committed() + RELIEVE_POOL / 2); + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); + bool relieved = h->pool_count == 1; + + /* An off-heap block past the room: to a spill file, nothing in RAM. */ + int64_t c = ray_heap_anon_committed(); + int64_t room = ray_heap_anon_watermark() - c; + void* sb = ray_sys_alloc((size_t)(room + 8 * RELIEVE_MB)); + bool filed = sb && ray_heap_anon_committed() == c; + if (sb) ray_sys_free(sb); + ray_heap_relieve(); + + /* A large off-heap block in RAM, a new pool emptied, a spill elsewhere. */ + void* lb = ray_sys_alloc((size_t)40 << 20); + bool large = room >= 40 * RELIEVE_MB && lb + && ray_heap_anon_committed() >= c + 40 * RELIEVE_MB; + if (lb) ray_sys_free(lb); + y = ray_alloc(RELIEVE_HALF); + bool mapped = y && h->pool_count == 2 && !relieve_pool_is_backed(h, y); + if (y) ray_free(y); + spill = relieve_spill_elsewhere(&e) && spill; + ray_heap_relieve(); + bool held = h->pool_count == 2; + + ray_free(x); + relieve_env_end(&e, h, NULL); + if (!spill || !filed) SKIP("no spill file"); + TEST_ASSERT(relieved, "a spill relieved"); + TEST_ASSERT(large && mapped, "a large block and a pool were mapped in RAM"); + TEST_ASSERT(held, "after the spill-only statement a spill did not relieve"); + PASS(); +} + +/* A large block about to cross the watermark first takes the room of its own + * heap's empty pools, parked or not, rather than spill; another heap's + * empty pool is not touched. Same for an off-heap block. */ +static test_result_t test_relieve_make_room(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* other = relieve_heap_new(&e); + ray_t* o1 = other ? ray_alloc(RELIEVE_HALF) : NULL; + ray_t* o2 = other ? ray_alloc(RELIEVE_HALF) : NULL; + if (o2) ray_free(o2); /* other's pool 2: empty */ + ray_heap_t* h = other ? relieve_heap_new(&e) : NULL; + ray_t* x = h ? ray_alloc(RELIEVE_HALF) : NULL; + ray_t* y = h ? ray_alloc(RELIEVE_HALF) : NULL; + ray_t* z = h ? ray_alloc(RELIEVE_HALF) : NULL; + if (!other || !h || !o1 || !x || !y || !z) { + if (x) ray_free(x); + if (y) ray_free(y); + if (z) ray_free(z); + if (other) { ray_tl_heap = other; if (o1) ray_free(o1); } + relieve_env_end(&e, h, other); + SKIP("heaps unavailable"); + } + uint32_t other_pools = other->pool_count; + + /* Pools 2 and 3 empty and parked; one taken back and freed again, so + * one empty pool is parked and one is on the lists. */ + ray_free(y); + ray_free(z); + relieve_pressure(RELIEVE_POOL); + ray_heap_relieve(); + ray_t* w = ray_alloc(RELIEVE_HALF); + bool layout = h->pool_count == 3 && relieve_parked(h) == 1 && w; + if (w) ray_free(w); + + /* 48 MB fits once both go. */ + ray_t* d = ray_alloc((size_t)48 << 20); + bool anon = d && !ray_direct_file_backed(d); + bool gone = h->pool_count == 1 && relieve_parked(h) == 0; + if (d) ray_free(d); + ray_heap_direct_cache_drain(); + + /* An off-heap block: a new pool, emptied, goes for it. */ + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_t* y2 = ray_alloc(RELIEVE_HALF); + bool fresh = y2 && h->pool_count == 2 && relieve_parked(h) == 0; + if (y2) ray_free(y2); + relieve_pressure(RELIEVE_POOL); + int64_t c0 = ray_heap_anon_committed(); + void* s = ray_sys_alloc((size_t)24 << 20); + bool sys = s && ray_heap_anon_committed() < c0 && h->pool_count == 1; + if (s) ray_sys_free(s); + + bool spared = other->pool_count == other_pools; + ray_free(x); + ray_tl_heap = other; + ray_free(o1); + relieve_env_end(&e, h, other); + TEST_ASSERT(layout, "one empty pool parked, one on the lists"); + TEST_ASSERT(anon, "the large block was mapped in RAM"); + TEST_ASSERT(gone, "both empty pools went for it"); + TEST_ASSERT(fresh, "a pool mapped after them is not parked"); + TEST_ASSERT(sys, "the off-heap block was mapped in RAM, its heap's empty pool gone"); + TEST_ASSERT(spared, "the other heap's empty pool stayed"); + PASS(); +} + +/* A pool is empty for heap_make_room only once the blocks freed to it from + * another thread are taken back and its slab cache is folded in: here the + * last block of a pool sits on the heap's foreign list and another in its + * slab cache, and a large block takes the pool's room. */ +static test_result_t test_relieve_make_room_drains(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* s = ray_alloc((64u << 10) - 64); + ray_t* y = ray_alloc(RELIEVE_HALF); + if (!x || !s || !y) { + if (x) ray_free(x); + if (s) ray_free(s); + if (y) ray_free(y); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + bool layout = h->pool_count == 2 && heap_find_pool(h, s) == heap_find_pool(h, x) + && heap_find_pool(h, y) != heap_find_pool(h, x); + ray_free(s); /* into h's slab cache */ + bool cached = h->slabs[SLAB_INDEX(s->order)].count == 1; + ray_tl_heap = e.base; + ray_free(x); /* onto h's foreign list */ + ray_tl_heap = h; + bool queued = atomic_load(&h->foreign) == x; + + /* 48 MB fits once pool 1 goes. */ + ray_heap_set_anon_watermark(ray_heap_anon_committed() + 24 * RELIEVE_MB); + ray_t* d = ray_alloc((size_t)48 << 20); + bool anon = d && !ray_direct_file_backed(d); + bool gone = h->pool_count == 1 && heap_find_pool(h, y) >= 0; + if (d) ray_free(d); + + ray_free(y); + relieve_env_end(&e, h, NULL); + if (!d) SKIP("no large block"); + TEST_ASSERT(layout && cached && queued, "pool 1 held only queued blocks"); + TEST_ASSERT(gone, "the pool was found empty and unmapped"); + TEST_ASSERT(anon, "the large block was mapped in RAM"); + PASS(); +} + +/* Likewise for a boundary near the watermark that relieves nothing + * (relieve_drains_flushes has one that does): the pool whose last block sits + * on the foreign list and another in the slab cache is found empty, and + * parked. */ +static test_result_t test_relieve_visit_drains(void) { + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* s = ray_alloc((64u << 10) - 64); + ray_t* y = ray_alloc(RELIEVE_HALF); + if (!x || !s || !y) { + if (x) ray_free(x); + if (s) ray_free(s); + if (y) ray_free(y); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + bool layout = h->pool_count == 2 && heap_find_pool(h, s) == heap_find_pool(h, x) + && heap_find_pool(h, y) != heap_find_pool(h, x); + ray_free(s); /* into h's slab cache */ + bool cached = h->slabs[SLAB_INDEX(s->order)].count == 1; + ray_tl_heap = e.base; + ray_free(x); /* onto h's foreign list */ + ray_tl_heap = h; + bool queued = atomic_load(&h->foreign) == x; + + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_heap_relieve(); + int p = heap_find_pool(h, x); + bool parked = p >= 0 && h->pools[p].parked; + + ray_free(y); + relieve_env_end(&e, h, NULL); + TEST_ASSERT(layout && cached && queued, "pool 1 held only queued blocks"); + TEST_ASSERT(parked, "the pool was found empty and parked"); + PASS(); +} + +/* Pool-worker tasks: each worker keeps one half-pool block live, then takes + * `empty` more (one when 0, at most 4) and frees them, leaving its heap that + * many empty pools, none of them its last. */ +#define RELIEVE_WORKERS 64 +typedef struct { + _Atomic(int) ran[RELIEVE_WORKERS]; + ray_t* keep[RELIEVE_WORKERS]; + int empty; +} relieve_workers_t; + +static void relieve_worker_task(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)start; (void)end; + relieve_workers_t* w = raw; + if (wid == 0 || wid >= RELIEVE_WORKERS) return; /* the dispatching thread */ + if (!w->keep[wid]) w->keep[wid] = ray_alloc(RELIEVE_HALF); + ray_t* b[4] = {0}; + int n = w->empty < 1 ? 1 : w->empty > 4 ? 4 : w->empty; + for (int i = 0; i < n; i++) + if ((b[i] = ray_alloc(RELIEVE_HALF))) memset(ray_data(b[i]), 1, 4096); + for (int i = 0; i < n; i++) if (b[i]) ray_free(b[i]); + atomic_store_explicit(&w->ran[wid], 1, memory_order_relaxed); +} + +/* The empty pools each worker is to keep for at least `pools` in all, + * whatever the number of workers. */ +static int relieve_worker_share(int pools) { + ray_pool_t* pool = ray_pool_get(); + int n = pool ? (int)pool->n_workers : 0; + return n > 0 ? (pools + n - 1) / n : 1; +} + +/* Dispatch until every worker has run a task; false without workers. */ +static bool relieve_worker_pool(relieve_workers_t* w) { + ray_pool_t* pool = ray_pool_get(); + if (!pool || pool->n_workers == 0 || pool->n_workers >= RELIEVE_WORKERS) return false; + uint32_t n = pool->n_workers, done = 0; + for (uint32_t i = 1; i <= n; i++) atomic_store(&w->ran[i], 0); + for (int round = 0; round < 1000 && done < n; round++) { + ray_pool_dispatch_n(pool, relieve_worker_task, w, 64); + done = 0; + for (uint32_t i = 1; i <= n; i++) done += atomic_load(&w->ran[i]) != 0; + } + return done == n; +} + +static void relieve_count_pools(ray_heap_t* h, void* ctx) { + *(uint32_t*)ctx += h->pool_count; +} +static uint32_t relieve_worker_pools(void) { + uint32_t n = 0; + ray_pool_each_worker_heap(relieve_count_pools, &n); + return n; +} + +/* A relief that takes the pool workers' empty pools leaves the heap that + * spilled a pool its anonymous ones: it ran out of them, they are parked. + * Its empty spill pool goes with the relief. */ +static test_result_t test_relieve_spilled_keeps(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + static relieve_workers_t w; + memset(&w, 0, sizeof w); + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + bool workers = relieve_worker_pool(&w); + uint32_t w0 = relieve_worker_pools(); + + /* Two anonymous pools, then a spill pool, all empty again. */ + ray_t* a1 = ray_alloc(RELIEVE_HALF); + ray_t* a2 = ray_alloc(RELIEVE_HALF); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_t* s1 = ray_alloc(RELIEVE_HALF); + bool layout = a1 && a2 && s1 && h->pool_count == 3 && relieve_pool_is_backed(h, s1); + if (s1) ray_free(s1); + if (a2) ray_free(a2); + if (a1) ray_free(a1); + + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_relieve(); + bool took = relieve_worker_pools() < w0; + bool kept = h->pool_count == 2 && relieve_backed_pools(h) == 0 + && relieve_parked(h) == 1; + + for (int i = 0; i < RELIEVE_WORKERS; i++) if (w.keep[i]) ray_free(w.keep[i]); + relieve_env_end(&e, h, NULL); + if (!workers) SKIP("no pool worker"); + if (!layout) SKIP("blocks or spill file unavailable"); + TEST_ASSERT(took, "the workers' empty pools went"); + TEST_ASSERT(kept, "the spilling heap's anonymous pools stayed, one parked"); + PASS(); +} + +/* A heap whose pools all spilled keeps one when a relief that acts — here on + * the workers' room — unmaps its empty spill pools, and serves blocks from + * it. */ +static test_result_t test_relieve_spill_disk_last(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + static relieve_workers_t w; + memset(&w, 0, sizeof w); + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + bool workers = relieve_worker_pool(&w); + uint32_t w0 = relieve_worker_pools(); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_t* s1 = ray_alloc(RELIEVE_HALF); + ray_t* s2 = ray_alloc(RELIEVE_HALF); + bool spilled = s1 && s2 && h->pool_count == 2 && relieve_backed_pools(h) == 2; + if (s2) ray_free(s2); + if (s1) ray_free(s1); + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_relieve(); + bool took = relieve_worker_pools() < w0; + bool last = h->pool_count == 1 && relieve_backed_pools(h) == 1; + ray_t* x = ray_alloc(RELIEVE_HALF); + bool serves = x && h->pool_count == 1 && relieve_pool_is_backed(h, x); + if (x) ray_free(x); + for (int i = 0; i < RELIEVE_WORKERS; i++) if (w.keep[i]) ray_free(w.keep[i]); + relieve_env_end(&e, h, NULL); + if (!workers) SKIP("no pool worker"); + if (!spilled) SKIP("no spill file"); + TEST_ASSERT(took, "the relief acted on the workers' room"); + TEST_ASSERT(last, "one spill pool unmapped, the last kept"); + TEST_ASSERT(serves, "and the heap serves blocks from it"); + PASS(); +} + +/* After a spill, the relief takes a pool worker's empty pool. When the + * statement after it does not spill but puts a large block in that room and + * runs up to the watermark, it needed the relief, and so will its repeat: + * its boundary relieves again. Not when the room went to pools only, not + * when the statement stayed clear of the watermark, and not when the room was + * the calling heap's own (heap_make_room gives that to a large block). */ +static test_result_t test_relieve_needed(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + static relieve_workers_t w; + memset(&w, 0, sizeof w); + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + /* x holds this heap's pool; the worker keeps a block and has exactly + * one empty pool, any older one handed back first. */ + ray_t* x = ray_alloc(RELIEVE_HALF); + bool workers = x && relieve_worker_pool(&w); + relieve_spill_elsewhere(&e); + ray_heap_relieve(); + workers = workers && relieve_worker_pool(&w); + uint32_t w0 = relieve_worker_pools(); + int64_t c0 = ray_heap_anon_committed(); + const size_t big = (size_t)48 << 20; + + /* A large block spills: the workers' empty pools go. */ + ray_heap_set_anon_watermark(c0 + 24 * RELIEVE_MB); + ray_t* d = workers ? ray_alloc(big) : NULL; + bool spilled = d && ray_direct_file_backed(d); + if (d) ray_free(d); + ray_heap_relieve(); + uint32_t w1 = relieve_worker_pools(); + bool took = w1 < w0; + + /* The repeat: the large block fits that room, then the workers take + * their pools back — up to the watermark, no spill: relieved again. */ + d = ray_alloc(big); + bool fit = d && !ray_direct_file_backed(d); + if (d) ray_free(d); + ray_heap_direct_cache_drain(); + relieve_worker_pool(&w); + bool back = relieve_worker_pools() == w0; + ray_heap_relieve(); + bool again = relieve_worker_pools() == w1; + + /* The room went to pools only — and to small off-heap blocks, which + * could not spill and do not count: not needed. */ + relieve_worker_pool(&w); + void* sm[48] = {0}; + for (int i = 0; i < 48; i++) sm[i] = ray_sys_alloc((size_t)768 << 10); + for (int i = 0; i < 48; i++) if (sm[i]) ray_sys_free(sm[i]); + ray_heap_relieve(); + bool pools_only = relieve_worker_pools() == w0; + + /* Clear of the watermark: not needed — however far past it the + * statement before the relief ran. */ + ray_heap_set_anon_watermark(INT64_C(1) << 40); + d = ray_alloc((size_t)256 << 20); + if (d) ray_free(d); + ray_heap_direct_cache_drain(); + ray_heap_set_anon_watermark(c0 + 80 * RELIEVE_MB); + d = ray_alloc((size_t)128 << 20); + bool spilled2 = d && ray_direct_file_backed(d); + if (d) ray_free(d); + ray_heap_relieve(); + d = ray_alloc((size_t)40 << 20); + if (d) ray_free(d); + ray_heap_direct_cache_drain(); + relieve_worker_pool(&w); + ray_heap_relieve(); + bool clear = relieve_worker_pools() == w0; + + /* The room was this heap's own: not needed. */ + bool spill = relieve_spill_elsewhere(&e); + ray_heap_relieve(); /* the workers' pools go */ + ray_t* y = ray_alloc(RELIEVE_HALF); + if (y) ray_free(y); + int64_t c1 = ray_heap_anon_committed(); + ray_heap_set_anon_watermark(c1 + 24 * RELIEVE_MB); + spill = relieve_spill_elsewhere(&e) && spill; + ray_heap_relieve(); /* y's pool goes */ + bool own = h->pool_count == 1; + d = ray_alloc(big); + bool fit2 = d && !ray_direct_file_backed(d); + if (d) ray_free(d); + ray_heap_direct_cache_drain(); + y = ray_alloc(RELIEVE_HALF); + if (y) ray_free(y); + ray_heap_relieve(); + bool own_kept = h->pool_count == 2; + + for (int i = 0; i < RELIEVE_WORKERS; i++) if (w.keep[i]) ray_free(w.keep[i]); + if (x) ray_free(x); + relieve_env_end(&e, h, NULL); + if (!workers) SKIP("no pool worker"); + if (!spilled || !spill) SKIP("no spill file"); + TEST_ASSERT(took, "a spill relieved the workers' empty pools"); + TEST_ASSERT(fit && back, "the repeat's large block fit, the workers took their pools back"); + TEST_ASSERT(again, "and its boundary relieved again"); + TEST_ASSERT(pools_only, "room gone to pools only: not relieved"); + TEST_ASSERT(spilled2, "a spill to start over"); + TEST_ASSERT(clear, "clear of the watermark: not relieved"); + TEST_ASSERT(own && fit2, "the heap's own pool went, its large block fit"); + TEST_ASSERT(own_kept, "room of the heap's own: not relieved"); + PASS(); +} + +/* A statement's peak is measured from the footprint the boundary before it + * left, not the one that boundary found: right after a relief that took the + * workers' pools, a light statement — a large block and a pool, well clear + * of the watermark — did not need it, however close the footprint was + * before the relief. Its boundary leaves the calling heap's pools be. */ +static test_result_t test_relieve_needed_baseline(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + static relieve_workers_t w; + memset(&w, 0, sizeof w); + w.empty = relieve_worker_share(2); /* room for the light statement */ + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + /* x holds this heap's pool; each worker keeps a block, and the workers + * have two empty pools or more between them, so the relief below leaves + * a light statement — a 40 MB block and a pool — clear of the watermark + * by more than a pool. */ + ray_t* x = ray_alloc(RELIEVE_HALF); + bool workers = x && relieve_worker_pool(&w); + relieve_spill_elsewhere(&e); + ray_heap_relieve(); + workers = workers && relieve_worker_pool(&w); + uint32_t w0 = relieve_worker_pools(); + int64_t c0 = ray_heap_anon_committed(); + + /* A large block spills: the relief takes the workers' empty pools. */ + ray_heap_set_anon_watermark(c0 + 24 * RELIEVE_MB); + ray_t* d = workers ? ray_alloc((size_t)48 << 20) : NULL; + bool spilled = d && ray_direct_file_backed(d); + if (d) ray_free(d); + ray_heap_relieve(); + bool took = relieve_worker_pools() < w0; + int64_t after = ray_heap_anon_committed(); + + /* A light statement: a 40 MB block in RAM, then a second pool here. */ + d = ray_alloc((size_t)40 << 20); + bool fit = d && !ray_direct_file_backed(d); + if (d) ray_free(d); + ray_heap_direct_cache_drain(); + ray_t* y = ray_alloc(RELIEVE_HALF); + if (y) ray_free(y); + bool two = h->pool_count == 2; + bool light = after + ((int64_t)40 << 20) + RELIEVE_POOL < ray_heap_anon_watermark(); + ray_heap_relieve(); + bool kept = h->pool_count == 2; + + for (int i = 0; i < RELIEVE_WORKERS; i++) if (w.keep[i]) ray_free(w.keep[i]); + if (x) ray_free(x); + relieve_env_end(&e, h, NULL); + if (!workers) SKIP("no pool worker"); + if (!spilled) SKIP("no spill file"); + TEST_ASSERT(took, "a spill relieved the workers' empty pools"); + TEST_ASSERT(fit && two && light, "a light statement: a block in RAM and a second pool"); + TEST_ASSERT(kept, "it did not need the relief: its boundary kept both pools"); + PASS(); +} + +/* A statement is judged by its peak, not by the footprint it ends with: + * right after a relief that took the workers' pools, one that ran a large + * block up near the watermark and freed it before its boundary needed that + * relief — a repeat will run up there again — though it ends far below. */ +static test_result_t test_relieve_needed_peak(void) { +#if defined(_WIN32) + SKIP("file-backed spill is POSIX-only"); +#endif + static relieve_workers_t w; + memset(&w, 0, sizeof w); + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + + /* x holds this heap's pool; each worker keeps a block and has one + * empty pool. */ + ray_t* x = ray_alloc(RELIEVE_HALF); + bool workers = x && relieve_worker_pool(&w); + relieve_spill_elsewhere(&e); + ray_heap_relieve(); + workers = workers && relieve_worker_pool(&w); + int64_t c0 = ray_heap_anon_committed(); + + /* A large block spills: the relief takes the workers' empty pools. */ + ray_heap_set_anon_watermark(c0 + 40 * RELIEVE_MB); + ray_t* d = workers ? ray_alloc((size_t)48 << 20) : NULL; + bool spilled = d && ray_direct_file_backed(d); + if (d) ray_free(d); + ray_heap_relieve(); + int64_t after = ray_heap_anon_committed(); + int64_t room = c0 - after; /* the workers' pools taken */ + + /* The next statement peaks with a block of room + 24 MB — a pool short + * of the watermark — frees it, and ends with one more pool here. */ + d = room >= 24 * RELIEVE_MB ? ray_alloc((size_t)(room + 24 * RELIEVE_MB)) : NULL; + bool peaked = d && !ray_direct_file_backed(d); + if (d) ray_free(d); + ray_heap_direct_cache_drain(); + ray_t* y = ray_alloc(RELIEVE_HALF); + if (y) ray_free(y); + int64_t end = ray_heap_anon_committed(); + bool low = h->pool_count == 2 && end + RELIEVE_POOL <= ray_heap_anon_watermark(); + ray_heap_relieve(); + bool relieved = h->pool_count == 1; + + for (int i = 0; i < RELIEVE_WORKERS; i++) if (w.keep[i]) ray_free(w.keep[i]); + if (x) ray_free(x); + relieve_env_end(&e, h, NULL); + if (!workers) SKIP("no pool worker"); + if (!spilled) SKIP("no spill file"); + TEST_ASSERT(room >= 24 * RELIEVE_MB, "a spill relieved the workers' empty pools"); + TEST_ASSERT(peaked && low, "a block in RAM up near the watermark, freed: the end far below"); + TEST_ASSERT(relieved, "judged by its peak, it needed the relief: the empty pool went"); + PASS(); +} + +/* A parked pool is off the freelists: the small allocations of the next + * statement are cut from the heap's other pools and leave it whole, and the + * heap takes it back before it maps a new pool. The heap's last pool stays + * on the lists. The idle decay, and a merge into another heap, put parked + * pools back on the lists. */ +static test_result_t test_relieve_park(void) { +#if defined(_WIN32) + SKIP("no file spill, so no relief: the watermark decides nothing"); +#endif + enum { S = 256 }; + relieve_env_t e; + relieve_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { relieve_env_end(&e, NULL, NULL); SKIP("no fresh heap"); } + ray_t* x = ray_alloc(RELIEVE_HALF); + ray_t* y = ray_alloc(RELIEVE_HALF); + ray_t* z = ray_alloc(RELIEVE_HALF); + if (!x || !y || !z) { + if (x) ray_free(x); + if (y) ray_free(y); + if (z) ray_free(z); + relieve_env_end(&e, h, NULL); + SKIP("blocks unavailable"); + } + ray_free(y); + ray_free(z); + relieve_pressure(RELIEVE_POOL); + ray_heap_relieve(); + bool parked = relieve_parked(h) == 2; + + /* Small blocks come from pool 1. */ + ray_t* sm[S] = {0}; + bool whole = true; + for (int i = 0; i < S; i++) { + sm[i] = ray_alloc((size_t)(64 << (i % 8))); + whole = whole && sm[i] && heap_find_pool(h, sm[i]) == heap_find_pool(h, x); + } + whole = whole && relieve_parked(h) == 2 && h->pool_count == 3; + for (int i = 0; i < S; i++) if (sm[i]) ray_free(sm[i]); + + /* A half-pool block takes a parked pool back; nothing new is mapped. */ + int64_t c0 = ray_heap_anon_committed(); + ray_t* w = ray_alloc(RELIEVE_HALF); + bool back = w && relieve_parked(h) == 1 && h->pool_count == 3 + && ray_heap_anon_committed() == c0; + if (w) ray_free(w); + + /* All empty: the last pool stays on the lists. */ + ray_free(x); + ray_heap_relieve(); + bool last = relieve_parked(h) == 2 && h->pool_count == 3; + + /* The decay puts them back. */ + ray_heap_set_decay_ms(0); + ray_heap_note_activity(); + ray_heap_decay(); + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + bool decayed = relieve_parked(h) == 0 && h->pool_count == 3; + + /* So does an explicit page release. */ + ray_heap_relieve(); + ray_heap_release_pages(); + bool released = relieve_parked(h) == 0; + + /* So does a merge: the other heap allocates from them at once. */ + ray_heap_relieve(); + bool parked_again = relieve_parked(h) == 2; + ray_heap_t* dst = relieve_heap_new(&e); + bool merged = false; + if (dst) { + ray_heap_merge(h); + int64_t c1 = ray_heap_anon_committed(); + ray_t* m1 = ray_alloc(RELIEVE_HALF); + ray_t* m2 = ray_alloc(RELIEVE_HALF); + merged = m1 && m2 && h->pool_count == 0 && dst->pool_count == 3 + && relieve_parked(dst) == 0 && ray_heap_anon_committed() == c1; + if (m1) ray_free(m1); + if (m2) ray_free(m2); + } + relieve_env_end(&e, dst, h); + if (!dst) SKIP("no fresh heap"); + TEST_ASSERT(parked, "both empty pools were parked"); + TEST_ASSERT(whole, "small blocks left the parked pools alone"); + TEST_ASSERT(back, "a parked pool was taken back before a new one was mapped"); + TEST_ASSERT(last, "the heap's last pool stayed on the lists"); + TEST_ASSERT(decayed, "the decay put the parked pools back"); + TEST_ASSERT(released, "an explicit page release put them back"); + TEST_ASSERT(parked_again && merged, "a merge put them back too"); + PASS(); +} + static void direct_cache_churn(void* raw, uint32_t wid, int64_t start, int64_t end) { (void)wid; _Atomic(int)* errors = raw; @@ -3013,6 +5425,22 @@ static test_result_t test_footprint_index_and_direct(void) { PASS(); } +/* Run test t with parked spill pools unmapped rather than their pages + * discarded — as where a mapped range cannot be punched (macOS) — so that + * path runs on every platform. */ +static test_result_t relieve_unmapping(test_func_t t) { + bool was = ray_heap_set_spill_discard(false); + test_result_t r = t(); + (void)ray_heap_set_spill_discard(was); + return r; +} +static test_result_t test_relieve_spill_pools_unmap(void) { return relieve_unmapping(test_relieve_spill_pools); } +static test_result_t test_relieve_spill_age_unmap(void) { return relieve_unmapping(test_relieve_spill_age); } +static test_result_t test_relieve_far_visit_unmap(void) { return relieve_unmapping(test_relieve_far_visit); } +static test_result_t test_relieve_spill_not_room_unmap(void) { return relieve_unmapping(test_relieve_spill_not_room); } +static test_result_t test_relieve_spill_last_pool_unmap(void) { return relieve_unmapping(test_relieve_spill_last_pool); } +static test_result_t test_relieve_futile_unmap(void) { return relieve_unmapping(test_relieve_futile); } + /* ---- Suite definition -------------------------------------------------- */ const test_entry_t heap_entries[] = { @@ -3091,6 +5519,48 @@ const test_entry_t heap_entries[] = { { "heap/order_overflow_guards", test_order_overflow_guards, heap_setup, heap_teardown }, { "heap/direct_cache_many_entries", test_direct_cache_many_entries, heap_setup, heap_teardown }, { "heap/direct_cache_replaces_old", test_direct_cache_replaces_old_blocks, heap_setup, heap_teardown }, + { "heap/sys_alloc_watermark", test_sys_alloc_watermark, heap_setup, heap_teardown }, + { "heap/sys_alloc_zero_fill", test_sys_alloc_zero_fill, heap_setup, heap_teardown }, + { "heap/raw_discard", test_raw_discard, heap_setup, heap_teardown }, + { "heap/relieve_under_pressure", test_relieve_under_pressure, heap_setup, heap_teardown }, + { "heap/relieve_needs_room", test_relieve_needs_room, heap_setup, heap_teardown }, + { "heap/relieve_drains_flushes", test_relieve_drains_and_flushes, heap_setup, heap_teardown }, + { "heap/relieve_many_pools", test_relieve_many_pools, heap_setup, heap_teardown }, + { "heap/relieve_inflight_free", test_relieve_inflight_free, heap_setup, heap_teardown }, + { "heap/relieve_spill_pools", test_relieve_spill_pools, heap_setup, heap_teardown }, + { "heap/relieve_spill_pools_unmap", test_relieve_spill_pools_unmap, heap_setup, heap_teardown }, + { "heap/relieve_spill_discard", test_relieve_spill_discard, heap_setup, heap_teardown }, + { "heap/relieve_spill_fallback", test_relieve_spill_fallback, heap_setup, heap_teardown }, + { "heap/relieve_spill_cloexec", test_relieve_spill_cloexec, heap_setup, heap_teardown }, + { "heap/relieve_spill_age", test_relieve_spill_age, heap_setup, heap_teardown }, + { "heap/relieve_spill_age_unmap", test_relieve_spill_age_unmap, heap_setup, heap_teardown }, + { "heap/relieve_far_visit", test_relieve_far_visit, heap_setup, heap_teardown }, + { "heap/relieve_far_visit_unmap", test_relieve_far_visit_unmap, heap_setup, heap_teardown }, + { "heap/relieve_spill_not_room", test_relieve_spill_not_room, heap_setup, heap_teardown }, + { "heap/relieve_spill_not_room_unmap", test_relieve_spill_not_room_unmap, heap_setup, heap_teardown }, + { "heap/relieve_abandon_spill", test_relieve_abandon_spill, heap_setup, heap_teardown }, + { "heap/relieve_spill_last_pool", test_relieve_spill_last_pool, heap_setup, heap_teardown }, + { "heap/relieve_spill_last_pool_unmap", test_relieve_spill_last_pool_unmap, heap_setup, heap_teardown }, + { "heap/relieve_no_spill_file", test_relieve_no_spill_file, heap_setup, heap_teardown }, + { "heap/relieve_last_pool", test_relieve_last_pool, heap_setup, heap_teardown }, + { "heap/decay_unmaps_spill_pools", test_decay_unmaps_spill_pools, heap_setup, heap_teardown }, + { "heap/relieve_skips_other_heaps", test_relieve_skips_other_heaps, heap_setup, heap_teardown }, + { "heap/relieve_steady_state", test_relieve_steady_state, heap_setup, heap_teardown }, + { "heap/relieve_needs_spill", test_relieve_needs_spill, heap_setup, heap_teardown }, + { "heap/relieve_futile", test_relieve_futile, heap_setup, heap_teardown }, + { "heap/relieve_futile_unmap", test_relieve_futile_unmap, heap_setup, heap_teardown }, + { "heap/relieve_spill_parks", test_relieve_spill_parks, heap_setup, heap_teardown }, + { "heap/relieve_spill_only", test_relieve_spill_only, heap_setup, heap_teardown }, + { "heap/relieve_make_room", test_relieve_make_room, heap_setup, heap_teardown }, + { "heap/relieve_make_room_drains", test_relieve_make_room_drains, heap_setup, heap_teardown }, + { "heap/relieve_visit_drains", test_relieve_visit_drains, heap_setup, heap_teardown }, + { "heap/relieve_spill_reads", test_relieve_spill_reads, heap_setup, heap_teardown }, + { "heap/relieve_spilled_keeps", test_relieve_spilled_keeps, heap_setup, heap_teardown }, + { "heap/relieve_spill_disk_last", test_relieve_spill_disk_last, heap_setup, heap_teardown }, + { "heap/relieve_needed", test_relieve_needed, heap_setup, heap_teardown }, + { "heap/relieve_needed_baseline", test_relieve_needed_baseline, heap_setup, heap_teardown }, + { "heap/relieve_needed_peak", test_relieve_needed_peak, heap_setup, heap_teardown }, + { "heap/relieve_park", test_relieve_park, heap_setup, heap_teardown }, { "heap/direct_cache_concurrent", test_direct_cache_concurrent_replacement, heap_setup, heap_teardown }, { "heap/anon_watermark_spill", test_anon_watermark_spill, heap_setup, heap_teardown }, { "heap/slab_byte_budget", test_slab_byte_budget, heap_setup, heap_teardown }, diff --git a/test/test_index.c b/test/test_index.c index bcba719ff..80cfb72f8 100644 --- a/test/test_index.c +++ b/test/test_index.c @@ -28,6 +28,7 @@ #include "mem/heap.h" #include "mem/sys.h" #include "core/pool.h" +#include "core/platform.h" #include "mem/cow.h" #include "vec/vec.h" #include "table/sym.h" @@ -35,12 +36,15 @@ #include "ops/rowsel.h" #include "store/col.h" #include +#include +#include #include #include #include #include #include #include +#include /* ─── Helpers ──────────────────────────────────────────────────────── */ @@ -286,12 +290,12 @@ static test_result_t test_index_hash_attach_drop(void) { TEST_ASSERT_EQ_I(ix->u.hash.offs->len, 5); /* CSR slice for key 7: rows 0 and 2 (both store 7), ascending. */ - const int64_t* grows = NULL; + ray_idx_rows_t grows = { NULL, false }; int64_t gn = 0; TEST_ASSERT_EQ_I(ray_index_hash_group(w, 7, &grows, &gn), 1); TEST_ASSERT_EQ_I(gn, 2); - TEST_ASSERT_EQ_I(grows[0], 0); - TEST_ASSERT_EQ_I(grows[1], 2); + TEST_ASSERT_EQ_I(ray_idx_rows_at(grows, 0), 0); + TEST_ASSERT_EQ_I(ray_idx_rows_at(grows, 1), 2); /* Absent key → provable miss. */ TEST_ASSERT_EQ_I(ray_index_hash_group(w, 42, &grows, &gn), 0); @@ -332,10 +336,56 @@ static test_result_t test_index_hash_with_nulls_preserved(void) { PASS(); } -/* Large column: the build runs partition-parallel above 64k rows and must - * produce the serial walk's layout — groups in first-occurrence order, rows - * ascending inside a group, nulls excluded — checked against a reference - * computed the obvious way. */ +/* The hash index's key mix (the splitmix64 finalizer), restated here to + * check the layout the builder promises: groups in ascending order of the + * mix, each key's home slot in its top bits. */ +static uint64_t idx_mix64(uint64_t x) { + x ^= x >> 30; + x *= 0xbf58476d1ce4e5b9ULL; + x ^= x >> 27; + x *= 0x94d049bb133111ebULL; + x ^= x >> 31; + return x; +} +static int idx_mix_cmp(const void* a, const void* b) { + uint64_t x = idx_mix64((uint64_t)*(const int64_t*)a), y = idx_mix64((uint64_t)*(const int64_t*)b); + return x < y ? -1 : x > y; +} +static int64_t idx_arr_get(const ray_t* v, int64_t i) { + return v->type == RAY_I32 ? (int64_t)((const uint32_t*)ray_data((ray_t*)v))[i] + : ((const int64_t*)ray_data((ray_t*)v))[i]; +} +/* `ix`'s groups ascend by mix, and its slot table is exactly the one that + * inserting the groups in order with linear probing from the top-bit home + * gives. */ +static test_result_t idx_table_check(const ray_index_t* ix) { + TEST_ASSERT_TRUE(ix->markers & RAY_MARK_HASH_HIGH); + uint64_t mask = ix->u.hash.mask, cap = mask + 1; + TEST_ASSERT_EQ_I(ix->u.hash.table->len, (int64_t)cap); + int sh = __builtin_clzll(mask); + const int64_t* gk = (const int64_t*)ray_data(ix->u.hash.gkeys); + int64_t ng = ix->u.hash.n_groups; + int64_t* ref = (int64_t*)ray_sys_alloc((size_t)cap * sizeof(int64_t)); + TEST_ASSERT_NOT_NULL(ref); + memset(ref, 0, (size_t)cap * sizeof(int64_t)); + int64_t bad = 0; + for (int64_t g = 0; g < ng; g++) { + if (g > 0 && idx_mix64((uint64_t)gk[g - 1]) >= idx_mix64((uint64_t)gk[g])) bad++; + uint64_t s = idx_mix64((uint64_t)gk[g]) >> sh; + while (ref[s]) s = (s + 1) & mask; + ref[s] = g + 1; + } + for (uint64_t s = 0; s < cap; s++) + if (idx_arr_get(ix->u.hash.table, (int64_t)s) != ref[s]) bad++; + ray_sys_free(ref); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +} + +/* Large column: the build runs partition-parallel above 64k rows. Groups + * come in ascending order of the key's mix, rows ascend inside a group and + * nulls are excluded — checked against a reference computed the obvious + * way. */ static test_result_t test_index_hash_large_parallel(void) { ray_heap_init(); /* The parallel build needs the pool; create it before the attach so @@ -353,7 +403,8 @@ static test_result_t test_index_hash_large_parallel(void) { for (int64_t i = 0; i < n; i += 977) TEST_ASSERT_EQ_I(ray_vec_set_null_checked(v, i, true), RAY_OK); - /* reference: first-occurrence group ids and counts */ + /* reference: the distinct keys and their counts, then the groups in + * ascending order of the key's mixed hash */ int64_t* gid_of_key = (int64_t*)ray_sys_alloc((size_t)kmax * sizeof(int64_t)); int64_t* ref_key = (int64_t*)ray_sys_alloc((size_t)kmax * sizeof(int64_t)); int64_t* ref_cnt = (int64_t*)ray_sys_alloc((size_t)kmax * sizeof(int64_t)); @@ -363,10 +414,13 @@ static test_result_t test_index_hash_large_parallel(void) { for (int64_t i = 0; i < n; i++) { if (ray_vec_is_null(v, i)) continue; int64_t k = xs[i] + 17; - if (gid_of_key[k] < 0) { gid_of_key[k] = ref_groups; ref_key[ref_groups++] = xs[i]; } - ref_cnt[gid_of_key[k]]++; + if (gid_of_key[k] < 0) { gid_of_key[k] = 0; ref_key[ref_groups++] = xs[i]; } ref_keys++; } + qsort(ref_key, (size_t)ref_groups, sizeof(int64_t), idx_mix_cmp); + for (int64_t g = 0; g < ref_groups; g++) gid_of_key[ref_key[g] + 17] = g; + for (int64_t i = 0; i < n; i++) + if (!ray_vec_is_null(v, i)) ref_cnt[gid_of_key[xs[i] + 17]]++; ray_t* w = v; ray_t* r = ray_index_attach_hash(&w); @@ -376,29 +430,36 @@ static test_result_t test_index_hash_large_parallel(void) { TEST_ASSERT_EQ_I(ix->u.hash.n_keys, ref_keys); TEST_ASSERT_EQ_I(ix->u.hash.n_groups, ref_groups); const int64_t* gk = (const int64_t*)ray_data(ix->u.hash.gkeys); - const int64_t* of = (const int64_t*)ray_data(ix->u.hash.offs); - const int64_t* rw = (const int64_t*)ray_data(ix->u.hash.rows); - TEST_ASSERT_EQ_I(of[0], 0); - TEST_ASSERT_EQ_I(of[ref_groups], ref_keys); - /* Serial layout: groups in first-occurrence order, each with its count, - * rows ascending and all storing the group's key. */ + /* The slot table, group offsets and row ids are stored narrow below + * 2^32 rows. */ + TEST_ASSERT_EQ_I(ix->u.hash.table->type, RAY_I32); + TEST_ASSERT_EQ_I(ix->u.hash.offs->type, RAY_I32); + TEST_ASSERT_EQ_I(ix->u.hash.rows->type, RAY_I32); + const uint32_t* of = (const uint32_t*)ray_data(ix->u.hash.offs); + const uint32_t* rw = (const uint32_t*)ray_data(ix->u.hash.rows); + TEST_ASSERT_EQ_I((int64_t)of[0], 0); + TEST_ASSERT_EQ_I((int64_t)of[ref_groups], ref_keys); + /* Groups in hash order, each with its count, rows ascending and all + * storing the group's key; the table is the in-order insertion's. */ for (int64_t g = 0; g < ref_groups; g++) { TEST_ASSERT_EQ_I(gk[g], ref_key[g]); - TEST_ASSERT_EQ_I(of[g + 1] - of[g], ref_cnt[g]); - for (int64_t j = of[g]; j < of[g + 1]; j++) { + TEST_ASSERT_EQ_I((int64_t)of[g + 1] - (int64_t)of[g], ref_cnt[g]); + for (int64_t j = (int64_t)of[g]; j < (int64_t)of[g + 1]; j++) { TEST_ASSERT_EQ_I(xs[rw[j]], ref_key[g]); - if (j > of[g]) TEST_ASSERT_TRUE(rw[j] > rw[j - 1]); + if (j > (int64_t)of[g]) TEST_ASSERT_TRUE(rw[j] > rw[j - 1]); } } + test_result_t tr = idx_table_check(ix); + if (tr.status != TEST_PASS) return tr; /* table probes: every key resolves to its group, an absent key misses */ for (int64_t k = 0; k < kmax; k += 61) { - const int64_t* grows = NULL; + ray_idx_rows_t grows = { NULL, false }; int64_t gn = 0; TEST_ASSERT_EQ_I(ray_index_hash_group(w, k - 17, &grows, &gn), 1); TEST_ASSERT_EQ_I(gn, ref_cnt[gid_of_key[k]]); } { - const int64_t* grows = NULL; + ray_idx_rows_t grows = { NULL, false }; int64_t gn = 0; TEST_ASSERT_EQ_I(ray_index_hash_group(w, kmax + 1000, &grows, &gn), 0); } @@ -584,6 +645,729 @@ static test_result_t test_index_persistence_roundtrip(void) { PASS(); } +/* ─── Narrow hash index on disk ─────────────────────────────────────── + * + * Below 2^32 rows the hash index keeps its slot table, group offsets and + * row ids as 32-bit values; with top-bit homes it is written as layout + * generation 3. A column saved that way maps back with the same answers; + * low-bit tables as written before (generation 2 narrow, generation 1 with + * 64-bit arrays) still map; and a region whose generation disagrees with + * its arrays or its home rule is not trusted (the column loads unindexed). */ +static ray_t* idx_widen(ray_t* v) { + if (v->type != RAY_I32) return v; + ray_t* w = ray_vec_new(RAY_I64, v->len); + w->len = v->len; + for (int64_t i = 0; i < v->len; i++) + ((int64_t*)ray_data(w))[i] = (int64_t)((const uint32_t*)ray_data(v))[i]; + ray_release(v); + return w; +} +static ray_t* hx_test_narrow(ray_t* v) { + if (v->type != RAY_I64) return v; + ray_t* w = ray_vec_new(RAY_I32, v->len); + w->len = v->len; + for (int64_t i = 0; i < v->len; i++) + ((uint32_t*)ray_data(w))[i] = (uint32_t)((const int64_t*)ray_data(v))[i]; + ray_release(v); + return w; +} +static test_result_t idx_narrow_check(ray_t* col, int64_t n, int64_t keys) { + TEST_ASSERT_TRUE(col->attrs & RAY_ATTR_HAS_INDEX); + TEST_ASSERT_EQ_I(ray_index_kind(col), RAY_IDX_HASH); + for (int64_t k = 0; k < keys + 3; k++) { + int64_t want = k < keys ? k : -1; + TEST_ASSERT_EQ_I(ray_index_find_row(col, k), want); + ray_idx_rows_t rows = { NULL, false }; int64_t gn = 0; + int hit = ray_index_hash_group(col, k, &rows, &gn); + if (k >= keys) { TEST_ASSERT_EQ_I(hit, 0); continue; } + TEST_ASSERT_EQ_I(hit, 1); + TEST_ASSERT_EQ_I(gn, (n - 1 - k) / keys + 1); + for (int64_t j = 0; j < gn; j++) TEST_ASSERT_EQ_I(ray_idx_rows_at(rows, j), k + j * keys); + } + PASS(); +} +/* An interrupt makes a pool dispatch skip its tasks. Narrowing the arrays + * of a just-built hash index runs as one; interrupted there it must keep the + * wide arrays it was copying, not install an unfilled copy. */ +static test_result_t test_index_hash_narrow_interrupted(void) { + ray_heap_init(); + ray_pool_t* pool = ray_pool_get(); + if (!pool || pool->n_workers == 0) { ray_heap_destroy(); SKIP("needs pool workers"); } + const int64_t n = 200000, keys = 1000; + ray_t* v = ray_vec_new(RAY_STR, n); + char buf[16]; + for (int64_t i = 0; i < n; i++) { + int l = snprintf(buf, sizeof buf, "k%d", (int)(i % keys)); + v = ray_str_vec_append(v, buf, (size_t)l); + } + ray_t* w = v; + atomic_store(&pool->cancelled, 1); + ray_t* r = ray_index_attach_hash(&w); + atomic_store(&pool->cancelled, 0); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(ray_index_kind(w), RAY_IDX_HASH); + int64_t bad = 0; + for (int64_t k = 0; k < keys; k++) { + int l = snprintf(buf, sizeof buf, "k%d", (int)k); + ray_t* a = ray_str(buf, (size_t)l); + if (ray_index_find_atom(w, a) != k) bad++; + ray_release(a); + } + TEST_ASSERT_EQ_I(bad, 0); + ray_release(w); + ray_heap_destroy(); + PASS(); +} + +/* Overwrite one byte of the index region at the end of column file `path` + * (`off` from the region start). */ +static bool idx_patch_byte(const char* path, const ray_index_t* ix, int64_t off, uint8_t val) { + struct stat st; + if (stat(path, &st) != 0) return false; + int64_t region = ray_index_inline_size(ix); + FILE* f = fopen(path, "r+b"); + if (!f) return false; + bool ok = fseek(f, (long)(st.st_size - region + off), SEEK_SET) == 0 && + fwrite(&val, 1, 1, f) == 1; + fclose(f); + return ok; +} +/* Re-lay `ix`'s slot table as builders before the top-bit homes did (low + * bits, groups inserted in order), as an index persisted by them reads. */ +static void idx_low_layout(ray_index_t* ix) { + ray_t* t = ix->u.hash.table; + uint64_t mask = ix->u.hash.mask; + const int64_t* gk = (const int64_t*)ray_data(ix->u.hash.gkeys); + memset(ray_data(t), 0, (size_t)t->len * (size_t)ray_elem_size(t->type)); + for (int64_t g = 0; g < ix->u.hash.n_groups; g++) { + uint64_t s = idx_mix64((uint64_t)gk[g]) & mask; + while (idx_arr_get(t, (int64_t)s) != 0) s = (s + 1) & mask; + if (t->type == RAY_I32) ((uint32_t*)ray_data(t))[s] = (uint32_t)(g + 1); + else ((int64_t*)ray_data(t))[s] = g + 1; + } + ix->markers &= (uint8_t)~RAY_MARK_HASH_HIGH; +} +static test_result_t test_index_hash_narrow_roundtrip(void) { + ray_heap_init(); + const int64_t n = 100000, keys = 977; + 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 % keys; + ray_t* w = v; + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&w))); + ray_index_t* ix = ray_index_payload(w->index); + TEST_ASSERT_EQ_I(ix->u.hash.table->type, RAY_I32); + TEST_ASSERT_EQ_I(ix->u.hash.offs->type, RAY_I32); + TEST_ASSERT_EQ_I(ix->u.hash.rows->type, RAY_I32); + test_result_t r = idx_narrow_check(w, n, keys); + if (r.status != TEST_PASS) return r; + + char path[] = "/tmp/idx_narrow_XXXXXX"; + int fd = mkstemp(path); + TEST_ASSERT_TRUE(fd >= 0); + close(fd); + + /* generation 3: top-bit homes, narrow arrays map back as written */ + TEST_ASSERT_EQ_I(ray_col_save(w, path), RAY_OK); + ray_t* m = ray_col_mmap(path); + TEST_ASSERT_FALSE(RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(m->index->order, 3); + TEST_ASSERT_TRUE(ray_index_payload(m->index)->markers & RAY_MARK_HASH_HIGH); + TEST_ASSERT_EQ_I(ray_index_payload(m->index)->u.hash.offs->type, RAY_I32); + TEST_ASSERT_EQ_I(ray_index_payload(m->index)->u.hash.rows->type, RAY_I32); + r = idx_narrow_check(m, n, keys); + ray_release(m); + if (r.status != TEST_PASS) { unlink(path); return r; } + + /* the generation and the home rule must agree, either way round */ + const int64_t mk_off = 32 + (int64_t)offsetof(ray_index_t, markers); + TEST_ASSERT_TRUE(idx_patch_byte(path, ix, mk_off, (uint8_t)(ix->markers & ~RAY_MARK_HASH_HIGH))); + m = ray_col_mmap(path); + TEST_ASSERT_FALSE(RAY_IS_ERR(m)); + TEST_ASSERT_FALSE(m->attrs & RAY_ATTR_HAS_INDEX); + ray_release(m); + TEST_ASSERT_TRUE(idx_patch_byte(path, ix, mk_off, ix->markers)); + TEST_ASSERT_TRUE(idx_patch_byte(path, ix, (int64_t)offsetof(ray_t, order), 2)); + m = ray_col_mmap(path); + TEST_ASSERT_FALSE(RAY_IS_ERR(m)); + TEST_ASSERT_FALSE(m->attrs & RAY_ATTR_HAS_INDEX); + ray_release(m); + + /* generation 2: a low-bit table with narrow arrays still maps */ + idx_low_layout(ix); + TEST_ASSERT_EQ_I(ray_col_save(w, path), RAY_OK); + m = ray_col_mmap(path); + TEST_ASSERT_FALSE(RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(m->index->order, 2); + TEST_ASSERT_FALSE(ray_index_payload(m->index)->markers & RAY_MARK_HASH_HIGH); + r = idx_narrow_check(m, n, keys); + ray_release(m); + if (r.status != TEST_PASS) { unlink(path); return r; } + + /* generation 1: an index written with 64-bit arrays still maps */ + ix->u.hash.table = idx_widen(ix->u.hash.table); + ix->u.hash.offs = idx_widen(ix->u.hash.offs); + ix->u.hash.rows = idx_widen(ix->u.hash.rows); + TEST_ASSERT_EQ_I(ray_col_save(w, path), RAY_OK); + m = ray_col_mmap(path); + TEST_ASSERT_FALSE(RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(m->index->order, 1); + TEST_ASSERT_EQ_I(ray_index_payload(m->index)->u.hash.offs->type, RAY_I64); + TEST_ASSERT_EQ_I(ray_index_payload(m->index)->u.hash.rows->type, RAY_I64); + r = idx_narrow_check(m, n, keys); + ray_release(m); + if (r.status != TEST_PASS) { unlink(path); return r; } + + /* a generation-1 region holding a narrow array is not trusted */ + ix->u.hash.offs = hx_test_narrow(ix->u.hash.offs); + TEST_ASSERT_EQ_I(ray_col_save(w, path), RAY_OK); /* written as generation 2 */ + TEST_ASSERT_TRUE(idx_patch_byte(path, ix, (int64_t)offsetof(ray_t, order), 1)); + m = ray_col_mmap(path); + unlink(path); + TEST_ASSERT_FALSE(RAY_IS_ERR(m)); + TEST_ASSERT_FALSE(m->attrs & RAY_ATTR_HAS_INDEX); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(m))[978], 1); /* the data itself still reads */ + ray_release(m); + + ray_release(w); + ray_heap_destroy(); + PASS(); +} + +/* ─── Partitioned hash build ────────────────────────────────────────── + * + * Numeric and SYM columns are indexed by the partitioned builder: groups in + * ascending order of the key's mix, homes in the top bits, so the arrays + * follow from the data alone. */ + +/* n rows: a third of them one hot key, the rest spread, some null. */ +static ray_t* idx_part_col_n(int64_t n) { + ray_t* v = ray_vec_new(RAY_I64, n); + if (!v || RAY_IS_ERR(v)) return v; + v->len = n; + int64_t* xs = (int64_t*)ray_data(v); + uint64_t s = 0x9E3779B97F4A7C15ULL; + for (int64_t i = 0; i < n; i++) { + s = s * 6364136223846793005ULL + 1442695040888963407ULL; + xs[i] = (s >> 33) % 3 == 0 ? 42 : (int64_t)((s >> 20) % 700000) - 350000; + } + for (int64_t i = 0; i < n; i += 1013) ray_vec_set_null_checked(v, i, true); + return v; +} +static ray_t* idx_part_col(void) { return idx_part_col_n(2000000); } +static bool idx_arr_same(const ray_t* a, const ray_t* b) { + return a->type == b->type && a->len == b->len && + memcmp(ray_data((ray_t*)a), ray_data((ray_t*)b), + (size_t)a->len * (size_t)ray_elem_size(a->type)) == 0; +} +static bool idx_same(const ray_index_t* a, const ray_index_t* b) { + return a->u.hash.n_groups == b->u.hash.n_groups && a->u.hash.n_keys == b->u.hash.n_keys && + a->u.hash.mask == b->u.hash.mask && a->markers == b->markers && + idx_arr_same(a->u.hash.table, b->u.hash.table) && + idx_arr_same(a->u.hash.gkeys, b->u.hash.gkeys) && + idx_arr_same(a->u.hash.offs, b->u.hash.offs) && + idx_arr_same(a->u.hash.rows, b->u.hash.rows); +} + +/* The same column built in parallel, serially, and under a memory budget + * small enough to split it into many more partitions and batches (the hot + * key's partition alone is larger than a batch) gives the same bytes; the + * groups cover every non-null row exactly once. */ +static test_result_t test_index_hash_part_invariant(void) { + ray_heap_init(); + (void)ray_pool_get(); + ray_t* cols[3]; + for (int c = 0; c < 3; c++) { + cols[c] = idx_part_col(); + TEST_ASSERT_FALSE(RAY_IS_ERR(cols[c])); + if (c == 1) atomic_store(&ray_parallel_flag, 1); + if (c == 2) ray_heap_set_anon_watermark(INT64_C(4) << 20); + ray_t* r = ray_index_attach_hash(&cols[c]); + if (c == 1) atomic_store(&ray_parallel_flag, 0); + if (c == 2) ray_heap_set_anon_watermark(0); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(ray_index_kind(cols[c]), RAY_IDX_HASH); + } + const ray_index_t* ix = ray_index_payload(cols[0]->index); + TEST_ASSERT_TRUE(idx_same(ix, ray_index_payload(cols[1]->index))); + TEST_ASSERT_TRUE(idx_same(ix, ray_index_payload(cols[2]->index))); + test_result_t tr = idx_table_check(ix); + if (tr.status != TEST_PASS) return tr; + + ray_t* v = cols[0]; + const int64_t* xs = (const int64_t*)ray_data(v); + const int64_t* gk = (const int64_t*)ray_data(ix->u.hash.gkeys); + int64_t n = v->len, nn = 0, bad = 0; + uint8_t* seen = (uint8_t*)ray_sys_alloc((size_t)n); + TEST_ASSERT_NOT_NULL(seen); + memset(seen, 0, (size_t)n); + for (int64_t g = 0; g < ix->u.hash.n_groups; g++) { + int64_t lo = idx_arr_get(ix->u.hash.offs, g), hi = idx_arr_get(ix->u.hash.offs, g + 1); + if (hi <= lo) bad++; + for (int64_t j = lo; j < hi; j++) { + int64_t row = idx_arr_get(ix->u.hash.rows, j); + if (seen[row]++ || ray_vec_is_null(v, row) || xs[row] != gk[g]) bad++; + if (j > lo && row <= idx_arr_get(ix->u.hash.rows, j - 1)) bad++; + } + } + for (int64_t i = 0; i < n; i++) { + if (ray_vec_is_null(v, i)) { if (seen[i]) bad++; continue; } + nn++; + if (!seen[i]) bad++; + } + ray_sys_free(seen); + TEST_ASSERT_EQ_I(bad, 0); + TEST_ASSERT_EQ_I(ix->u.hash.n_keys, nn); + for (int c = 0; c < 3; c++) ray_release(cols[c]); + ray_heap_destroy(); + PASS(); +} + +/* Small tables: a run of slots that passes the last slot continues from + * slot 0. Many small random columns, each checked slot by slot and probed + * for every key and for absent ones; some of them must wrap for the test + * to mean anything. */ +static test_result_t test_index_hash_part_wraps(void) { + ray_heap_init(); + uint64_t s = 12345; + int64_t wraps = 0, bad = 0; + for (int t = 0; t < 2000; t++) { + int64_t m = 2 + t % 30, n = 3 * m; + int64_t keys[32]; + for (int64_t k = 0; k < m; k++) { + s = s * 6364136223846793005ULL + 1442695040888963407ULL; + keys[k] = (int64_t)s; + } + ray_t* v = ray_vec_new(RAY_I64, n); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + v->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = keys[(i * 7) % m]; + ray_t* w = v; + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&w))); + const ray_index_t* ix = ray_index_payload(w->index); + test_result_t tr = idx_table_check(ix); + if (tr.status != TEST_PASS) return tr; + int sh = __builtin_clzll(ix->u.hash.mask); + const int64_t* gk = (const int64_t*)ray_data(ix->u.hash.gkeys); + for (int64_t sl = 0; sl <= (int64_t)ix->u.hash.mask; sl++) { + int64_t g1 = idx_arr_get(ix->u.hash.table, sl); + if (g1 && (int64_t)(idx_mix64((uint64_t)gk[g1 - 1]) >> sh) > sl) { wraps++; break; } + } + for (int64_t k = 0; k < m; k++) { + int64_t first = -1; + for (int64_t i = 0; i < n && first < 0; i++) + if (((int64_t*)ray_data(w))[i] == keys[k]) first = i; + if (ray_index_find_row(w, keys[k]) != first) bad++; + } + if (ray_index_find_row(w, keys[0] ^ 1) != -1 && (keys[0] ^ 1) != keys[1]) bad++; + ray_release(w); + } + TEST_ASSERT_EQ_I(bad, 0); + TEST_ASSERT_TRUE(wraps > 0); + ray_heap_destroy(); + PASS(); +} + +/* An interrupt makes a pool dispatch skip its tasks: the build reports the + * cancel and leaves the column unindexed, and the next build is whole. */ +static test_result_t test_index_hash_part_interrupted(void) { + ray_heap_init(); + ray_pool_t* pool = ray_pool_get(); + if (!pool) { ray_heap_destroy(); SKIP("needs the pool"); } + const int64_t n = 300000; + ray_t* v = ray_vec_new(RAY_I64, n); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + v->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = i % 5000; + ray_t* w = v; + atomic_store(&pool->cancelled, 1); + ray_t* r = ray_index_attach_hash(&w); + atomic_store(&pool->cancelled, 0); + TEST_ASSERT_TRUE(RAY_IS_ERR(r)); + ray_error_free(r); + TEST_ASSERT_FALSE(w->attrs & RAY_ATTR_HAS_INDEX); + r = ray_index_attach_hash(&w); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + test_result_t tr = idx_narrow_check(w, n, 5000); + if (tr.status != TEST_PASS) return tr; + tr = idx_table_check(ray_index_payload(w->index)); + if (tr.status != TEST_PASS) return tr; + ray_release(w); + ray_heap_destroy(); + PASS(); +} + +/* The interrupt can land anywhere in the build, in particular inside a + * batch's row pass, whose skipped tasks leave their partitions in hand. + * One build is timed, then interrupts are raised at points spread over + * that time, under a budget that splits the column into many batches: + * each attempt either reports the cancel and leaves the column as it was, + * or completes with exactly the uninterrupted index, and the build after + * each attempt is whole. */ +static int64_t idx_now_ns(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; +} +static void idx_interrupt_after(void* arg) { + int64_t ns = *(const int64_t*)arg; + struct timespec ts = { (time_t)(ns / 1000000000), (long)(ns % 1000000000) }; + nanosleep(&ts, NULL); + ray_request_interrupt(); +} +static test_result_t test_index_hash_part_interrupt_sweep(void) { + ray_heap_init(); + ray_pool_t* pool = ray_pool_get(); + if (!pool || ray_pool_total_workers(pool) < 2) { ray_heap_destroy(); SKIP("needs workers"); } + ray_heap_set_anon_watermark(INT64_C(64) << 20); /* batches of 128K rows */ + ray_t* ref = idx_part_col_n(500000); + TEST_ASSERT_FALSE(RAY_IS_ERR(ref)); + int64_t t0 = idx_now_ns(); + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&ref))); + int64_t took = idx_now_ns() - t0; + const ray_index_t* rix = ray_index_payload(ref->index); + int64_t cancelled = 0, bad = 0; + for (int k = 0; k < 6; k++) { + ray_t* v = idx_part_col_n(500000); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + int64_t delay = took * k / 6; + ray_thread_t th; + TEST_ASSERT_EQ_I(ray_thread_create(&th, idx_interrupt_after, &delay), RAY_OK); + ray_t* r = ray_index_attach_hash(&v); + ray_thread_join(th); + ray_clear_interrupt(); + if (RAY_IS_ERR(r)) { + cancelled++; + ray_error_free(r); + if (v->attrs & RAY_ATTR_HAS_INDEX) bad++; + if (memcmp(ray_data(v), ray_data(ref), (size_t)v->len * 8) != 0) bad++; + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&v))); + } + if (!idx_same(rix, ray_index_payload(v->index))) bad++; + ray_release(v); + } + ray_heap_set_anon_watermark(0); + TEST_ASSERT_EQ_I(bad, 0); + TEST_ASSERT_TRUE(cancelled > 0); + ray_release(ref); + ray_heap_destroy(); + PASS(); +} + +/* ─── Hash index built in place ────────────────────────────────────────── + * + * ray_index_hash_build_region writes into memory the caller hands it the + * region ray_index_inline_write lays out for the index ray_index_attach_hash + * builds — byte for byte, block headers included — whatever the shape, + * memory budget or core count. The memory here stands in for the column + * file the store maps. */ +typedef struct { uint8_t* buf; int64_t bytes; int calls; bool fail; } idx_region_ctx_t; +static uint8_t* idx_region_map(void* raw, int64_t bytes) { + idx_region_ctx_t* c = (idx_region_ctx_t*)raw; + c->calls++; + if (c->fail) return NULL; + c->buf = (uint8_t*)ray_calloc_raw((size_t)bytes); + c->bytes = bytes; + return c->buf; +} + +/* n rows of `type`, keys spread over `keys` values (negative ones too), every + * null_every-th row null (0: none). */ +static ray_t* idx_reg_col(int8_t type, int64_t n, int64_t keys, int64_t null_every) { + ray_t* v = type == RAY_SYM ? ray_sym_vec_new(RAY_SYM_W32, n > 0 ? n : 1) + : ray_vec_new(type, n > 0 ? n : 1); + if (!v || RAY_IS_ERR(v)) return v; + v->len = n; + void* d = ray_data(v); + for (int64_t i = 0; i < n; i++) { + int64_t k = (int64_t)(((uint64_t)i * 2654435761ull) % (uint64_t)keys) - keys / 3; + switch (type) { + case RAY_BOOL: ((uint8_t*)d)[i] = (uint8_t)(k & 1); break; + case RAY_U8: ((uint8_t*)d)[i] = (uint8_t)k; break; + case RAY_I16: ((int16_t*)d)[i] = (int16_t)k; break; + case RAY_I32: case RAY_DATE: ((int32_t*)d)[i] = (int32_t)k; break; + case RAY_I64: case RAY_TIMESTAMP: ((int64_t*)d)[i] = k * 1000003; break; + case RAY_F64: ((double*)d)[i] = k == 0 ? -0.0 : k == 1 ? 0.0 : (double)k * 0.25; break; + case RAY_SYM: ((uint32_t*)d)[i] = (uint32_t)(k + keys); break; + default: break; + } + } + for (int64_t i = 0; null_every && i < n; i += null_every) + if (ray_vec_set_null_checked(v, i, true) != RAY_OK) { ray_release(v); return NULL; } + return v; +} + +/* The region of `v` built in place equals the one of its attached index; + * `ref` (may be NULL) keeps that index's region for the caller. */ +static bool idx_region_same(ray_t* v, idx_region_ctx_t* ref) { + idx_region_ctx_t c = {0}; + ray_err_t e = ray_index_hash_build_region(v, idx_region_map, &c, NULL); + ray_t* w = v; + ray_retain(w); /* the attach builds on a copy */ + ray_t* r = ray_index_attach_hash(&w); + bool ok = e == RAY_OK && c.calls == 1 && !RAY_IS_ERR(r); + if (!RAY_IS_ERR(r)) { + const ray_index_t* ix = ray_index_payload(w->index); + int64_t size = ray_index_inline_size(ix); + uint8_t* want = (uint8_t*)ray_calloc_raw((size_t)size); + ray_index_inline_write(want, ix); + ok = ok && size == c.bytes && memcmp(want, c.buf, (size_t)size) == 0; + if (ref) { ref->buf = want; ref->bytes = size; } else ray_free_raw(want); + } else { + ray_error_free(r); + } + ray_release(w); + ray_free_raw(c.buf); + return ok; +} + +typedef struct { int8_t type; int64_t n, keys, null_every; } idx_reg_shape_t; +static const idx_reg_shape_t idx_reg_shapes[] = { + { RAY_I64, 200000, 200000, 0 }, /* every key distinct */ + { RAY_I64, 300000, 5003, 977 }, /* gkeys and offs cut to the groups */ + { RAY_I32, 1000, 10, 0 }, /* few groups, kept at the key count */ + { RAY_F64, 100000, 2003, 101 }, /* -0.0, +0.0 and NaN */ + { RAY_DATE, 70000, 3000, 13 }, + { RAY_TIMESTAMP, 90000, 90000, 0 }, + { RAY_I16, 50000, 30000, 7 }, + { RAY_U8, 20000, 256, 0 }, + { RAY_BOOL, 5000, 2, 0 }, + { RAY_SYM, 120000, 997, 0 }, /* domain ids */ + { RAY_I64, 0, 1, 0 }, /* empty */ + { RAY_I64, 1, 1, 0 }, /* one row */ + { RAY_I64, 2000, 50, 1 }, /* every row null */ +}; + +/* Every shape under three plans: the default (one batch), serial, and a + * budget small enough for many batches and the counting pass; each gives + * the attached index's region. */ +static test_result_t test_index_hash_region_bytes(void) { + ray_heap_init(); + (void)ray_pool_get(); + int64_t bad = 0; + for (int plan = 0; plan < 3; plan++) { + if (plan == 1) atomic_store(&ray_parallel_flag, 1); + if (plan == 2) ray_heap_set_anon_watermark(INT64_C(4) << 20); + for (size_t s = 0; s < sizeof(idx_reg_shapes) / sizeof(idx_reg_shapes[0]); s++) { + const idx_reg_shape_t* sh = &idx_reg_shapes[s]; + ray_t* v = idx_reg_col(sh->type, sh->n, sh->keys, sh->null_every); + if (!v || RAY_IS_ERR(v)) { bad++; continue; } + if (!idx_region_same(v, NULL)) bad++; + ray_release(v); + } + ray_t* hot = idx_part_col_n(300000); /* a partition larger than a batch */ + if (!idx_region_same(hot, NULL)) bad++; + ray_release(hot); + if (plan == 1) atomic_store(&ray_parallel_flag, 0); + if (plan == 2) ray_heap_set_anon_watermark(0); + } + TEST_ASSERT_EQ_I(bad, 0); + ray_heap_destroy(); + PASS(); +} + +/* A column with arrays past the pool order, direct blocks in memory whose + * headers carry the direct order byte, and arrays below it: 2.2M distinct + * keys (gkeys 17.6 MB and table 32 MB direct, offs and rows 8.8 MB not; key + * words 17.6 MB), built in many batches against the in-memory build's own + * sizing. Spilled, each batch's key words are punched out of their spill + * file once read and the later batches still find theirs, and the blocks + * are freed as direct blocks after (the punch spares their header page); + * anonymous, they are left alone. */ +static test_result_t test_index_hash_region_discard(void) { + ray_heap_init(); + (void)ray_pool_get(); + ray_t* v = idx_reg_col(RAY_I64, 2200000, 2200000, 0); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + int64_t bad = 0; + for (int plan = 0; plan < 2; plan++) { + ray_heap_direct_cache_drain(); + ray_mem_stats_t s0, s1; + ray_mem_stats(&s0); + ray_heap_set_anon_watermark(plan == 0 ? INT64_C(4) << 20 + : ray_heap_anon_committed() + (INT64_C(96) << 20)); + if (!idx_region_same(v, NULL)) bad++; + ray_heap_set_anon_watermark(0); + ray_mem_stats(&s1); + if (s1.direct_bytes != s0.direct_bytes || s1.direct_count != s0.direct_count) bad++; + } + TEST_ASSERT_EQ_I(bad, 0); + ray_release(v); + ray_heap_destroy(); + PASS(); +} + +/* The block headers keep their arrays' allocation order: gkeys and offs are + * allocated for the keys and cut to the groups only when the slack is worth + * a copy, so a region built in place must take the same capacities. */ +static test_result_t test_index_hash_region_capacity(void) { + ray_heap_init(); + ray_t* few = idx_reg_col(RAY_I32, 1000, 10, 0); /* slack under 1 MB: kept */ + ray_t* many = idx_reg_col(RAY_I64, 300000, 5003, 0); /* cut */ + TEST_ASSERT_FALSE(RAY_IS_ERR(few)); TEST_ASSERT_FALSE(RAY_IS_ERR(many)); + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&few))); + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&many))); + const ray_index_t* a = ray_index_payload(few->index); + const ray_index_t* b = ray_index_payload(many->index); + TEST_ASSERT_EQ_I(a->u.hash.n_groups, 10); + TEST_ASSERT_EQ_I(a->u.hash.gkeys->order, ray_order_for_size(1000 * 8)); + TEST_ASSERT_EQ_I(a->u.hash.offs->order, ray_order_for_size(1001 * 4)); + TEST_ASSERT_EQ_I(b->u.hash.n_groups, 5003); + TEST_ASSERT_EQ_I(b->u.hash.gkeys->order, ray_order_for_size(5003 * 8)); + /* and the regions built in place say the same */ + ray_t* v1 = idx_reg_col(RAY_I32, 1000, 10, 0); + ray_t* v2 = idx_reg_col(RAY_I64, 300000, 5003, 0); + TEST_ASSERT_TRUE(idx_region_same(v1, NULL)); + TEST_ASSERT_TRUE(idx_region_same(v2, NULL)); + ray_release(v1); ray_release(v2); + ray_release(few); ray_release(many); + ray_heap_destroy(); + PASS(); +} + +/* Row ids past 32 bits take 64-bit arrays; the threshold is lowered here + * (debug builds) so a small column takes that layout. */ +static test_result_t test_index_hash_region_wide(void) { +#if defined(DEBUG) + ray_heap_init(); + (void)ray_pool_get(); + TEST_ASSERT_EQ_I(setenv("RAY_HASH_WIDE_ROWS", "100", 1), 0); + int64_t bad = 0; + for (int plan = 0; plan < 2; plan++) { + if (plan == 1) ray_heap_set_anon_watermark(INT64_C(4) << 20); + ray_t* v = idx_reg_col(RAY_I64, 300000, 5003, 977); + idx_region_ctx_t ref = {0}; + if (!idx_region_same(v, &ref)) bad++; + /* the table, offs and rows blocks are I64 in the region */ + ray_t* m = ref.buf ? ray_index_inline_map(ref.buf, ref.bytes) : NULL; + if (!m) bad++; + else { + const ray_index_t* ix = ray_index_payload(m); + if (ix->u.hash.table->type != RAY_I64 || ix->u.hash.offs->type != RAY_I64 || + ix->u.hash.rows->type != RAY_I64 || ix->u.hash.n_groups != 5003) bad++; + } + ray_free_raw(ref.buf); + ray_t* w = idx_reg_col(RAY_I32, 1000, 10, 0); + if (!idx_region_same(w, NULL)) bad++; + ray_release(v); ray_release(w); + if (plan == 1) ray_heap_set_anon_watermark(0); + } + unsetenv("RAY_HASH_WIDE_ROWS"); + TEST_ASSERT_EQ_I(bad, 0); + ray_heap_destroy(); + PASS(); +#else + SKIP("RAY_HASH_WIDE_ROWS is read by debug builds only"); +#endif +} + +/* What the in-place build refuses or fails on: a STR column (the attach + * keeps its own walk) and a slice before anything is mapped; a mapping that + * cannot be made; and a column already carrying another index, whose + * pre-index aux the region records as the attach does after dropping it. + * A failed build leaves nothing allocated. */ +static test_result_t test_index_hash_region_guards(void) { + ray_heap_init(); + (void)ray_pool_get(); + idx_region_ctx_t c = {0}; + ray_t* s = ray_vec_new(RAY_STR, 4); + s = ray_str_vec_append(s, "a", 1); + s = ray_str_vec_append(s, "b", 1); + TEST_ASSERT_EQ_I(ray_index_hash_build_region(s, idx_region_map, &c, NULL), RAY_ERR_NYI); + TEST_ASSERT_EQ_I(c.calls, 0); + ray_release(s); + + ray_t* v = idx_reg_col(RAY_I64, 300000, 5003, 977); + ray_t* sl = ray_vec_slice(v, 10, 1000); + TEST_ASSERT_FALSE(RAY_IS_ERR(sl)); + TEST_ASSERT_EQ_I(ray_index_hash_build_region(sl, idx_region_map, &c, NULL), RAY_ERR_NYI); + TEST_ASSERT_EQ_I(c.calls, 0); + ray_release(sl); + + for (int plan = 0; plan < 2; plan++) { /* mapped after one batch, after the count */ + if (plan == 1) ray_heap_set_anon_watermark(INT64_C(4) << 20); + idx_region_ctx_t f = { .fail = true }; + ray_mem_trace_t mt; + TEST_ASSERT_TRUE(ray_mem_trace_begin()); + ray_err_t e = ray_index_hash_build_region(v, idx_region_map, &f, NULL); + ray_mem_trace_end(&mt); + if (plan == 1) ray_heap_set_anon_watermark(0); + TEST_ASSERT_EQ_I(e, RAY_ERR_IO); + TEST_ASSERT_EQ_I(f.calls, 1); + TEST_ASSERT_EQ_I(mt.net_bytes, 0); + } + + ray_t* z = v; + ray_retain(z); + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_zone(&z))); /* z: a copy with a zone */ + TEST_ASSERT_TRUE(z->attrs & RAY_ATTR_HAS_INDEX); + TEST_ASSERT_TRUE(idx_region_same(z, NULL)); + ray_release(z); + ray_release(v); + ray_heap_destroy(); + PASS(); +} + +/* Interrupted anywhere — the pool cancelled up front, or an interrupt at + * points spread over a build under a budget of many batches — the build + * reports the cancel and leaves nothing allocated, or completes with + * exactly the uninterrupted region. */ +static test_result_t test_index_hash_region_interrupt(void) { + ray_heap_init(); + ray_pool_t* pool = ray_pool_get(); + if (!pool || ray_pool_total_workers(pool) < 2) { ray_heap_destroy(); SKIP("needs workers"); } + ray_t* v = idx_part_col_n(500000); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + ray_mem_trace_t mt; + idx_region_ctx_t c = {0}; + atomic_store(&pool->cancelled, 1); + TEST_ASSERT_TRUE(ray_mem_trace_begin()); + ray_err_t e = ray_index_hash_build_region(v, idx_region_map, &c, NULL); + ray_free_raw(c.buf); + ray_mem_trace_end(&mt); + atomic_store(&pool->cancelled, 0); + TEST_ASSERT_EQ_I(e, RAY_ERR_CANCEL); + TEST_ASSERT_EQ_I(mt.net_bytes, 0); + + ray_heap_set_anon_watermark(INT64_C(64) << 20); /* batches of 128K rows */ + idx_region_ctx_t ref = {0}; + TEST_ASSERT_TRUE(idx_region_same(v, &ref)); + int64_t t0 = idx_now_ns(); + idx_region_ctx_t once = {0}; + TEST_ASSERT_EQ_I(ray_index_hash_build_region(v, idx_region_map, &once, NULL), RAY_OK); + int64_t took = idx_now_ns() - t0; + ray_free_raw(once.buf); + int64_t cancelled = 0, bad = 0; + for (int k = 0; k < 8; k++) { + idx_region_ctx_t a = {0}; + int64_t delay = took * k / 8; + ray_thread_t th; + TEST_ASSERT_TRUE(ray_mem_trace_begin()); + TEST_ASSERT_EQ_I(ray_thread_create(&th, idx_interrupt_after, &delay), RAY_OK); + e = ray_index_hash_build_region(v, idx_region_map, &a, NULL); + ray_thread_join(th); + ray_clear_interrupt(); + if (e == RAY_OK) { + if (a.bytes != ref.bytes || memcmp(a.buf, ref.buf, (size_t)ref.bytes) != 0) bad++; + ray_free_raw(a.buf); + ray_mem_trace_end(&mt); + } else { + cancelled++; + if (e != RAY_ERR_CANCEL) bad++; + ray_free_raw(a.buf); + ray_mem_trace_end(&mt); + if (mt.net_bytes != 0) bad++; + } + } + ray_heap_set_anon_watermark(0); + ray_free_raw(ref.buf); + TEST_ASSERT_EQ_I(bad, 0); + TEST_ASSERT_TRUE(cancelled > 0); + ray_release(v); + ray_heap_destroy(); + PASS(); +} + /* ─── Mapped column drops its own index: the whole mapping is unmapped ── * * A column loaded by mmap with an inline index region is longer than its @@ -2619,12 +3403,12 @@ static test_result_t test_index_hash_collisions(void) { TEST_ASSERT_EQ_I(ih->u.hash.n_groups, 1); /* One CSR group holding rows 0..4 in ascending order. */ - const int64_t* grows = NULL; + ray_idx_rows_t grows = { NULL, false }; int64_t gn = 0; TEST_ASSERT_EQ_I(ray_index_hash_group(w, 5, &grows, &gn), 1); TEST_ASSERT_EQ_I(gn, 5); for (int64_t i = 0; i < 5; i++) - TEST_ASSERT_EQ_I(grows[i], i); + TEST_ASSERT_EQ_I(ray_idx_rows_at(grows, i), i); ray_release(w); ray_heap_destroy(); @@ -3849,6 +4633,18 @@ const test_entry_t index_entries[] = { { "index/aux_helper_slice", test_index_aux_helper_slice, NULL, NULL }, { "index/drop_under_shared_cow", test_index_drop_under_shared_cow, NULL, NULL }, { "index/mapped_drop_unmaps_tail", test_index_mapped_drop_unmaps_tail, NULL, NULL }, + { "index/hash_narrow_roundtrip", test_index_hash_narrow_roundtrip, NULL, NULL }, + { "index/hash_narrow_interrupted", test_index_hash_narrow_interrupted, NULL, NULL }, + { "index/hash_part_invariant", test_index_hash_part_invariant, NULL, NULL }, + { "index/hash_part_wraps", test_index_hash_part_wraps, NULL, NULL }, + { "index/hash_part_interrupted", test_index_hash_part_interrupted, NULL, NULL }, + { "index/hash_part_interrupt_sweep", test_index_hash_part_interrupt_sweep, NULL, NULL }, + { "index/hash_region_bytes", test_index_hash_region_bytes, NULL, NULL }, + { "index/hash_region_capacity", test_index_hash_region_capacity, NULL, NULL }, + { "index/hash_region_discard", test_index_hash_region_discard, NULL, NULL }, + { "index/hash_region_wide", test_index_hash_region_wide, NULL, NULL }, + { "index/hash_region_guards", test_index_hash_region_guards, NULL, NULL }, + { "index/hash_region_interrupt", test_index_hash_region_interrupt, NULL, NULL }, { "index/persistence_roundtrip", test_index_persistence_roundtrip, NULL, NULL }, { "index/bool_zone_and_hash", test_index_bool_zone_and_hash, NULL, NULL }, { "index/i16_zone_and_hash", test_index_i16_zone_and_hash, NULL, NULL }, diff --git a/test/test_lang.c b/test/test_lang.c index 4907e194b..fa80c1085 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -157,6 +157,239 @@ static void lang_teardown(void) { ray_runtime_destroy(__RUNTIME); } + +/* ---- Test: query helper row provenance survives a runtime re-init ---- + * The row-wise builtin tables and the per-object verdict cache behind the + * bytecode provenance flags are keyed on the symbol-table epoch; a stale + * entry would silently turn text concat into a collection append. */ +static test_result_t test_query_helper_reinit(void) { + for (int round = 0; round < 2; round++) { + if (round) { + ray_runtime_destroy(__RUNTIME); + ray_runtime_create(0, NULL); + /* Shift user symbol ids before the helpers are defined again. */ + ray_t* shift = ray_eval_str("(set shifted (list 'zz0 'zz1 'zz2 'zz3 'zz4 'zz5 'zz6 'zz7))"); + if (shift && !RAY_IS_ERR(shift)) ray_release(shift); else if (shift) ray_error_free(shift); + } + ray_t* setup = ray_eval_str("(do (set T (table [x s] (list [1 2 3] ['a 'b 'c])))" + " (set hup (fn [v] 1 (concat (upper v) \"!\")))" + " (set hif (fn [v] 1 (if (> 1 0) (concat v \"?\") v))) 1)"); + TEST_ASSERT_NOT_NULL(setup); + TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); + ray_release(setup); + ASSERT_EQ("(at (update {r: (hup s) from: T}) 'r)", "['A! 'B! 'C!]"); + ASSERT_EQ("(at (update {r: (hif s) from: T}) 'r)", "['a? 'b? 'c?]"); + ASSERT_EQ("(at (select {from: T where: (in (hup s) ['A! 'C!])}) 'x)", "[1 3]"); + } + PASS(); +} + + +/* ---- Test: a closure whose capture values are not a LIST never compiles ---- + * A deserialized lambda may carry a dict with a typed value vector; the + * compiled capture load would read its payload as pointers. Such a + * closure stays on the tree walker, whose capture binding reports a type + * error, inside and outside a query. */ +static test_result_t test_closure_malformed_capture(void) { + /* A closure as the deserializer hands it back: no bytecode yet, so the + * compile gate decides. (A closure made by interpreted code shares + * its literal's template at birth; strip that to get the shape.) */ + ray_t* lam = ray_eval_str("(do (let k 1) (fn [v] (+ v k)))"); + TEST_ASSERT_NOT_NULL(lam); + TEST_ASSERT_FALSE(RAY_IS_ERR(lam)); + TEST_ASSERT_EQ_I(lam->type, RAY_LAMBDA); + TEST_ASSERT_NOT_NULL(LAMBDA_CLOSURE(lam)); + if (LAMBDA_BC(lam)) { ray_release(LAMBDA_BC(lam)); LAMBDA_BC(lam) = NULL; } + if (LAMBDA_CONSTS(lam)) { ray_release(LAMBDA_CONSTS(lam)); LAMBDA_CONSTS(lam) = NULL; } + if (LAMBDA_DBG(lam)) { ray_release(LAMBDA_DBG(lam)); LAMBDA_DBG(lam) = NULL; } + LAMBDA_NLOCALS(lam) = 0; + lam->attrs &= (uint8_t)~RAY_FN_COMPILED; + TEST_ASSERT(!LAMBDA_IS_COMPILED(lam), "the closure is uncompiled before the call"); + /* Replace the closure's values with a typed vector of the same length. */ + ray_t* keys = ray_dict_keys(LAMBDA_CLOSURE(lam)); + ray_t* vals = ray_vec_new(RAY_I64, keys->len); + TEST_ASSERT_NOT_NULL(vals); + for (int64_t i = 0; i < keys->len; i++) ((int64_t*)ray_data(vals))[i] = 0x4141414141414141LL; + vals->len = keys->len; + ray_retain(keys); + ray_t* bad = ray_dict_new(keys, vals); + TEST_ASSERT_NOT_NULL(bad); + TEST_ASSERT_FALSE(RAY_IS_ERR(bad)); + ray_release(LAMBDA_CLOSURE(lam)); + LAMBDA_CLOSURE(lam) = bad; + ray_t* arg = ray_i64(2); + ray_t* args[1] = { arg }; + ray_t* r = call_lambda(lam, args, 1); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT(RAY_IS_ERR(r), "malformed closure must fail, not be dereferenced"); + TEST_ASSERT(!LAMBDA_IS_COMPILED(lam), "malformed closure must not compile"); + ray_error_free(r); + ray_release(lam); + + /* A closure made by compiled code shares its literal's bytecode from + * birth; its capture binding checks the dict's shape at run time. */ + lam = ray_eval_str("((fn [k] (fn [v] (+ v k))) 1)"); + TEST_ASSERT_NOT_NULL(lam); + TEST_ASSERT_FALSE(RAY_IS_ERR(lam)); + TEST_ASSERT(LAMBDA_IS_COMPILED(lam), "a closure made by compiled code is born compiled"); + keys = ray_dict_keys(LAMBDA_CLOSURE(lam)); + vals = ray_vec_new(RAY_I64, keys->len); + TEST_ASSERT_NOT_NULL(vals); + for (int64_t i = 0; i < keys->len; i++) ((int64_t*)ray_data(vals))[i] = 0x4141414141414141LL; + vals->len = keys->len; + ray_retain(keys); + bad = ray_dict_new(keys, vals); + TEST_ASSERT_NOT_NULL(bad); + ray_release(LAMBDA_CLOSURE(lam)); + LAMBDA_CLOSURE(lam) = bad; + r = call_lambda(lam, args, 1); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT(RAY_IS_ERR(r), "a malformed closure dict must fail the capture binding"); + ray_error_free(r); + ray_release(arg); + ray_release(lam); + PASS(); +} + +/* A lazy handle passed through the C API to a compiled closure maker reaches + * the maker's parameter slot unmaterialized (Rayfall call sites materialize + * lazy arguments, call_lambda does not). The closure must capture the + * concrete value: a lazy handle is single-use, and a dict holding the + * handle would fail the closure's second call. */ +static test_result_t test_closure_lazy_capture_vm(void) { + ray_t* mk = ray_eval_str("(fn [v] (fn [] (at v 0)))"); + TEST_ASSERT_NOT_NULL(mk); + TEST_ASSERT_FALSE(RAY_IS_ERR(mk)); + /* A lazy handle over a constant vector, as a deferred DAG result is. */ + ray_t* vec = ray_eval_str("[1 2 3]"); + TEST_ASSERT_NOT_NULL(vec); + TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); + ray_graph_t* g = ray_graph_new(NULL); + TEST_ASSERT_NOT_NULL(g); + ray_t* lazy = ray_lazy_wrap(g, ray_graph_input_vec(g, vec)); + TEST_ASSERT_NOT_NULL(lazy); + TEST_ASSERT_FALSE(RAY_IS_ERR(lazy)); + TEST_ASSERT(ray_is_lazy(lazy), "the argument must be a lazy handle"); + ray_t* args[1] = { lazy }; + ray_t* clo = call_lambda(mk, args, 1); + TEST_ASSERT_NOT_NULL(clo); + TEST_ASSERT_FALSE(RAY_IS_ERR(clo)); + TEST_ASSERT_EQ_I(clo->type, RAY_LAMBDA); + TEST_ASSERT(LAMBDA_IS_COMPILED(mk), "the maker compiles on its first call"); + TEST_ASSERT(LAMBDA_IS_COMPILED(clo), "a closure made by compiled code is born compiled"); + for (int i = 0; i < 3; i++) { + ray_t* r = call_lambda(clo, NULL, 0); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FMT(!RAY_IS_ERR(r), "call %d of a closure over a lazy capture failed: %s", i + 1, ray_err_code(r)); + TEST_ASSERT_EQ_I(r->type, -RAY_I64); + TEST_ASSERT_EQ_I(r->i64, 1); + ray_release(r); + } + ray_release(clo); + ray_release(lazy); + ray_release(vec); + ray_release(mk); + PASS(); +} + +/* The symbol walk behind a closure's capture names stops at 1024 levels + * of nesting rather than following the text down the C stack; the closure + * compiler then binds every capture (closure_locals.rfl pins that). */ +static test_result_t test_closure_sym_walk_guard(void) { + ray_t* mk = ray_eval_str("(do (set nestw (fn [n] (let a (parse \"kw\")) (times n (let a (list a))) a)) 0)"); + TEST_ASSERT_NOT_NULL(mk); + TEST_ASSERT_FALSE(RAY_IS_ERR(mk)); + ray_release(mk); + int depths[2] = { 1000, 1100 }; + for (int i = 0; i < 2; i++) { + char src[64]; + snprintf(src, sizeof src, "(nestw %d)", depths[i]); + ray_t* ast = ray_eval_str(src); + TEST_ASSERT_NOT_NULL(ast); + TEST_ASSERT_FALSE(RAY_IS_ERR(ast)); + bool dynamic = false; + int64_t weight = 0; + ray_t* ment = ray_closure_mentioned_syms(ast, &dynamic, &weight); + if (i == 0) { + TEST_ASSERT(ment != NULL, "a body within the guard is walked"); + TEST_ASSERT_EQ_I(ment->len, 1); + ray_release(ment); + } else { + TEST_ASSERT(ment == NULL, "a body past the guard is given up on"); + } + ray_release(ast); + } + PASS(); +} + +/* A body that does not compile is marked (NLOCALS -1) so it stays on the + * tree walker without a compile attempt per call, and a lambda so marked + * is never compiled again. */ +static test_result_t test_lambda_compile_failure_mark(void) { + ray_t* bad = ray_eval_str("(fn [x] (if false (set 1 2)) (+ x 1))"); + TEST_ASSERT_NOT_NULL(bad); + TEST_ASSERT_FALSE(RAY_IS_ERR(bad)); + TEST_ASSERT_EQ_I(bad->type, RAY_LAMBDA); + /* (Made by interpreted code, it may carry the literal's verdict + * already; clear it so ray_compile decides.) */ + LAMBDA_NLOCALS(bad) = 0; + ray_compile(bad); + TEST_ASSERT(!LAMBDA_IS_COMPILED(bad), "the body does not compile"); + TEST_ASSERT_EQ_I(LAMBDA_NLOCALS(bad), -1); + ray_t* arg = ray_i64(2); + ray_t* args[1] = { arg }; + for (int i = 0; i < 2; i++) { + ray_t* r = call_lambda(bad, args, 1); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->i64, 3); + ray_release(r); + TEST_ASSERT_EQ_I(LAMBDA_NLOCALS(bad), -1); + } + ray_release(bad); + + /* The mark alone keeps a compilable body interpreted. */ + ray_t* good = ray_eval_str("(fn [x] (+ x 1))"); + TEST_ASSERT_NOT_NULL(good); + TEST_ASSERT_FALSE(RAY_IS_ERR(good)); + TEST_ASSERT(!LAMBDA_IS_COMPILED(good), "a definition compiles on its first call"); + LAMBDA_NLOCALS(good) = -1; + ray_t* r = call_lambda(good, args, 1); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->i64, 3); + ray_release(r); + TEST_ASSERT(!LAMBDA_IS_COMPILED(good), "a lambda marked not compilable is not compiled"); + ray_release(good); + ray_release(arg); + PASS(); +} + +/* A closure whose text is heavy (a 66 KB string constant) but small in + * nodes still binds only the captures its body mentions: one slot for v7, + * not one per binding in scope. */ +static test_result_t test_closure_heavy_literal_captures(void) { + static char src[200 * 24 + 70000 + 256]; + size_t cap = sizeof src; + size_t n = (size_t)snprintf(src, cap, "(do (set mkHv (fn [] (if false (set 1 2))"); + for (int i = 0; i < 200; i++) n += (size_t)snprintf(src + n, cap - n, " (let v%d %d)", i, i); + n += (size_t)snprintf(src + n, cap - n, " (fn [x] (+ x (+ v7 (count \""); + for (int i = 0; i < 66000; i++) src[n++] = 'a'; + n += (size_t)snprintf(src + n, cap - n, "\")))))) (set cHv (mkHv)) (cHv 1))"); + ray_t* r = ray_eval_str(src); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->i64, 66008); + ray_release(r); + ray_t* c = ray_eval_str("cHv"); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_EQ_I(c->type, RAY_LAMBDA); + TEST_ASSERT(LAMBDA_IS_COMPILED(c), "the closure compiles"); + TEST_ASSERT(LAMBDA_NLOCALS(c) <= 4, "only the mentioned capture takes a slot"); + ray_release(c); + PASS(); +} + /* ---- Dummy function for testing ---- */ static ray_t* dummy_unary(ray_t* x) { return ray_retain(x), x; } static ray_t* dummy_binary(ray_t* x, ray_t* y) { (void)y; return ray_retain(x), x; } @@ -892,6 +1125,15 @@ static test_result_t test_eval_select_where_in_guid_nulls(void) { TEST_ASSERT_EQ_I(ray_table_nrows(result), 1); ray_release(result); + /* GUID producers can emit payload nulls without HAS_NULLS. + * The inline distinct probe forces evaluator membership. */ + col->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + ray_t* bound = ray_eval_str("(set Pg (at t 'g))"); + TEST_ASSERT_NOT_NULL(bound); + TEST_ASSERT_FALSE(RAY_IS_ERR(bound)); + ray_release(bound); + ASSERT_EQ("(count (select {from: t where: (in g (distinct Pg))}))", "1"); + ASSERT_EQ("(count (select {from: t where: (not-in g (distinct (list probe)))}))", "1"); ray_release(table); PASS(); } @@ -1561,6 +1803,17 @@ static test_result_t test_eval_pivot_multi_index(void) { PASS(); } +static test_result_t test_eval_zone_sym_diagnostic(void) { + ray_t* r = ray_eval_str("(.idx.zone ['a 'b])"); + TEST_ASSERT(r && RAY_IS_ERR(r), "SYM zone index remains unsupported"); + TEST_ASSERT_STR_EQ(ray_err_code(r), "nyi"); + TEST_ASSERT_NOT_NULL(ray_error_msg()); + TEST_ASSERT_STR_EQ(ray_error_msg(), + "zone: only numeric/temporal vectors supported (got type 12)"); + ray_release(r); + PASS(); +} + static test_result_t test_eval_select_where_in_sym_vs_atom_mismatch(void) { /* Intern the probe sym so we know its numeric ID, then embed * that ID as a decimal literal in the source string so the i64 @@ -2326,6 +2579,28 @@ static test_result_t test_eval_select_by_nonagg_colref_vs_const(void) { PASS(); } +/* ---- Test: a by: key that is no value ---- + * A name bound to a function or to null is refused, with or without an + * output, by what it is: the refusal of a function once caught null too + * and called it a function. */ +static test_result_t test_eval_select_by_key_not_a_value(void) { + static const char* const cases[][2] = { + { "(select {by: sum from: (table [x y] (list [3 1] [30 10]))})", "function" }, + { "(select {c: (count y) by: sum from: (table [x y] (list [3 1] [30 10]))})", "function" }, + { "(do (set Nk (println \"\")) (select {by: Nk from: (table [x y] (list [3 1] [30 10]))}))", "null" }, + { "(do (set Nk (println \"\")) (select {c: (count y) by: Nk from: (table [x y] (list [3 1] [30 10]))}))", "null" }, + }; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + ray_t* r = ray_eval_str(cases[i][0]); + TEST_ASSERT_TRUE(RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "domain"); + const char* msg = ray_error_msg(); + TEST_ASSERT_FMT(msg && strstr(msg, cases[i][1]), "case %zu: %s", i, msg ? msg : "(none)"); + ray_error_free(r); + } + PASS(); +} + /* ---- Test: non-agg literal/short vectors broadcast ---- * Regression: the over-eager fix that routed all RAY_LIST results * through gather_by_idx also swept up literal lists like `[1 2]` @@ -9418,12 +9693,13 @@ static test_result_t test_read_unsized_stream_is_bounded(void) { if (!probe) SKIP("/dev/zero unavailable"); fclose(probe); - /* ray_heap_anon_watermark() resolves the 0 sentinel to physical RAM, so - * restoring what it returns would pin the watermark to a number where - * the suite found "use physical RAM". Detect that case and put the - * sentinel back instead, which keeps this test order-independent. */ + /* ray_heap_anon_watermark() resolves the 0 sentinel to the default + * threshold, so restoring what it returns would pin the watermark to a + * number where the suite found "use the default". Detect that case and + * put the sentinel back instead, which keeps this test order-independent. */ int64_t saved = ray_heap_anon_watermark(); - bool was_default = (saved == ray_sys_total_ram()); + ray_heap_set_anon_watermark(0); + bool was_default = (saved == ray_heap_anon_watermark()); /* budget = (watermark - committed) / 4, so this leaves ~1 MB. */ ray_heap_set_anon_watermark(ray_heap_anon_committed() + 4 * 1024 * 1024); @@ -9480,7 +9756,8 @@ static test_result_t test_exec_capture_is_bounded(void) { SKIP("shell capture unavailable"); #else int64_t saved = ray_heap_anon_watermark(); - bool was_default = (saved == ray_sys_total_ram()); + ray_heap_set_anon_watermark(0); + bool was_default = (saved == ray_heap_anon_watermark()); ray_heap_set_anon_watermark(ray_heap_anon_committed() + 4 * 1024 * 1024); ray_t* args[2]; @@ -9615,6 +9892,7 @@ const test_entry_t lang_entries[] = { { "lang/eval/select_by_str_nonagg_list_col", test_eval_select_by_str_nonagg_list_col, lang_setup, lang_teardown }, { "lang/eval/select_by_nonagg_broadcast", test_eval_select_by_nonagg_broadcast, lang_setup, lang_teardown }, { "lang/eval/select_by_nonagg_colref_vs_const", test_eval_select_by_nonagg_colref_vs_const, lang_setup, lang_teardown }, + { "lang/eval/select_by_key_not_a_value", test_eval_select_by_key_not_a_value, lang_setup, lang_teardown }, { "lang/eval/select_by_nonagg_with_agg_subexpr", test_eval_select_by_nonagg_with_agg_subexpr, lang_setup, lang_teardown }, { "lang/eval/select_by_nonagg_sort_take", test_eval_select_by_nonagg_sort_take, lang_setup, lang_teardown }, { "lang/eval/select_by_take_clamps", test_eval_select_by_take_clamps, lang_setup, lang_teardown }, @@ -9924,6 +10202,13 @@ const test_entry_t lang_entries[] = { { "lang/temporal/extract_epoch", test_temporal_extract_epoch, lang_setup, lang_teardown }, { "lang/temporal/date_trunc_month_case", test_temporal_date_trunc_month_case, lang_setup, lang_teardown }, + { "lang/zone_sym_diagnostic", test_eval_zone_sym_diagnostic, lang_setup, lang_teardown }, + { "lang/query_helper_reinit", test_query_helper_reinit, lang_setup, lang_teardown }, + { "lang/closure_malformed_capture", test_closure_malformed_capture, lang_setup, lang_teardown }, + { "lang/closure_lazy_capture_vm", test_closure_lazy_capture_vm, lang_setup, lang_teardown }, + { "lang/closure_sym_walk_guard", test_closure_sym_walk_guard, lang_setup, lang_teardown }, + { "lang/lambda_compile_failure_mark", test_lambda_compile_failure_mark, lang_setup, lang_teardown }, + { "lang/closure_heavy_literal_captures", test_closure_heavy_literal_captures, lang_setup, lang_teardown }, { "lang/io/read_procfs_zero_size", test_read_procfs_reports_zero_size, lang_setup, lang_teardown }, { "lang/io/read_unsized_bounded", test_read_unsized_stream_is_bounded, lang_setup, lang_teardown }, { "lang/io/exec_capture_bounded", test_exec_capture_is_bounded, lang_setup, lang_teardown }, diff --git a/test/test_parquet.c b/test/test_parquet.c index 76e1d9a33..6dbad7054 100644 --- a/test/test_parquet.c +++ b/test/test_parquet.c @@ -1,21 +1,52 @@ /* Copyright (c) 2026 Anton Kundenko. MIT license; see LICENSE. */ +#if !defined(_WIN32) +#define _POSIX_C_SOURCE 200809L /* setenv / unsetenv */ +#endif #include "test.h" #include "io/parquet.h" #include "core/pool.h" #include "mem/heap.h" +#include "mem/sys.h" #include "table/sym.h" #include "store/part.h" #include "store/splay.h" #include "ops/idxop.h" +#include "core/runtime.h" /* ray_error_msg: the skeptic probes */ +#include "core/profile.h" /* ray_profile_now_ns: pq_pool's bounded wait */ +#include "core/crc32.h" /* ray_crc32: page checksums of the made files */ #include +#include #include #include +#include #if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) #include +#include /* the skeptic probes' child imports */ #endif static void pq_setup(void) { ray_heap_init(); (void)ray_sym_init(); } static void pq_teardown(void) { ray_sym_destroy(); ray_heap_destroy(); } +/* A pool of `cores` workers, every one of them started. Its workers read + * the environment as they start (ray_heap_init's getenv), and these tests + * set and unset variables right after making a pool; ray_pool_init_total + * waits for the workers itself, and this does not rely on it. A worker + * whose heap never shows (its ray_heap_init failed) fails the pool within + * a bound instead of hanging the test. */ +static ray_err_t pq_pool(int cores) { + ray_pool_destroy(); + ray_err_t e = ray_pool_init_total((uint32_t)cores); + ray_pool_t* p = ray_pool_get(); + int64_t until = ray_profile_now_ns() + (int64_t)30 * 1000000000; + for (uint32_t i = 0; e == RAY_OK && p && i < p->n_workers; i++) + while (!atomic_load_explicit(&p->worker_heaps[i], memory_order_acquire)) { + if (ray_profile_now_ns() > until) { + fprintf(stderr, " pq_pool: worker %u of %u has no heap\n", i, p->n_workers); + return RAY_ERR_OOM; + } + RAY_CPU_RELAX(); + } + return e; +} #define FIX "test/data/parquet/" static test_result_t test_pq_snappy(void) { @@ -258,7 +289,7 @@ static test_result_t test_pq_parallel(void) { } 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); + TEST_ASSERT_EQ_I(pq_pool(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; @@ -292,27 +323,288 @@ static void pq_remove_native(const char* dir, const char** columns, int n) { for (int i = 0; i < 3; i++) { snprintf(path,sizeof(path),"%s/%s",dir,special[i]); unlink(path); } rmdir(dir); } +/* The direct import picks its pass layout from memory; RAY_PQ_PASS_COLS + * forces it, so a test covers both: NULL = the default (one pass on any + * test machine), "1" = column by column. */ +static void pq_set_env(const char* name, const char* v) { +#ifdef RAY_OS_WINDOWS + _putenv_s(name, v ? v : ""); +#else + if (v) setenv(name, v, 1); else unsetenv(name); +#endif +} +static void pq_set_layout(const char* v) { pq_set_env("RAY_PQ_PASS_COLS", v); } +/* The symbol columns' import: NULL = the default (direct on any test + * file), "grouped" = two decodes and the hash-grouped dictionary + * (table/symgrp.h), "direct" forced. */ +static void pq_set_symmode(const char* v) { pq_set_env("RAY_PQ_SYM_MODE", v); } +/* Every knob of the grouped import back to its default (a failed test can + * leave one set). */ +static void pq_sym_env_clear(void) { + const char* knobs[] = {"RAY_PQ_SYM_MODE","RAY_PQ_SYM_ORDER","RAY_PQ_SYM_GROUPS","RAY_PQ_SYM_WINDOW", + "RAY_PQ_SYM_ARENA","RAY_PQ_SYM_HASH_BITS","RAY_PQ_SYM_INJECT","RAY_PQ_PASS_COLS", + "RAY_PQ_SYM_RAM","RAY_PQ_DIRECT_REVERSE","RAY_PQ_SYM_HASH_TOP"}; + for (size_t i = 0; i < sizeof(knobs)/sizeof(knobs[0]); i++) pq_set_env(knobs[i], NULL); +} + +/* A Parquet file for the grouped import's tests: `groups` row groups of + * x, the row as a required INT32, and s, an optional BYTE_ARRAY (UTF8) that + * fn gives (NULL for a null); PLAIN, uncompressed, one v1 data page per + * chunk. The thrift compact encoding of test/data/parquet/generate.py. */ +typedef const char* (*pq_synth_fn)(int64_t row, char* buf, uint32_t* len); +typedef struct { uint8_t* p; size_t n, cap; bool bad; } pq_buf; +static void pb_bytes(pq_buf* b, const void* s, size_t n) { + if (b->bad) return; + if (b->n + n > b->cap) { + size_t cap = b->cap ? b->cap : 4096; + while (cap < b->n + n) cap *= 2; + uint8_t* p = (uint8_t*)ray_sys_realloc(b->p, cap); + if (!p) { b->bad = true; return; } + b->p = p; b->cap = cap; + } + if (n) memcpy(b->p + b->n, s, n); + b->n += n; +} +static void pb_byte(pq_buf* b, uint8_t v) { pb_bytes(b, &v, 1); } +static void pb_var(pq_buf* b, uint64_t v) { + while (v > 127) { pb_byte(b, (uint8_t)((v & 127) | 128)); v >>= 7; } + pb_byte(b, (uint8_t)v); +} +static void pb_zz(pq_buf* b, int64_t v) { pb_var(b, ((uint64_t)v << 1) ^ (uint64_t)(v >> 63)); } +enum { PB_I32 = 5, PB_I64 = 6, PB_BIN = 8, PB_LIST = 9, PB_STRUCT = 12 }; +static void pb_field(pq_buf* b, int* last, int id, int type) { + int d = id - *last; + if (d > 0 && d < 16) pb_byte(b, (uint8_t)((d << 4) | type)); + else { pb_byte(b, (uint8_t)type); pb_zz(b, id); } + *last = id; +} +static void pb_i(pq_buf* b, int* last, int id, int type, int64_t v) { pb_field(b, last, id, type); pb_zz(b, v); } +static void pb_bin(pq_buf* b, const char* s, size_t n) { pb_var(b, n); pb_bytes(b, s, n); } +static void pb_list(pq_buf* b, int n, int type) { + if (n < 15) pb_byte(b, (uint8_t)((n << 4) | type)); + else { pb_byte(b, (uint8_t)(0xf0 | type)); pb_var(b, (uint64_t)n); } +} +/* ColumnMetaData 13, a chunk's encoding stats: a dictionary page, data + * pages of dictionary ids, data pages of PLAIN values, as given. */ +static void pb_enc_stats(pq_buf* f, int* last, bool dict, bool ids, bool plain) { + pb_field(f, last, 13, PB_LIST); pb_list(f, (int)dict + (int)ids + (int)plain, PB_STRUCT); + if (dict) { int l = 0; pb_i(f, &l, 1, PB_I32, 2); pb_i(f, &l, 2, PB_I32, 0); pb_i(f, &l, 3, PB_I32, 1); pb_byte(f, 0); } + if (ids) { int l = 0; pb_i(f, &l, 1, PB_I32, 0); pb_i(f, &l, 2, PB_I32, 8); pb_i(f, &l, 3, PB_I32, 1); pb_byte(f, 0); } + if (plain) { int l = 0; pb_i(f, &l, 1, PB_I32, 0); pb_i(f, &l, 2, PB_I32, 0); pb_i(f, &l, 3, PB_I32, 1); pb_byte(f, 0); } +} +/* Columns x, s (fn of the row) and t (fn of the row + rows / 2: a + * vocabulary that meets s's, for the second column's pass). A test may set + * pq_synth_t, column t's own function of the row, and pq_synth_dict, the + * columns (bit c) written dictionary-encoded (a dictionary page of the + * chunk's distinct strings, then the ids), and resets them after. */ +#define PQ_SYNTH_COLS 3 +static pq_synth_fn pq_synth_t; +static unsigned pq_synth_dict; +static const char* pq_synth_row(pq_synth_fn fn, int c, int64_t r, int64_t rows, char* buf, uint32_t* len) { + return c == 2 && pq_synth_t ? pq_synth_t(r, buf, len) : fn(c == 1 ? r : r + rows / 2, buf, len); +} +static bool pq_synth(const char* path, int64_t rows, int64_t groups, pq_synth_fn fn) { + pq_buf f = {0}, page = {0}, levels = {0}, values = {0}, dict = {0}, doff = {0}; + int64_t* at = (int64_t*)ray_sys_alloc((size_t)groups * PQ_SYNTH_COLS * sizeof(int64_t)); + int64_t* sz = (int64_t*)ray_sys_alloc((size_t)groups * PQ_SYNTH_COLS * sizeof(int64_t)); + int64_t* dat = (int64_t*)ray_sys_alloc((size_t)groups * PQ_SYNTH_COLS * sizeof(int64_t)); + if (!at || !sz || !dat) return false; + pb_bytes(&f, "PAR1", 4); + char buf[256]; + for (int64_t g = 0; g < groups; g++) { + int64_t lo = rows * g / groups, hi = rows * (g + 1) / groups; + for (int c = 0; c < PQ_SYNTH_COLS; c++) { + bool dicted = c && (pq_synth_dict >> c & 1); + levels.n = values.n = page.n = dict.n = doff.n = 0; + if (c == 0) for (int64_t r = lo; r < hi; r++) { int32_t x = (int32_t)r; pb_bytes(&values, &x, 4); } + else { + uint8_t bits = 0; + int64_t n = hi - lo, groups8 = (n + 7) / 8; + pb_var(&levels, (uint64_t)(groups8 * 2 + 1)); + pq_buf ids = {0}; + for (int64_t r = lo; r < lo + groups8 * 8; r++) { + uint32_t len = 0; + const char* s = r < hi ? pq_synth_row(fn, c, r, rows, buf, &len) : NULL; + if (s) { + bits |= (uint8_t)(1u << ((r - lo) & 7)); + if (!dicted) { pb_bytes(&values, &len, 4); pb_bytes(&values, s, len); } + else { + /* the entry's id, the entry added on its first occurrence */ + uint32_t id = 0, nd = (uint32_t)(doff.n / 4); + for (; id < nd; id++) { + uint32_t o; memcpy(&o, doff.p + id * 4, 4); + uint32_t l; memcpy(&l, dict.p + o, 4); + if (l == len && !memcmp(dict.p + o + 4, s, len)) break; + } + if (id == nd) { uint32_t o = (uint32_t)dict.n; pb_bytes(&doff, &o, 4); pb_bytes(&dict, &len, 4); pb_bytes(&dict, s, len); } + pb_bytes(&ids, &id, 4); + } + } + if (((r - lo) & 7) == 7) { pb_byte(&levels, bits); bits = 0; } + } + uint32_t ln = (uint32_t)levels.n; + pb_bytes(&page, &ln, 4); pb_bytes(&page, levels.p, levels.n); + if (dicted) { + /* the ids: their bit width, then a run of one a value */ + uint32_t nd = (uint32_t)(doff.n / 4), bw = 1; + while (bw < 32 && ((uint64_t)1 << bw) < nd) bw++; + pb_byte(&values, (uint8_t)bw); + for (size_t i = 0; i + 4 <= ids.n; i += 4) { + uint32_t id; memcpy(&id, ids.p + i, 4); + pb_var(&values, 2); + pb_bytes(&values, &id, (bw + 7) / 8); + } + if (ids.bad) values.bad = true; + } + ray_sys_free(ids.p); + } + pb_bytes(&page, values.p, values.n); + int last = 0; + int64_t start = (int64_t)f.n; + dat[g * PQ_SYNTH_COLS + c] = -1; + if (dicted) { + pb_i(&f, &last, 1, PB_I32, 2); + pb_i(&f, &last, 2, PB_I32, (int64_t)dict.n); + pb_i(&f, &last, 3, PB_I32, (int64_t)dict.n); + pb_field(&f, &last, 7, PB_STRUCT); + { int l = 0; pb_i(&f, &l, 1, PB_I32, (int64_t)(doff.n / 4)); pb_i(&f, &l, 2, PB_I32, 0); pb_byte(&f, 0); } + pb_byte(&f, 0); + pb_bytes(&f, dict.p, dict.n); + dat[g * PQ_SYNTH_COLS + c] = (int64_t)f.n; + last = 0; + } + pb_i(&f, &last, 1, PB_I32, 0); + pb_i(&f, &last, 2, PB_I32, (int64_t)page.n); + pb_i(&f, &last, 3, PB_I32, (int64_t)page.n); + pb_field(&f, &last, 5, PB_STRUCT); + int l2 = 0; + pb_i(&f, &l2, 1, PB_I32, hi - lo); pb_i(&f, &l2, 2, PB_I32, dicted ? 8 : 0); + pb_i(&f, &l2, 3, PB_I32, 3); pb_i(&f, &l2, 4, PB_I32, 3); + pb_byte(&f, 0); pb_byte(&f, 0); + pb_bytes(&f, page.p, page.n); + at[g * PQ_SYNTH_COLS + c] = start; sz[g * PQ_SYNTH_COLS + c] = (int64_t)f.n - start; + } + } + static const char* cols[PQ_SYNTH_COLS] = {"x","s","t"}; + int64_t footer = (int64_t)f.n; + int last = 0; + pb_i(&f, &last, 1, PB_I32, 1); + pb_field(&f, &last, 2, PB_LIST); pb_list(&f, PQ_SYNTH_COLS + 1, PB_STRUCT); + { int l = 0; pb_i(&f, &l, 3, PB_I32, 0); pb_field(&f, &l, 4, PB_BIN); pb_bin(&f, "schema", 6); pb_i(&f, &l, 5, PB_I32, PQ_SYNTH_COLS); pb_byte(&f, 0); } + { int l = 0; pb_i(&f, &l, 1, PB_I32, 1); pb_i(&f, &l, 3, PB_I32, 0); pb_field(&f, &l, 4, PB_BIN); pb_bin(&f, "x", 1); pb_byte(&f, 0); } + for (int c = 1; c < PQ_SYNTH_COLS; c++) { + int l = 0; + pb_i(&f, &l, 1, PB_I32, 6); pb_i(&f, &l, 3, PB_I32, 1); + pb_field(&f, &l, 4, PB_BIN); pb_bin(&f, cols[c], 1); pb_i(&f, &l, 6, PB_I32, 0); pb_byte(&f, 0); + } + pb_i(&f, &last, 3, PB_I64, rows); + pb_field(&f, &last, 4, PB_LIST); pb_list(&f, (int)groups, PB_STRUCT); + for (int64_t g = 0; g < groups; g++) { + int64_t n = rows * (g + 1) / groups - rows * g / groups, total = 0; + int l = 0; + pb_field(&f, &l, 1, PB_LIST); pb_list(&f, PQ_SYNTH_COLS, PB_STRUCT); + for (int c = 0; c < PQ_SYNTH_COLS; c++) { + int64_t i = g * PQ_SYNTH_COLS + c; + int lc = 0; + pb_i(&f, &lc, 2, PB_I64, at[i]); + pb_field(&f, &lc, 3, PB_STRUCT); + int lm = 0; + pb_i(&f, &lm, 1, PB_I32, c ? 6 : 1); + if (dat[i] >= 0) { pb_field(&f, &lm, 2, PB_LIST); pb_list(&f, 3, PB_I32); pb_zz(&f, 0); pb_zz(&f, 3); pb_zz(&f, 8); } + else { pb_field(&f, &lm, 2, PB_LIST); pb_list(&f, 2, PB_I32); pb_zz(&f, 0); pb_zz(&f, 3); } + pb_field(&f, &lm, 3, PB_LIST); pb_list(&f, 1, PB_BIN); pb_bin(&f, cols[c], 1); + pb_i(&f, &lm, 4, PB_I32, 0); + pb_i(&f, &lm, 5, PB_I64, n); + pb_i(&f, &lm, 6, PB_I64, sz[i]); + pb_i(&f, &lm, 7, PB_I64, sz[i]); + pb_i(&f, &lm, 9, PB_I64, dat[i] >= 0 ? dat[i] : at[i]); + if (dat[i] >= 0) pb_i(&f, &lm, 11, PB_I64, at[i]); + if (dat[i] >= 0) pb_enc_stats(&f, &lm, true, true, false); + pb_byte(&f, 0); /* meta */ + pb_byte(&f, 0); /* column chunk */ + total += sz[i]; + } + pb_i(&f, &l, 2, PB_I64, total); + pb_i(&f, &l, 3, PB_I64, n); + pb_byte(&f, 0); + } + pb_field(&f, &last, 6, PB_BIN); pb_bin(&f, "rayforce test", 13); + pb_byte(&f, 0); + uint32_t flen = (uint32_t)(f.n - (size_t)footer); + pb_bytes(&f, &flen, 4); pb_bytes(&f, "PAR1", 4); + bool ok = !f.bad && !page.bad && !levels.bad && !values.bad && !dict.bad && !doff.bad; + FILE* out = ok ? fopen(path, "wb") : NULL; + ok = out && fwrite(f.p, 1, f.n, out) == f.n; + if (out && fclose(out)) ok = false; + ray_sys_free(f.p); ray_sys_free(page.p); ray_sys_free(levels.p); ray_sys_free(values.p); + ray_sys_free(dict.p); ray_sys_free(doff.p); + ray_sys_free(at); ray_sys_free(sz); ray_sys_free(dat); + return ok; +} +/* The columns s and t of an import as strings: true when every row is + * fn's (a null and "" both the empty symbol). */ +static bool pq_synth_check(const char* dir, int64_t rows, pq_synth_fn fn) { + char sym[200]; snprintf(sym, sizeof(sym), "%s/.sym", dir); + ray_t* t = ray_read_splayed(dir, sym); + if (!t || RAY_IS_ERR(t)) { if (t) ray_error_free(t); return false; } + bool ok = ray_table_nrows(t) == rows; + char buf[256]; + for (int c = 1; ok && c < PQ_SYNTH_COLS; c++) { + ray_t* s = ray_table_get_col_idx(t, c); + for (int64_t r = 0; ok && r < rows; r++) { + uint32_t len = 0; + const char* want = pq_synth_row(fn, c, r, rows, buf, &len); + if (!want) len = 0; + ray_t* text = ray_sym_vec_cell(s, r); + ok = text && ray_str_len(text) == len && (!len || !memcmp(ray_str_ptr(text), want, len)); + if (ok && ((int32_t*)ray_data(ray_table_get_col_idx(t, 0)))[r] != r) ok = false; + } + } + ray_release(t); + return ok; +} +/* A whole file's bytes compared with another's. */ +static bool pq_same_file(const char* a, const char* b) { + FILE* fa = fopen(a, "rb"); FILE* fb = fopen(b, "rb"); + bool ok = fa && fb; + while (ok) { + char x[4096], y[4096]; + size_t na = fread(x, 1, sizeof(x), fa), nb = fread(y, 1, sizeof(y), fb); + if (na != nb || memcmp(x, y, na)) ok = false; + if (!na) break; + } + if (fa) fclose(fa); + if (fb) fclose(fb); + return ok; +} 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_EQ_I(pq_pool(cores), RAY_OK); + /* 0-3: STR or SYM, one pass or column by column; 5 and 7: SYM + * through the grouped import */ + for (int run = 0; run < 8; run++) { + if (run == 4 || run == 6) continue; + int sym = run & 3; + pq_set_layout(sym >= 2 ? "1" : NULL); + pq_set_symmode(run >= 4 ? "grouped" : NULL); + char dir[160]; snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-groups-%d-%d-%d",(int)getpid(),cores,run); + ray_t* result = ray_parquet_splayed_typed(FIX "row-groups.parquet",dir,sym & 1 ? types : NULL); + pq_set_layout(NULL); pq_set_symmode(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); + ray_t* table = ray_read_splayed(dir,sym & 1 ? 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); + TEST_ASSERT_EQ_I(strings->type,sym & 1 ? 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); } + if (sym & 1) { 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)); } @@ -328,22 +620,70 @@ static test_result_t test_pq_group_native(void) { 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); + for (int grouped = 0; grouped < 2; grouped++) { + char dir[160]; snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-unix-%d-%d",(int)getpid(),grouped); + pq_set_symmode(grouped ? "grouped" : NULL); + ray_t* result = ray_parquet_splayed_typed(FIX "unix.parquet",dir,types); + pq_set_symmode(NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); ray_release(result); + 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_t* text = ray_sym_vec_cell(ray_table_get_col_idx(table,2),1); + TEST_ASSERT_TRUE(text && !strcmp(ray_str_ptr(text),"pooled string number two")); + ray_release(table); pq_remove_native(dir,unames,3); + } + ray_release(types); + PASS(); +} +/* The direct import over dictionary pages, stored (flat-0-v1) and Snappy + * (flat-1-v2): two row groups whose chunks each hold a dictionary page, two + * dictionary-encoded data pages and a PLAIN one, with nulls and an empty + * string (both the SYM null), on one worker and four, in one pass and + * column by column. */ +static test_result_t test_pq_native_dictionary(void) { + const char* files[] = {FIX "flat-0-v1.parquet",FIX "flat-1-v2.parquet"}; + const char* names[] = {"x","name","flag","wide","day","ts","f"}; + const char* strings[] = {"alpha","a long string over twelve bytes","","","alpha","beta","gamma","delta","z"}; + int64_t expect[] = {1,NULL_I32,3,4,5,NULL_I32,7,8,9}; + int64_t 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)}; + ray_t* types = ray_vec_from_raw(RAY_SYM,ids,7); + for (int run = 0; run < 16; run++) { /* 8-15: the grouped import */ + TEST_ASSERT_EQ_I(pq_pool(run & 2 ? 4 : 1), RAY_OK); + char dir[160]; snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-dict-%d-%d",(int)getpid(),run); + pq_set_layout(run & 4 ? "1" : NULL); + pq_set_symmode(run & 8 ? "grouped" : NULL); + ray_t* result = ray_parquet_splayed_typed(files[run & 1],dir,types); + pq_set_layout(NULL); pq_set_symmode(NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); TEST_ASSERT_EQ_I(result->i64,18); ray_release(result); + char sym[200]; snprintf(sym,sizeof(sym),"%s/.sym",dir); + ray_t* table = ray_read_splayed(dir,sym); + TEST_ASSERT_FALSE(RAY_IS_ERR(table)); TEST_ASSERT_EQ_I(ray_table_nrows(table),18); + ray_t* name = ray_table_get_col_idx(table,1); + TEST_ASSERT_EQ_I(name->type,RAY_SYM); + TEST_ASSERT_TRUE(name->attrs & RAY_ATTR_HAS_NULLS); + for (int64_t i = 0; i < 18; i++) { + int j = (int)(i%9); size_t len = strlen(strings[j]); + ray_t* text = ray_sym_vec_cell(name,i); + TEST_ASSERT_TRUE(text != NULL); TEST_ASSERT_EQ_I(ray_str_len(text),len); + TEST_ASSERT_TRUE(!len || !memcmp(ray_str_ptr(text),strings[j],len)); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(ray_table_get_col_idx(table,0)))[i],expect[j]); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(table,3)))[i],100+j); + } + ray_release(table); pq_remove_native(dir,names,7); + ray_pool_destroy(); + } + ray_release(types); 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); + TEST_ASSERT_EQ_I(pq_pool(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++) { @@ -355,30 +695,43 @@ static test_result_t test_pq_native_edges(void) { 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); + char dir[160], sym[200]; + for (int grouped = 0; grouped < 2; grouped++) { + snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-rle-%d-%d",(int)getpid(),grouped); + pq_set_symmode(grouped ? "grouped" : NULL); + t = ray_parquet_splayed_typed(FIX "rle-runs.parquet",dir,types); + pq_set_symmode(NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); ray_release(t); + 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); } - ray_release(t); - const char* names[] = {"x","y","s"}; pq_remove_native(dir,names,3); + ray_release(types); 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()); + pq_set_symmode("grouped"); /* no row group: the grouped import's empty pass */ t = ray_parquet_splayed_typed(FIX "empty.parquet",dir,types); + pq_set_symmode(NULL); 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); + char partial[200]; + for (int grouped = 0; grouped < 2; grouped++) { + pq_set_symmode(grouped ? "grouped" : NULL); + t = ray_parquet_splayed_typed(FIX "projection.parquet",dir,types); + pq_set_symmode(NULL); + TEST_ASSERT_TRUE(RAY_IS_ERR(t)); ray_release(t); TEST_ASSERT_TRUE(access(dir,F_OK) != 0); + 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); @@ -400,7 +753,7 @@ static test_result_t test_pq_native_edges(void) { } static test_result_t test_pq_parted_symbols(void) { - ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(8),RAY_OK); + TEST_ASSERT_EQ_I(pq_pool(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]; @@ -465,10 +818,13 @@ static void* pq_small_stack_worker(void* result) { * 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); + for (int run = 0; run < 4; run++) { + int cores = run & 1 ? 4 : 1; + TEST_ASSERT_EQ_I(pq_pool(cores), RAY_OK); + char dir[160]; snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-zones-%d-%d",(int)getpid(),run); + pq_set_layout(run >= 2 ? "1" : NULL); ray_t* result = ray_parquet_splayed_typed(FIX "zones.parquet",dir,NULL); + pq_set_layout(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)); @@ -510,7 +866,2782 @@ static test_result_t test_pq_small_stack(void) { SKIP("requires POSIX thread stack attributes"); #endif } +#if defined(__linux__) +#include +#include +#include +/* A row group's chunk ends with a flush of the bytes its stream still + * buffers (glibc writes whole blocks of a large write at once and keeps the + * tail). The file size limit here falls inside that tail of the first + * chunk of x (rows 0-5002, the first task), so it is the flush that fails: + * the import must report that chunk's failure, not a later write's, and + * publish nothing. */ +static test_result_t test_pq_chunk_flush_error(void) { + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + 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); + char dir[160]; snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-flush-%d",(int)getpid()); + struct rlimit old, lim; + TEST_ASSERT_EQ_I(getrlimit(RLIMIT_FSIZE,&old),0); + lim = old; lim.rlim_cur = 32 + 5003*4 - 1; + void (*prev)(int) = signal(SIGXFSZ,SIG_IGN); + pq_set_layout(NULL); + TEST_ASSERT_EQ_I(setrlimit(RLIMIT_FSIZE,&lim),0); + ray_t* result = ray_parquet_splayed_typed(FIX "row-groups.parquet",dir,types); + setrlimit(RLIMIT_FSIZE,&old); + signal(SIGXFSZ,prev); + ray_release(types); + bool failed = RAY_IS_ERR(result); + const char* code = failed ? ray_err_code(result) : ""; + bool on_chunk = failed && code && strcmp(code,"parquet") == 0; /* the flush, not a later write */ + if (failed) ray_error_free(result); else ray_release(result); + struct stat st; + bool published = stat(dir,&st) == 0; + char staging[200]; snprintf(staging,sizeof(staging),"%s.parquet-partial",dir); + const char* names[] = {"x","y","s"}; + pq_remove_native(dir,names,3); pq_remove_native(staging,names,3); + ray_pool_destroy(); + TEST_ASSERT_TRUE(failed); + TEST_ASSERT_FALSE(published); + TEST_ASSERT_TRUE(on_chunk); + PASS(); +} +#endif + +/* Rows for the grouped import: repeats inside and across row groups, + * nulls, "" and strings past the inline bytes. */ +static const char* pq_synth_mixed(int64_t r, char* buf, uint32_t* len) { + if (r % 17 == 0) return NULL; + if (r % 23 == 0) { *len = 0; return buf; } + int n = snprintf(buf, 256, "v%lld-%s", (long long)((r * 7919) % 3001), + r % 3 ? "s" : "a longer tail past the inline bytes"); + *len = (uint32_t)n; + return buf; +} +/* 48 strings of one length told apart by one byte: the first, the middle + * or the last. */ +static const char* pq_synth_alike(int64_t r, char* buf, uint32_t* len) { + if (r % 29 == 0) return NULL; + memcpy(buf, "abcdefghijklmnopqrstuvwxyz012345", 32); + int v = (int)((r * 13) % 48), at = v < 16 ? 0 : v < 32 ? 16 : 31; + buf[at] = (char)('A' + v % 16); + *len = 32; + return buf; +} +/* A unique 100-byte string a row. */ +static const char* pq_synth_long(int64_t r, char* buf, uint32_t* len) { + int n = snprintf(buf, 256, "%08lld", (long long)r); + memset(buf + n, 'x', (size_t)(100 - n)); + *len = 100; + return buf; +} +/* An import with RAY_CSV_TRACE set, its trace (stderr) kept in buf, which + * ends with a NUL; buf is empty when stderr cannot be redirected. */ +static ray_t* pq_traced_import(const char* src, const char* dir, ray_t* types, char* buf, size_t cap) { + char path[160]; snprintf(path, sizeof(path), "/tmp/rayforce-pq-trace-%d.txt", (int)getpid()); + buf[0] = 0; + fflush(stderr); + int saved = dup(2), fd = open(path, O_CREAT | O_TRUNC | O_RDWR, 0600); + bool redirected = saved >= 0 && fd >= 0 && dup2(fd, 2) >= 0; + if (fd >= 0) close(fd); + pq_set_env("RAY_CSV_TRACE", "1"); + ray_t* res = ray_parquet_splayed_typed(src, dir, types); + pq_set_env("RAY_CSV_TRACE", NULL); + fflush(stderr); + if (redirected) dup2(saved, 2); + if (saved >= 0) close(saved); + FILE* f = redirected ? fopen(path, "rb") : NULL; + size_t n = f ? fread(buf, 1, cap - 1, f) : 0; + if (f) fclose(f); + buf[n] = 0; + unlink(path); + return res; +} +/* The sum of a trace field (" key=value") over the trace's lines, and how + * many lines have it. */ +static double pq_trace_sum(const char* buf, const char* key, int* lines) { + char pat[64]; snprintf(pat, sizeof(pat), " %s=", key); + size_t pl = strlen(pat); + double sum = 0; int n = 0; + for (const char* p = buf; (p = strstr(p, pat)); p += pl) { sum += strtod(p + pl, NULL); n++; } + if (lines) *lines = n; + return sum; +} +/* Whether the trace's first line starting with `line` has `token` in it. */ +static bool pq_trace_line_has(const char* buf, const char* line, const char* token) { + const char* p = strstr(buf, line); + if (!p) return false; + const char* e = strchr(p, '\n'); + const char* q = strstr(p, token); + return q && (!e || q < e); +} +/* A field of the trace's first line starting with `line` (" key=value"), + * -1 when there is none. */ +static double pq_trace_line_num(const char* buf, const char* line, const char* key) { + const char* p = strstr(buf, line); + if (!p) return -1; + const char* e = strchr(p, '\n'); + char pat[64]; snprintf(pat, sizeof(pat), " %s=", key); + const char* q = strstr(p, pat); + return q && (!e || q < e) ? strtod(q + strlen(pat), NULL) : -1; +} +/* The entries of an import's symbol file (its header count). */ +static int64_t pq_sym_count(const char* dir) { + char path[200]; snprintf(path, sizeof(path), "%s/.sym", dir); + FILE* f = fopen(path, "rb"); + uint8_t head[12]; + int64_t count = -1; + if (f && fread(head, 1, 12, f) == 12) memcpy(&count, head + 4, 8); + if (f) fclose(f); + return count; +} + +/* The grouped import of a 9-row-group file: every row's string, the same + * vocabulary as the direct import's, and positions (the symbol file and the + * column file byte for byte) that do not depend on the worker count, in + * every order of new positions, over several hash groups and windows. Its + * trace: no collision on this data (a comparison that never matched would + * still give every string a position, through the collision path), and + * every record's writeback started by the window that wrote it (exactly + * the records' bytes in the orders that write each window's records side + * by side). */ +static test_result_t test_pq_sym_grouped(void) { + pq_sym_env_clear(); + char src[160]; snprintf(src, sizeof(src), "/tmp/rayforce-pq-synth-%d.parquet", (int)getpid()); + const int64_t rows = 20000; + TEST_ASSERT_TRUE(pq_synth(src, rows, 9, pq_synth_mixed)); + int64_t tids[] = {ray_sym_intern("I32",3), ray_sym_intern("SYM",3), ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + const char* names[] = {"x","s","t"}; + const char* orders[] = {"rows","shards","freq","rowsflat"}; + char dir[160], ref[160], a[200], b[200]; + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-sg-direct-%d", (int)getpid()); + pq_set_symmode("direct"); + ray_t* res = ray_parquet_splayed_typed(src, dir, types); + pq_set_symmode(NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(res)); ray_release(res); + TEST_ASSERT_TRUE(pq_synth_check(dir, rows, pq_synth_mixed)); + int64_t words = pq_sym_count(dir); + TEST_ASSERT_TRUE(words > 1000); + pq_remove_native(dir, names, 3); + pq_set_env("RAY_PQ_SYM_GROUPS", "4"); + pq_set_env("RAY_PQ_SYM_WINDOW", "4096"); /* debug builds: several windows */ + for (int o = 0; o < 4; o++) { + pq_set_env("RAY_PQ_SYM_ORDER", orders[o]); + snprintf(ref, sizeof(ref), "/tmp/rayforce-pq-sg-%d-%d-1", (int)getpid(), o); + for (int cores = 1; cores <= 8; cores *= 2) { + TEST_ASSERT_EQ_I(pq_pool(cores), RAY_OK); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-sg-%d-%d-%d", (int)getpid(), o, cores); + pq_set_symmode("grouped"); pq_set_layout(cores == 2 ? "1" : NULL); + res = pq_traced_import(src, dir, types, trace, cap); + pq_set_symmode(NULL); pq_set_layout(NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(res)); TEST_ASSERT_EQ_I(res->i64, rows); ray_release(res); + TEST_ASSERT_TRUE(pq_synth_check(dir, rows, pq_synth_mixed)); + TEST_ASSERT_EQ_I(pq_sym_count(dir), words); /* no string twice */ + int passes = 0; + double windows = pq_trace_sum(trace, "windows", &passes); + double recb = pq_trace_sum(trace, "rec_bytes", NULL), wbb = pq_trace_sum(trace, "wb_bytes", NULL); + TEST_ASSERT_EQ_I(passes, 2); + TEST_ASSERT_TRUE(windows > 2 * passes); + TEST_ASSERT_TRUE(pq_trace_sum(trace, "collisions", NULL) == 0); + TEST_ASSERT_TRUE(recb > 0); + if (o == 0 || o == 3) TEST_ASSERT_TRUE(wbb == recb); + else TEST_ASSERT_TRUE(wbb >= recb); + if (cores > 1) { + snprintf(a, sizeof(a), "%s/.sym", ref); snprintf(b, sizeof(b), "%s/.sym", dir); + TEST_ASSERT_TRUE(pq_same_file(a, b)); + for (int c = 1; c < 3; c++) { + snprintf(a, sizeof(a), "%s/%s", ref, names[c]); snprintf(b, sizeof(b), "%s/%s", dir, names[c]); + TEST_ASSERT_TRUE(pq_same_file(a, b)); + } + pq_remove_native(dir, names, 3); + } + ray_pool_destroy(); + } + pq_remove_native(ref, names, 3); + } + pq_set_env("RAY_PQ_SYM_ORDER", NULL); pq_set_env("RAY_PQ_SYM_GROUPS", NULL); + pq_set_env("RAY_PQ_SYM_WINDOW", NULL); + ray_sys_free(trace); + ray_release(types); unlink(src); + PASS(); +} + +/* Hash collisions on purpose (a debug build keeps none of the hash's bits): + * 48 strings of one length that differ only in their first, middle or last + * byte all share a hash, and the dedupe arena is small enough to start + * over inside a chunk. Every candidate is then compared, most mismatch, + * and each string still gets one position of its own, in every order, on + * one worker and four; with some of the bits kept (the low ones, or the + * top ones over several hash groups) the vocabulary is the + * direct import's. */ +static test_result_t test_pq_sym_grouped_collisions(void) { +#if !defined(DEBUG) + SKIP("hash truncation is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], mix[160], dir[160]; + snprintf(src, sizeof(src), "/tmp/rayforce-pq-alike-%d.parquet", (int)getpid()); + snprintf(mix, sizeof(mix), "/tmp/rayforce-pq-mixed-%d.parquet", (int)getpid()); + TEST_ASSERT_TRUE(pq_synth(src, 3000, 5, pq_synth_alike)); + TEST_ASSERT_TRUE(pq_synth(mix, 6000, 4, pq_synth_mixed)); + int64_t tids[] = {ray_sym_intern("I32",3), ray_sym_intern("SYM",3), ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + const char* names[] = {"x","s","t"}; + const char* orders[] = {"rows","shards","freq","rowsflat"}; + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-coll-%d", (int)getpid()); + ray_t* res = ray_parquet_splayed_typed(mix, dir, types); /* direct */ + TEST_ASSERT_FALSE(RAY_IS_ERR(res)); ray_release(res); + int64_t words = pq_sym_count(dir); + pq_remove_native(dir, names, 3); + pq_set_env("RAY_PQ_SYM_ARENA", "200"); + /* one window (candidates of other tasks deferred, mismatches redone) + * or a window a task (candidates compared with records read before) */ + for (int run = 0; run < 16; run++) { + int o = run % 4, cores = run & 4 ? 4 : 1; + pq_set_env("RAY_PQ_SYM_WINDOW", run >= 8 ? "64" : NULL); + TEST_ASSERT_EQ_I(pq_pool(cores), RAY_OK); + pq_set_env("RAY_PQ_SYM_ORDER", orders[o]); + pq_set_env("RAY_PQ_SYM_HASH_BITS", "0"); + pq_set_symmode("grouped"); + char trace[8192]; + res = pq_traced_import(src, dir, types, trace, sizeof(trace)); + TEST_ASSERT_FALSE(RAY_IS_ERR(res)); ray_release(res); + TEST_ASSERT_TRUE(pq_synth_check(dir, 3000, pq_synth_alike)); + TEST_ASSERT_EQ_I(pq_sym_count(dir), 49); /* "" and the 48 */ + /* the trace counts the collisions, and the writeback covers the + * records they added */ + TEST_ASSERT_TRUE(pq_trace_sum(trace, "collisions", NULL) > 0); + double recb = pq_trace_sum(trace, "rec_bytes", NULL), wbb = pq_trace_sum(trace, "wb_bytes", NULL); + TEST_ASSERT_TRUE(o == 0 || o == 3 ? wbb == recb : wbb >= recb); + /* the second column's pass takes nothing into its index: the + * first's records are there, those its collisions added too */ + TEST_ASSERT_TRUE(pq_trace_sum(trace, "adopted", NULL) == 0); + pq_remove_native(dir, names, 3); + /* six low bits of the hash kept, or (a run in two) its two top + * bits with four hash groups: collisions in every group, not only + * the first */ + bool top = (run & 2) != 0; + pq_set_env("RAY_PQ_SYM_HASH_BITS", top ? NULL : "6"); + pq_set_env("RAY_PQ_SYM_HASH_TOP", top ? "2" : NULL); + pq_set_env("RAY_PQ_SYM_GROUPS", top ? "4" : NULL); + res = pq_traced_import(mix, dir, types, trace, sizeof(trace)); + pq_set_env("RAY_PQ_SYM_HASH_TOP", NULL); pq_set_env("RAY_PQ_SYM_GROUPS", NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(res)); ray_release(res); + TEST_ASSERT_TRUE(pq_synth_check(dir, 6000, pq_synth_mixed)); + TEST_ASSERT_EQ_I(pq_sym_count(dir), words); + if (top) TEST_ASSERT_TRUE(pq_trace_sum(trace, "collisions", NULL) > 0); + TEST_ASSERT_TRUE(pq_trace_sum(trace, "adopted", NULL) == 0); + pq_remove_native(dir, names, 3); + ray_pool_destroy(); + } + pq_set_symmode(NULL); + pq_set_env("RAY_PQ_SYM_ORDER", NULL); pq_set_env("RAY_PQ_SYM_HASH_BITS", NULL); + pq_set_env("RAY_PQ_SYM_ARENA", NULL); pq_set_env("RAY_PQ_SYM_WINDOW", NULL); + ray_release(types); unlink(src); unlink(mix); + PASS(); +#endif +} + +/* Strings as a column of addresses has them: half the rows a string of + * their own, the rest drawn from a few heavy hitters and a long tail + * (k uniform below m, m uniform in 1..4000), 20 to 119 bytes. */ +static const char* pq_synth_zipf(int64_t r, char* buf, uint32_t* len) { + uint64_t x = (uint64_t)r * UINT64_C(0x9E3779B97F4A7C15); + x ^= x >> 29; x *= UINT64_C(0xBF58476D1CE4E5B9); x ^= x >> 32; + uint64_t key = x & 1 ? (uint64_t)r : (x >> 1) % (1 + (x >> 40) % 4000); + int n = snprintf(buf, 256, "%c%llu/", x & 1 ? 'u' : 'z', (unsigned long long)key); + int want = 20 + (int)((key * 7919) % 100); + if (n < want) { memset(buf + n, 'p', (size_t)(want - n)); n = want; } + *len = (uint32_t)n; + return buf; +} +/* The positions the grouped import gives a pass's new strings: under + * "rows" first the strings a later row group meets again, then the others, + * each part in first-occurrence order; under "rowsflat" all of them in + * first-occurrence order. On one worker and four, over several windows + * (debug builds), the vocabulary the direct import's. */ +static test_result_t test_pq_sym_grouped_layout(void) { + pq_sym_env_clear(); + char src[160], dir[160], sym[200]; + snprintf(src, sizeof(src), "/tmp/rayforce-pq-zipf-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-layout-%d", (int)getpid()); + snprintf(sym, sizeof(sym), "%s/.sym", dir); + const int64_t rows = 24000, groups = 12; + TEST_ASSERT_TRUE(pq_synth(src, rows, groups, pq_synth_zipf)); + int64_t tids[] = {ray_sym_intern("I32",3), ray_sym_intern("SYM",3), ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + const char* names[] = {"x","s","t"}; + ray_t* res = ray_parquet_splayed_typed(src, dir, types); /* direct */ + TEST_ASSERT_FALSE(RAY_IS_ERR(res)); ray_release(res); + int64_t words = pq_sym_count(dir); + pq_remove_native(dir, names, 3); + pq_set_env("RAY_PQ_SYM_WINDOW", "16384"); + for (int run = 0; run < 4; run++) { + bool split = run < 2; + TEST_ASSERT_EQ_I(pq_pool(run & 1 ? 4 : 1), RAY_OK); + pq_set_env("RAY_PQ_SYM_ORDER", split ? "rows" : "rowsflat"); + pq_set_env("RAY_PQ_SYM_GROUPS", run & 1 ? "64" : NULL); /* a group table over and over */ + pq_set_symmode("grouped"); + /* a dedupe arena of 100000 bytes a generation: past the 64 KB it + * starts with, doubled no further than that */ + pq_set_env("RAY_PQ_SYM_ARENA", "100000"); + char trace[8192]; + res = pq_traced_import(src, dir, types, trace, sizeof(trace)); + pq_set_env("RAY_PQ_SYM_ARENA", NULL); + pq_set_symmode(NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(res)); ray_release(res); + TEST_ASSERT_TRUE(pq_synth_check(dir, rows, pq_synth_zipf)); + int gpasses = 0, workers = run & 1 ? 4 : 1; + double arena = pq_trace_sum(trace, "arena_kb", &gpasses); + if (arena > gpasses * workers * 98.0 || arena <= gpasses * 64.0) fprintf(stderr, " layout %d: arenas %.0f KB in %d passes\n", run, arena, gpasses); + TEST_ASSERT_TRUE(gpasses == 2 && arena > gpasses * 64.0 && arena <= gpasses * workers * 98.0); + TEST_ASSERT_EQ_I(pq_sym_count(dir), words); + /* the column of the first pass (the smaller chunks), the one whose + * strings hold positions 1 to their count: their first row and + * whether a later row group has them too, by position */ + ray_t* t = ray_read_splayed(dir, sym); + TEST_ASSERT_FALSE(!t || RAY_IS_ERR(t)); + int64_t* first = (int64_t*)ray_sys_alloc((size_t)words * sizeof(int64_t)); + uint8_t* again = (uint8_t*)ray_sys_alloc((size_t)words); + TEST_ASSERT_TRUE(first && again); + int64_t met = 0, others = 0, passes = 0; + bool order = true, parted = true; + for (int c = 1; c < 3; c++) { + ray_t* s = ray_table_get_col_idx(t, c); + int64_t distinct = 0, run1 = 0; + for (int64_t p = 0; p < words; p++) { first[p] = -1; again[p] = 0; } + for (int64_t r = 0; r < rows; r++) { + int64_t p = ray_read_sym(ray_data(s), r, RAY_SYM, s->attrs); + if (p <= 0 || p >= words) continue; + if (first[p] < 0) { first[p] = r; distinct++; } + else if (first[p] * groups / rows != r * groups / rows) again[p] = 1; + } + while (run1 + 1 < words && first[run1 + 1] >= 0) run1++; + if (run1 != distinct) continue; + passes++; + int64_t last[2] = {-1, -1}; + for (int64_t p = 1; p <= run1; p++) { + int a = split ? again[p] : 0; + if (first[p] < last[a]) order = false; + last[a] = first[p]; + if (again[p]) met++; else others++; + if (split && again[p] && others) parted = false; + } + } + ray_sys_free(first); ray_sys_free(again); + ray_release(t); + TEST_ASSERT_EQ_I(passes, 1); + TEST_ASSERT_TRUE(met > 100 && others > 100); + TEST_ASSERT_TRUE(order); + TEST_ASSERT_TRUE(parted); + pq_remove_native(dir, names, 3); + ray_pool_destroy(); + } + pq_set_env("RAY_PQ_SYM_ORDER", NULL); pq_set_env("RAY_PQ_SYM_WINDOW", NULL); + pq_set_env("RAY_PQ_SYM_GROUPS", NULL); + ray_release(types); unlink(src); + PASS(); +} + +/* A low-cardinality column (40 strings, nulls, dictionary-encoded) and a + * high-cardinality one: a string of its own a row but every fifth, which + * is one of the other column's, or (sparse) one in twenty rows, 34 bytes + * of its own, the rest null: fewer bytes than the other column's, so it + * comes first by size. */ +static const char* pq_synth_lowcard(int64_t r, char* buf, uint32_t* len) { + if (r % 31 == 0) return NULL; + *len = (uint32_t)snprintf(buf, 256, "c%02lld", (long long)((r * 7) % 40)); + return buf; +} +static const char* pq_synth_highcard(int64_t r, char* buf, uint32_t* len) { + if (r % 5 == 0) return pq_synth_lowcard(r + 1, buf, len); + *len = (uint32_t)snprintf(buf, 256, "u%06lld-high", (long long)r); + return buf; +} +static const char* pq_synth_sparse(int64_t r, char* buf, uint32_t* len) { + if (r % 20) return NULL; + *len = (uint32_t)snprintf(buf, 256, "sparse-%06lld-and-twenty-bytes", (long long)r); + return buf; +} +/* Grouped or direct, column by column: with symbol text past a quarter of + * the memory the decision assumes (RAY_PQ_SYM_RAM, debug builds) the + * low-cardinality column still goes direct, decoded once, ahead of the + * grouped one (the sparse one included, smaller as it is), which takes its + * strings into its index: every row's string and the direct import's + * vocabulary (none twice), on one worker and four the same files (the + * direct pass's dictionaries seeded in row-group order); the trace + * tells which column went which way. Forced grouped, both columns are. */ +static test_result_t test_pq_sym_mixed_modes(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160], ref[160]; + snprintf(src, sizeof(src), "/tmp/rayforce-pq-mixmode-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-mixmode-%d", (int)getpid()); + snprintf(ref, sizeof(ref), "/tmp/rayforce-pq-mixmode-%d-ref", (int)getpid()); + int64_t rows = 20000; + int64_t tids[] = {ray_sym_intern("I32",3), ray_sym_intern("SYM",3), ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + const char* names[] = {"x","s","t"}; + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + int bad = 0; + for (int v = 0; v < 2; v++) { + pq_synth_t = v ? pq_synth_sparse : pq_synth_highcard; pq_synth_dict = 1u << 1; + /* the sparse variant twice the rows in half the row groups: its text + * past a quarter of memory with s's bound in a sixty-fourth */ + rows = v ? 40000 : 20000; + bool made = pq_synth(src, rows, v ? 2 : 4, pq_synth_lowcard); + TEST_ASSERT_TRUE(made); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + pq_set_symmode("direct"); + ray_t* res = pq_traced_import(src, dir, types, trace, cap); + pq_set_symmode(NULL); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + TEST_ASSERT_TRUE(pq_synth_check(dir, rows, pq_synth_lowcard)); + int64_t words = pq_sym_count(dir); + pq_remove_native(dir, names, 3); + /* the sparse column first by size */ + if (v && !(strstr(trace, "parquet symcol: col=t ") < strstr(trace, "parquet symcol: col=s "))) bad++; + /* the memory the decision assumes: s's bound just within its + * sixty-fourth, the symbol text past its quarter, t's bound past + * its sixty-fourth (the footer's bounds, from the trace) */ + double bs = pq_trace_line_num(trace, "parquet symcol: col=s ", "vocab_bytes"); + double bt = pq_trace_line_num(trace, "parquet symcol: col=t ", "vocab_bytes"); + double text = pq_trace_line_num(trace, "parquet symcol: col=s ", "text_bytes") + + pq_trace_line_num(trace, "parquet symcol: col=t ", "text_bytes"); + int64_t sram = (int64_t)bs * 64; + char ramv[32]; snprintf(ramv, sizeof(ramv), "%lld", (long long)sram); + if (bs <= 0 || sram / 4 >= text || bt <= sram / 64) { + fprintf(stderr, " %d: no memory size mixes them: s %.0f, t %.0f, text %.0f\n", v, bs, bt, text); + bad++; + } + for (int run = 0; run < 4; run++) { + /* one worker's files kept for four workers' and for one worker's + * row groups last to first (a debug knob) */ + const char* out = run ? dir : ref; + TEST_ASSERT_EQ_I(pq_pool(run == 1 ? 4 : 1), RAY_OK); + pq_set_env("RAY_PQ_SYM_RAM", ramv); + pq_set_symmode(run == 3 ? "grouped" : NULL); + if (run == 2) pq_set_env("RAY_PQ_DIRECT_REVERSE", "1"); + res = pq_traced_import(src, out, types, trace, cap); + pq_sym_env_clear(); + if (!res || RAY_IS_ERR(res)) { + fprintf(stderr, " %d/%d: import failed: %s\n", v, run, res ? ray_err_code(res) : "null"); + if (res) ray_error_free(res); + char partial[200]; snprintf(partial, sizeof(partial), "%s.parquet-partial", out); + pq_remove_native(partial, names, 3); + bad++; continue; + } + ray_release(res); + if (!pq_synth_check(out, rows, pq_synth_lowcard)) { fprintf(stderr, " %d/%d: rows differ\n", v, run); bad++; } + if (pq_sym_count(out) != words) { fprintf(stderr, " %d/%d: %lld symbols, direct %lld\n", v, run, (long long)pq_sym_count(out), (long long)words); bad++; } + bool s_direct = pq_trace_line_has(trace, "parquet symcol: col=s ", " mode=direct"); + bool t_grouped = pq_trace_line_has(trace, "parquet symcol: col=t ", " mode=grouped"); + int passes = 0; + double adopted = pq_trace_sum(trace, "adopted", &passes); + fprintf(stderr, " %d/%d: s %s, t %s, grouped passes %d, adopted %.0f\n", v, run, s_direct ? "direct" : "grouped", + t_grouped ? "grouped" : "direct", passes, adopted); + /* forced: the second pass adopts nothing, the first's records in its + * index already */ + if (run < 3 ? !s_direct || !t_grouped || passes != 1 || adopted != 40 : s_direct || !t_grouped || passes != 2 || adopted != 0) bad++; + /* the direct passes' shard tables freed at the first reservation: + * none through the grouped passes */ + double tabs = pq_trace_sum(trace, "imp_index_kb", NULL); + if (tabs != 0) { fprintf(stderr, " %d/%d: the import dictionary's shard tables kept, %.0f KB\n", v, run, tabs); bad++; } + if (run == 1 || run == 2) { + /* the direct pass's positions too: s's dictionaries seeded + * in row-group order */ + char a[220], b[220]; + bool same = true; + snprintf(a, sizeof(a), "%s/.sym", ref); snprintf(b, sizeof(b), "%s/.sym", dir); + if (!pq_same_file(a, b)) same = false; + for (int c = 1; c < 3; c++) { + snprintf(a, sizeof(a), "%s/%s", ref, names[c]); snprintf(b, sizeof(b), "%s/%s", dir, names[c]); + if (!pq_same_file(a, b)) same = false; + } + if (!same) { fprintf(stderr, " %d/%d: files differ from one worker's\n", v, run); bad++; } + if (run == 2) pq_remove_native(ref, names, 3); + } + if (run) pq_remove_native(dir, names, 3); + } + unlink(src); + } + pq_synth_t = NULL; pq_synth_dict = 0; + ray_pool_destroy(); + ray_sys_free(trace); + ray_release(types); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} + +/* The grouped import failing: out of memory in each of its steps (a debug + * build injects it), its record writes failing, cancelled in the middle, + * and the symbol file unable to grow (the file size limit; the direct + * import too). Each reports its error and publishes nothing. */ +static test_result_t test_pq_sym_grouped_failures(void) { + pq_sym_env_clear(); + char src[160], big[160], dir[160], partial[200]; + snprintf(src, sizeof(src), "/tmp/rayforce-pq-fail-%d.parquet", (int)getpid()); + snprintf(big, sizeof(big), "/tmp/rayforce-pq-fail-big-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-fail-%d", (int)getpid()); + snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + TEST_ASSERT_TRUE(pq_synth(src, 20000, 9, pq_synth_mixed)); + TEST_ASSERT_TRUE(pq_synth(big, 20000, 4, pq_synth_long)); + int64_t tids[] = {ray_sym_intern("I32",3), ray_sym_intern("SYM",3), ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + const char* names[] = {"x","s","t"}; + TEST_ASSERT_EQ_I(pq_pool(4), RAY_OK); +#if defined(DEBUG) + const char* steps[] = {"r1","p2","load","reload","r2","write","settle","cancel"}; + for (int i = 0; i < 8; i++) { + pq_set_symmode("grouped"); + pq_set_env("RAY_PQ_SYM_INJECT", steps[i]); + pq_set_env("RAY_PQ_SYM_WINDOW", "4096"); /* a window a row group: "reload" fails one */ + ray_t* res = ray_parquet_splayed_typed(src, dir, types); + pq_set_env("RAY_PQ_SYM_INJECT", NULL); pq_set_env("RAY_PQ_SYM_WINDOW", NULL); pq_set_symmode(NULL); + bool failed = res && RAY_IS_ERR(res); + bool cancel = failed && !strcmp(ray_err_code(res), "cancel"); + if (res) { if (failed) ray_error_free(res); else ray_release(res); } + ray_clear_interrupt(); + TEST_ASSERT_TRUE(failed); + TEST_ASSERT_TRUE(cancel == (i == 7)); + TEST_ASSERT_TRUE(access(dir, F_OK) != 0); + pq_remove_native(partial, names, 3); + } +#endif +#if defined(__linux__) + /* 2 MB of records; the column files are 80 KB */ + for (int grouped = 0; grouped < 2; grouped++) { + struct rlimit old, lim; + TEST_ASSERT_EQ_I(getrlimit(RLIMIT_FSIZE, &old), 0); + lim = old; lim.rlim_cur = 1536 << 10; + void (*prev)(int) = signal(SIGXFSZ, SIG_IGN); + pq_set_symmode(grouped ? "grouped" : "direct"); + TEST_ASSERT_EQ_I(setrlimit(RLIMIT_FSIZE, &lim), 0); + ray_t* res = ray_parquet_splayed_typed(big, dir, types); + setrlimit(RLIMIT_FSIZE, &old); + signal(SIGXFSZ, prev); + pq_set_symmode(NULL); + bool failed = res && RAY_IS_ERR(res); + if (res) { if (failed) ray_error_free(res); else ray_release(res); } + TEST_ASSERT_TRUE(failed); + TEST_ASSERT_TRUE(access(dir, F_OK) != 0); + pq_remove_native(partial, names, 3); + } +#endif + ray_pool_destroy(); + ray_release(types); unlink(src); unlink(big); + PASS(); +} + +/* One row group of six rows of a required BYTE_ARRAY column s, every row + * the first entry of a stored (uncompressed) dictionary page of two entries + * whose header declares `declared` decoded bytes and `count` entries. */ +static bool pq_dict_file(const char* path, int64_t declared, int64_t count) { + pq_buf f = {0}, dict = {0}, data = {0}; + const char* entries[] = {"first", "second-entry-longer"}; + for (int k = 0; k < 2; k++) { + uint32_t l = (uint32_t)strlen(entries[k]); + pb_bytes(&dict, &l, 4); pb_bytes(&dict, entries[k], l); + } + const int64_t rows = 6; + pb_byte(&data, 1); pb_var(&data, (uint64_t)rows << 1); pb_byte(&data, 0); /* width 1, a run of id 0 */ + pb_bytes(&f, "PAR1", 4); + int64_t start = (int64_t)f.n; + int last = 0; + pb_i(&f, &last, 1, PB_I32, 2); pb_i(&f, &last, 2, PB_I32, declared); pb_i(&f, &last, 3, PB_I32, (int64_t)dict.n); + pb_field(&f, &last, 7, PB_STRUCT); + { int l = 0; pb_i(&f, &l, 1, PB_I32, count); pb_i(&f, &l, 2, PB_I32, 0); pb_byte(&f, 0); } + pb_byte(&f, 0); + pb_bytes(&f, dict.p, dict.n); + int64_t data_off = (int64_t)f.n; + last = 0; + pb_i(&f, &last, 1, PB_I32, 0); pb_i(&f, &last, 2, PB_I32, (int64_t)data.n); pb_i(&f, &last, 3, PB_I32, (int64_t)data.n); + pb_field(&f, &last, 5, PB_STRUCT); + { int l = 0; pb_i(&f, &l, 1, PB_I32, rows); pb_i(&f, &l, 2, PB_I32, 8); pb_i(&f, &l, 3, PB_I32, 3); pb_i(&f, &l, 4, PB_I32, 3); pb_byte(&f, 0); } + pb_byte(&f, 0); + pb_bytes(&f, data.p, data.n); + int64_t chunk = (int64_t)f.n - start, footer = (int64_t)f.n; + last = 0; + pb_i(&f, &last, 1, PB_I32, 1); + pb_field(&f, &last, 2, PB_LIST); pb_list(&f, 2, PB_STRUCT); + { int l = 0; pb_i(&f, &l, 3, PB_I32, 0); pb_field(&f, &l, 4, PB_BIN); pb_bin(&f, "schema", 6); pb_i(&f, &l, 5, PB_I32, 1); pb_byte(&f, 0); } + { int l = 0; pb_i(&f, &l, 1, PB_I32, 6); pb_i(&f, &l, 3, PB_I32, 0); pb_field(&f, &l, 4, PB_BIN); pb_bin(&f, "s", 1); pb_i(&f, &l, 6, PB_I32, 0); pb_byte(&f, 0); } + pb_i(&f, &last, 3, PB_I64, rows); + pb_field(&f, &last, 4, PB_LIST); pb_list(&f, 1, PB_STRUCT); + { + int l = 0; + pb_field(&f, &l, 1, PB_LIST); pb_list(&f, 1, PB_STRUCT); + int lc = 0; + pb_i(&f, &lc, 2, PB_I64, start); + pb_field(&f, &lc, 3, PB_STRUCT); + int lm = 0; + pb_i(&f, &lm, 1, PB_I32, 6); + pb_field(&f, &lm, 2, PB_LIST); pb_list(&f, 3, PB_I32); pb_zz(&f, 0); pb_zz(&f, 3); pb_zz(&f, 8); + pb_field(&f, &lm, 3, PB_LIST); pb_list(&f, 1, PB_BIN); pb_bin(&f, "s", 1); + pb_i(&f, &lm, 4, PB_I32, 0); + pb_i(&f, &lm, 5, PB_I64, rows); + pb_i(&f, &lm, 6, PB_I64, chunk); + pb_i(&f, &lm, 7, PB_I64, chunk); + pb_i(&f, &lm, 9, PB_I64, data_off); + pb_i(&f, &lm, 11, PB_I64, start); + pb_byte(&f, 0); /* meta */ + pb_byte(&f, 0); /* column chunk */ + pb_i(&f, &l, 2, PB_I64, chunk); + pb_i(&f, &l, 3, PB_I64, rows); + pb_byte(&f, 0); + } + pb_field(&f, &last, 6, PB_BIN); pb_bin(&f, "rayforce test", 13); + pb_byte(&f, 0); + uint32_t flen = (uint32_t)(f.n - (size_t)footer); + pb_bytes(&f, &flen, 4); pb_bytes(&f, "PAR1", 4); + bool ok = !f.bad && !dict.bad && !data.bad; + FILE* out = ok ? fopen(path, "wb") : NULL; + ok = out && fwrite(f.p, 1, f.n, out) == f.n; + if (out && fclose(out)) ok = false; + ray_sys_free(f.p); ray_sys_free(dict.p); ray_sys_free(data.p); + return ok; +} +/* A stored dictionary page must decode to exactly the bytes it stores: a + * header that declares fewer (here just the first entry's, with a count of + * one, which would parse) or many more (up to the 64 MiB page limit, far + * past the file) is an invalid page, for the read and for the direct and + * grouped imports alike; the honest page reads. */ +static test_result_t test_pq_dict_page_size(void) { + pq_sym_env_clear(); + char src[160], dir[160], partial[200]; + snprintf(src, sizeof(src), "/tmp/rayforce-pq-dictsize-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-dictsize-%d", (int)getpid()); + snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + int64_t tid = ray_sym_intern("SYM", 3); + ray_t* types = ray_vec_from_raw(RAY_SYM, &tid, 1); + const char* names[] = {"s"}; + const int64_t declared[3] = {4 + 5, (INT64_C(64) << 20) - 1, 4 + 5 + 4 + 19}; + const int64_t counts[3] = {1, 2, 2}; + for (int c = 0; c < 3; c++) { + bool honest = c == 2; + TEST_ASSERT_TRUE(pq_dict_file(src, declared[c], counts[c])); + ray_t* t = ray_parquet_read(src, NULL); + TEST_ASSERT_TRUE(t != NULL); + TEST_ASSERT_TRUE(RAY_IS_ERR(t) != honest); + if (honest) { + size_t len; const char* text = ray_str_vec_get(ray_table_get_col_idx(t, 0), 5, &len); + TEST_ASSERT_TRUE(len == 5 && !memcmp(text, "first", 5)); + } + if (RAY_IS_ERR(t)) ray_error_free(t); else ray_release(t); + for (int grouped = 0; grouped < 2; grouped++) { + pq_set_symmode(grouped ? "grouped" : "direct"); + t = ray_parquet_splayed_typed(src, dir, types); + pq_set_symmode(NULL); + TEST_ASSERT_TRUE(t != NULL); + TEST_ASSERT_TRUE(RAY_IS_ERR(t) != honest); + if (RAY_IS_ERR(t)) ray_error_free(t); else ray_release(t); + TEST_ASSERT_TRUE((access(dir, F_OK) == 0) == honest); + pq_remove_native(dir, names, 1); pq_remove_native(partial, names, 1); + } + } + ray_release(types); unlink(src); + PASS(); +} +/* Imports keep no memory after they end: the per-worker buffers the tasks + * share (pages, dictionaries, symbol scratch) and each pass's state are + * freed, direct and grouped. One worker, so the calling thread's heap holds + * it all; eight imports, the bytes allocated after the second and the last. */ +static test_result_t test_pq_import_no_growth(void) { + pq_sym_env_clear(); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + 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); + const char* names[] = {"x","y","s"}; + for (int grouped = 0; grouped < 2; grouped++) { + size_t base = 0; + for (int i = 0; i < 8; i++) { + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-growth-%d-%d-%d", (int)getpid(), grouped, i); + pq_set_symmode(grouped ? "grouped" : "direct"); + ray_t* res = ray_parquet_splayed_typed(FIX "row-groups.parquet", dir, types); + pq_set_symmode(NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(res)); ray_release(res); + pq_remove_native(dir, names, 3); + ray_mem_stats_t st; + ray_mem_stats(&st); + if (i == 1) base = st.bytes_allocated; + if (i == 7) TEST_ASSERT_TRUE(st.bytes_allocated <= base + (64u << 10)); + } + } + ray_release(types); + ray_pool_destroy(); + PASS(); +} +/* Edge inputs for the grouped import, each against the direct import of the + * same file: strings past the 1 MB record buffer, a 4 MB read piece and the + * 32 MB read-ahead (equal prefixes, told apart by their last bytes), a + * string a later row group meets again only in the last one, row groups of + * no rows, every string unique, every string the same; in every order, one + * worker and four, one window or a window per row group, all of the hash or + * none of it. Every row's string, the vocabulary's size (no string lost + * or twice), the null flag, and the files byte for byte across the worker + * counts. The default run is a subset (PQ_EDGE_FULL=1 runs all of it, + * PQ_EDGE_ONLY=name one set, the PQ_EDGE_* knobs below change the runs). */ +static char* pq_big; +static const char* pq_big_row(uint32_t len, char fill, int64_t key, uint32_t* out) { + memset(pq_big, fill, len); + char tail[24]; int n = snprintf(tail, sizeof(tail), "#%lld", (long long)key); + if ((uint32_t)n <= len) memcpy(pq_big + len - (uint32_t)n, tail, (size_t)n); + *out = len; + return pq_big; +} +static const char* pq_synth_huge(int64_t r, char* buf, uint32_t* len) { + switch (r % 8) { + case 0: return NULL; + case 1: *len = 0; return buf; + case 2: return pq_big_row((1u << 20) - 4, 'b', (r / 8) % 2, len); /* the 1 MB buffer exactly */ + case 3: return pq_big_row((1u << 20) - 3, 'b', (r / 8) % 3, len); /* a byte past it */ + case 4: return pq_big_row((4u << 20) + 7, 'c', (r / 8) % 2, len); /* past a 4 MB piece */ + case 5: *len = (uint32_t)snprintf(buf, 256, "k%lld", (long long)(r % 3)); return buf; + case 6: return pq_big_row(300000, 'd', r % 5, len); + default: return r == 15 ? pq_big_row(33u << 20, 'e', 7, len) /* past the 32 MB read-ahead */ + : pq_big_row((2u << 20) + 1, 'e', (r / 8) % 2, len); + } +} +/* 4000 rows in 8 row groups of 500: forty strings of the first group met + * again only in the last, ten of the fourth met again only in the last, + * the rest unique. */ +static const char* pq_synth_last(int64_t r, char* buf, uint32_t* len) { + int64_t g = (r % 4000) / 500; + int n; + if ((g == 0 || g == 7) && r % 5 == 0) n = snprintf(buf, 256, "again-%lld", (long long)((r / 5) % 40)); + else if ((g == 3 || g == 7) && r % 7 == 1) n = snprintf(buf, 256, "mid-%lld", (long long)((r / 7) % 10)); + else if (r % 97 == 0) return NULL; + else n = snprintf(buf, 256, "u%06lld", (long long)r); + *len = (uint32_t)n; + return buf; +} +static const char* pq_synth_same(int64_t r, char* buf, uint32_t* len) { + (void)r; + *len = (uint32_t)snprintf(buf, 256, "one and the same string"); + return buf; +} +/* pq_synth_check, telling the first row that differs. */ +static bool pq_edge_check(const char* dir, int64_t rows, pq_synth_fn fn, const char* what, int nulls[2]) { + char sym[200]; snprintf(sym, sizeof(sym), "%s/.sym", dir); + ray_t* t = ray_read_splayed(dir, sym); + if (!t || RAY_IS_ERR(t)) { fprintf(stderr, " [%s] read failed\n", what); if (t) ray_error_free(t); return false; } + bool ok = ray_table_nrows(t) == rows; + if (!ok) fprintf(stderr, " [%s] rows %lld != %lld\n", what, (long long)ray_table_nrows(t), (long long)rows); + char buf[256]; + for (int c = 1; ok && c < PQ_SYNTH_COLS; c++) { + ray_t* s = ray_table_get_col_idx(t, c); + if (nulls) nulls[c - 1] = (s->attrs & RAY_ATTR_HAS_NULLS) != 0; + for (int64_t r = 0; ok && r < rows; r++) { + uint32_t len = 0; + const char* want = pq_synth_row(fn, c, r, rows, buf, &len); + if (!want) len = 0; + ray_t* text = ray_sym_vec_cell(s, r); + ok = text && ray_str_len(text) == len && (!len || !memcmp(ray_str_ptr(text), want, len)); + if (!ok) fprintf(stderr, " [%s] col %d row %lld: want len %u, got len %lld pos %lld\n", what, c, (long long)r, + len, text ? (long long)ray_str_len(text) : -1LL, + (long long)ray_read_sym(ray_data(s), r, RAY_SYM, s->attrs)); + } + } + ray_release(t); + return ok; +} +typedef struct { const char* name; pq_synth_fn fn; int64_t rows, groups; bool big, opt; } pq_edge_set; +static test_result_t test_pq_sym_grouped_edges(void) { +#if !defined(DEBUG) + SKIP("window and hash knobs are debug-build only"); +#else + pq_sym_env_clear(); + pq_big = (char*)ray_sys_alloc((size_t)34 << 20); + TEST_ASSERT_TRUE(pq_big != NULL); + const pq_edge_set sets[] = { + {"huge", pq_synth_huge, 24, 6, true, false}, + {"last", pq_synth_last, 4000, 8, false, false}, + {"zero", pq_synth_mixed, 7, 10, false, false}, + {"unique", pq_synth_long, 3000, 6, false, false}, + {"same", pq_synth_same, 3000, 5, false, false}, + {"zipf", pq_synth_zipf, 24000, 12, false, true}, + {"mixed", pq_synth_mixed, 20000, 9, false, true}, + }; + const char* e_arena = getenv("PQ_EDGE_ARENA"); + const char* e_bits = getenv("PQ_EDGE_BITS"); + const char* e_groups = getenv("PQ_EDGE_GROUPS"); + const char* e_window = getenv("PQ_EDGE_WINDOW"); + int e_cores = getenv("PQ_EDGE_CORES") ? atoi(getenv("PQ_EDGE_CORES")) : 4; + bool full = getenv("PQ_EDGE_FULL") != NULL; + const char* orders[] = {"rows","shards","freq","rowsflat"}; + const char* names[] = {"x","s","t"}; + int64_t tids[] = {ray_sym_intern("I32",3), ray_sym_intern("SYM",3), ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + char src[160], dir[160], ref[160], a[220], b[220], what[160]; + int fails = 0; + const char* only = getenv("PQ_EDGE_ONLY"); + for (size_t si = 0; si < sizeof(sets) / sizeof(sets[0]); si++) { + const pq_edge_set* S = &sets[si]; + if (only ? strcmp(only, S->name) != 0 : S->opt) continue; /* zipf, mixed: by name only (the other tests cover them) */ + snprintf(src, sizeof(src), "/tmp/rayforce-pq-edge-%d-%s.parquet", (int)getpid(), S->name); + TEST_ASSERT_TRUE(pq_synth(src, S->rows, S->groups, S->fn)); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-edge-%d", (int)getpid()); + TEST_ASSERT_EQ_I(pq_pool(4), RAY_OK); + pq_set_symmode("direct"); + ray_t* res = ray_parquet_splayed_typed(src, dir, types); + pq_set_symmode(NULL); + if (!res || RAY_IS_ERR(res)) { + fprintf(stderr, " [%s direct] import failed: %s\n", S->name, res ? ray_err_code(res) : "null"); + if (res) ray_error_free(res); + fails++; unlink(src); continue; + } + ray_release(res); + int dn[2] = {0, 0}; + snprintf(what, sizeof(what), "%s direct", S->name); + if (!pq_edge_check(dir, S->rows, S->fn, what, dn)) fails++; + int64_t words = pq_sym_count(dir); + pq_remove_native(dir, names, 3); + for (int o = 0; o < 4; o++) { + for (int run = 0; run < 8; run++) { + int cores = run & 1 ? e_cores : 1; + const char* window = run & 2 ? (e_window ? e_window : "1") : NULL; + const char* bits = run & 4 ? (e_bits ? e_bits : "0") : NULL; + /* the default run: the big records in "rows" only and all of the + * hash; the truncated hash (every candidate a collision, slow + * under the sanitizers) in "rows" with one window. PQ_EDGE_FULL=1: every + * order with every knob, the big records' collisions in "rows" */ + if (S->big && (full ? bits && o != 0 : bits || o != 0)) continue; + if (!full && bits && (o != 0 || window)) continue; + snprintf(what, sizeof(what), "%s %s cores=%d window=%s bits=%s", S->name, orders[o], cores, + window ? window : "-", bits ? bits : "-"); + TEST_ASSERT_EQ_I(pq_pool(cores), RAY_OK); + snprintf(ref, sizeof(ref), "/tmp/rayforce-pq-edge-%d-ref-%d", (int)getpid(), run & 6); + const char* out = cores == 1 ? ref : dir; + pq_set_symmode("grouped"); + pq_set_env("RAY_PQ_SYM_ORDER", orders[o]); + pq_set_env("RAY_PQ_SYM_WINDOW", window); + pq_set_env("RAY_PQ_SYM_HASH_BITS", bits); + pq_set_env("RAY_PQ_SYM_ARENA", e_arena); + pq_set_env("RAY_PQ_SYM_GROUPS", e_groups); + res = ray_parquet_splayed_typed(src, out, types); + pq_sym_env_clear(); + if (!res || RAY_IS_ERR(res)) { + fprintf(stderr, " [%s] import failed: %s\n", what, res ? ray_err_code(res) : "null"); + if (res) ray_error_free(res); + char partial[240]; snprintf(partial, sizeof(partial), "%s.parquet-partial", out); + pq_remove_native(partial, names, 3); + fails++; continue; + } + TEST_ASSERT_EQ_I(res->i64, S->rows); ray_release(res); + int gn[2] = {0, 0}; + if (!pq_edge_check(out, S->rows, S->fn, what, gn)) fails++; + if (pq_sym_count(out) != words) { + fprintf(stderr, " [%s] symbols %lld, direct %lld\n", what, (long long)pq_sym_count(out), (long long)words); + fails++; + } + if (gn[0] != dn[0] || gn[1] != dn[1]) { + fprintf(stderr, " [%s] null flags %d/%d, direct %d/%d\n", what, gn[0], gn[1], dn[0], dn[1]); + fails++; + } + if (cores > 1) { + bool same = true; + snprintf(a, sizeof(a), "%s/.sym", ref); snprintf(b, sizeof(b), "%s/.sym", dir); + same = pq_same_file(a, b); + for (int c = 1; c < 3; c++) { + snprintf(a, sizeof(a), "%s/%s", ref, names[c]); snprintf(b, sizeof(b), "%s/%s", dir, names[c]); + if (!pq_same_file(a, b)) same = false; + } + if (!same) { fprintf(stderr, " [%s] files differ from one worker's\n", what); fails++; } + pq_remove_native(dir, names, 3); + pq_remove_native(ref, names, 3); + } + } + } + unlink(src); + } + ray_pool_destroy(); + ray_sys_free(pq_big); pq_big = NULL; + ray_release(types); + TEST_ASSERT_EQ_I(fails, 0); + PASS(); +#endif +} +/* A file of many small row groups (4000 of 2 rows; PQ_RG_GROUPS), grouped + * (or direct by PQ_RG_MODE): the grouped pass's staged arrays and its + * workers' dedupe arenas cost memory by the rows, not a few pages a row + * group or the generation limit (their bytes from the trace). It prints + * the process's committed-memory peak too, for the modes compared in + * separate processes. */ +static test_result_t test_pq_sym_grouped_rowgroups(void) { + pq_sym_env_clear(); + const char* mode = getenv("PQ_RG_MODE"); + int64_t groups = getenv("PQ_RG_GROUPS") ? atoll(getenv("PQ_RG_GROUPS")) : 4000; + int64_t rows = groups * 2; + char src[160], dir[160]; + snprintf(src, sizeof(src), "/tmp/rayforce-pq-rg-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-rg-%d", (int)getpid()); + TEST_ASSERT_TRUE(pq_synth(src, rows, groups, pq_synth_mixed)); + int64_t tids[] = {ray_sym_intern("I32",3), ray_sym_intern("SYM",3), ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + const char* names[] = {"x","s","t"}; + TEST_ASSERT_EQ_I(pq_pool(4), RAY_OK); + ray_mem_stats_t st0, st1; + ray_mem_stats(&st0); + pq_set_symmode(mode ? mode : "grouped"); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + ray_t* res = pq_traced_import(src, dir, types, trace, cap); + pq_set_symmode(NULL); + ray_mem_stats(&st1); + bool failed = !res || RAY_IS_ERR(res); + if (failed) fprintf(stderr, " rowgroups: import failed: %s\n", res ? ray_err_code(res) : "null"); + if (res) { if (failed) ray_error_free(res); else ray_release(res); } + int passes = 0; + double stage = pq_trace_sum(trace, "stage_mb", &passes); + double arena = pq_trace_sum(trace, "arena_mb", NULL); + ray_sys_free(trace); + long hwm = -1; + FILE* f = fopen("/proc/self/status", "r"); + if (f) { char line[256]; while (fgets(line, sizeof(line), f)) if (!strncmp(line, "VmHWM:", 6)) hwm = atol(line + 6); fclose(f); } + fprintf(stderr, " rowgroups: mode=%s groups=%lld stage=%.1fMB arenas=%.1fMB in %d passes sys_peak=%.1fMB (before %.1fMB) VmHWM=%ldkB\n", + mode ? mode : "grouped", (long long)groups, stage, arena, passes, (double)st1.sys_peak / 1048576.0, + (double)st0.sys_peak / 1048576.0, hwm); + TEST_ASSERT_FALSE(failed); + TEST_ASSERT_TRUE(pq_synth_check(dir, rows, pq_synth_mixed)); + if (!mode || !strcmp(mode, "grouped")) { + TEST_ASSERT_EQ_I(passes, 2); + TEST_ASSERT_TRUE(stage <= 2.0 * passes * (double)(groups > 4000 ? groups / 4000 : 1)); + TEST_ASSERT_TRUE(arena <= 1.0 * passes); /* four workers, their arenas grown to the chunks' bytes */ + } + pq_remove_native(dir, names, 3); + ray_pool_destroy(); + ray_release(types); unlink(src); + PASS(); +} +/* The grouped import's failures keep no memory: each injected failure run + * five times on one worker, the heap's and the system allocator's bytes + * after the second run and after the last. */ +static test_result_t test_pq_sym_grouped_fail_leaks(void) { +#if !defined(DEBUG) + SKIP("failure injection is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160], partial[200]; + snprintf(src, sizeof(src), "/tmp/rayforce-pq-fleak-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-fleak-%d", (int)getpid()); + snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + TEST_ASSERT_TRUE(pq_synth(src, 20000, 9, pq_synth_mixed)); + int64_t tids[] = {ray_sym_intern("I32",3), ray_sym_intern("SYM",3), ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + const char* names[] = {"x","s","t"}; + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + const char* steps[] = {"r1","p2","load","reload","r2","write","settle","cancel",NULL}; + int bad = 0; + for (int i = 0; i < 9; i++) { + size_t base = 0, sbase = 0; + for (int k = 0; k < 5; k++) { + pq_set_symmode("grouped"); + pq_set_env("RAY_PQ_SYM_WINDOW", "4096"); + pq_set_env("RAY_PQ_SYM_HASH_BITS", "6"); + pq_set_env("RAY_PQ_SYM_INJECT", steps[i]); + ray_t* res = ray_parquet_splayed_typed(src, dir, types); + pq_sym_env_clear(); + bool failed = res && RAY_IS_ERR(res); + if (res) { if (failed) ray_error_free(res); else ray_release(res); } + ray_clear_interrupt(); + if (failed != (steps[i] != NULL)) bad++; + pq_remove_native(partial, names, 3); + pq_remove_native(dir, names, 3); + ray_mem_stats_t st; ray_mem_stats(&st); + if (k == 1) { base = st.bytes_allocated; sbase = st.sys_current; } + if (k == 4) { + fprintf(stderr, " fail_leaks %-6s heap %+lld B sys %+lld B\n", steps[i] ? steps[i] : "none", + (long long)st.bytes_allocated - (long long)base, (long long)st.sys_current - (long long)sbase); + /* a window's copy left behind is a few pages a run, the + * row groups' errors past the first a few hundred bytes */ + if (st.bytes_allocated > base + 512 || st.sys_current > sbase + (8u << 10)) bad++; + } + } + } + ray_pool_destroy(); + ray_release(types); unlink(src); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* A cancelled import reports "cancel" whichever symbol import runs, the + * interrupt seen in the first decode of the grouped one as well. */ +static test_result_t test_pq_sym_grouped_cancel_code(void) { + pq_sym_env_clear(); + char src[160], dir[160], partial[200]; + snprintf(src, sizeof(src), "/tmp/rayforce-pq-ccode-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-ccode-%d", (int)getpid()); + snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + TEST_ASSERT_TRUE(pq_dict_file(src, 4 + 5 + 4 + 19, 2)); + int64_t tid = ray_sym_intern("SYM", 3); + ray_t* types = ray_vec_from_raw(RAY_SYM, &tid, 1); + const char* names[] = {"s"}; + char codes[2][32]; + for (int grouped = 0; grouped < 2; grouped++) { + pq_set_symmode(grouped ? "grouped" : "direct"); + ray_request_interrupt(); + ray_t* res = ray_parquet_splayed_typed(src, dir, types); + ray_clear_interrupt(); + pq_set_symmode(NULL); + snprintf(codes[grouped], sizeof(codes[grouped]), "%s", res && RAY_IS_ERR(res) ? ray_err_code(res) : "ok"); + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + pq_remove_native(dir, names, 1); pq_remove_native(partial, names, 1); + } + fprintf(stderr, " cancel codes: direct=%s grouped=%s\n", codes[0], codes[1]); + ray_release(types); unlink(src); + TEST_ASSERT_TRUE(!strcmp(codes[0], "cancel")); + TEST_ASSERT_TRUE(!strcmp(codes[1], "cancel")); + PASS(); +} +/* Hash collisions resolved in parallel: with none of the hash's bits kept + * every candidate of one length collides, and the records the collisions + * add must not take positions in the order the workers reach them. The + * symbol file and the columns are the same bytes on one worker, two, four + * and eight, run after run, in one window (candidates of other tasks + * deferred) and in a window a task (compared at once), and in another + * order of new positions. */ +static test_result_t test_pq_sym_grouped_collision_determinism(void) { +#if !defined(DEBUG) + SKIP("hash truncation is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[2][160], a[220], b[220]; + snprintf(src, sizeof(src), "/tmp/rayforce-pq-cdet-%d.parquet", (int)getpid()); + TEST_ASSERT_TRUE(pq_synth(src, 3000, 4, pq_synth_mixed)); + int64_t tids[] = {ray_sym_intern("I32",3), ray_sym_intern("SYM",3), ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + const char* names[] = {"x","s","t"}; + static const int cores[] = {1, 2, 4, 8, 4, 8}; + const int nruns = (int)(sizeof(cores) / sizeof(cores[0])); + int differ = 0; + for (int v = 0; v < 3; v++) { + for (int i = 0; i < nruns; i++) { + if (v && i && i != 3) continue; /* the other variants: one worker and eight */ + int d = i ? 1 : 0; + snprintf(dir[d], sizeof(dir[d]), "/tmp/rayforce-pq-cdet-%d-%d", (int)getpid(), d); + TEST_ASSERT_EQ_I(pq_pool(cores[i]), RAY_OK); + pq_set_symmode("grouped"); + pq_set_env("RAY_PQ_SYM_ORDER", v == 2 ? "shards" : "rows"); + pq_set_env("RAY_PQ_SYM_WINDOW", v == 1 ? "1" : NULL); + pq_set_env("RAY_PQ_SYM_HASH_BITS", "0"); + ray_t* res = ray_parquet_splayed_typed(src, dir[d], types); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + TEST_ASSERT_TRUE(pq_synth_check(dir[d], 3000, pq_synth_mixed)); + if (!i) continue; + bool same = true; + snprintf(a, sizeof(a), "%s/.sym", dir[0]); snprintf(b, sizeof(b), "%s/.sym", dir[1]); + if (!pq_same_file(a, b)) same = false; + for (int c = 1; c < 3; c++) { + snprintf(a, sizeof(a), "%s/%s", dir[0], names[c]); snprintf(b, sizeof(b), "%s/%s", dir[1], names[c]); + if (!pq_same_file(a, b)) same = false; + } + if (!same) { fprintf(stderr, " variant %d, %d workers: files differ from one worker's\n", v, cores[i]); differ++; } + pq_remove_native(dir[1], names, 3); + } + pq_remove_native(dir[0], names, 3); + } + ray_pool_destroy(); + ray_release(types); unlink(src); + TEST_ASSERT_EQ_I(differ, 0); + PASS(); +#endif +} +/* ---- several symbol columns of their own make (pqx_synth) ----------------- + * x, a required INT32 (the row), then n optional BYTE_ARRAY (UTF8) columns, + * each from its own function of the row and with its own pages: PQX_DICT a + * dictionary page of the chunk's distinct strings and RLE ids; PQX_FALLBACK + * the dictionary for the first half of the chunk's rows only and a PLAIN + * page for the rest (a writer's fallback); PQX_SNAPPY every page of the + * column snappy-compressed (a greedy LZ over 2-byte offsets). */ +enum { PQX_DICT = 1, PQX_FALLBACK = 2, PQX_SNAPPY = 4, PQX_LATE = 8, PQX_NOSTATS = 16, + PQX_LIESTATS = 32, PQX_ZSTD = 64, PQX_HUGERAW = 128, PQX_ZERORAW = 256, PQX_BADDICT = 512, + PQX_FARDATA = 1024, PQX_INDICT = 2048, PQX_CRC = 4096, PQX_CRCFLIP = 8192 }; /* PQX_ZERORAW: total_uncompressed_size 0; PQX_BADDICT: the dictionary page encoded 3 */ + /* PQX_CRC: page checksums; PQX_CRCFLIP: and the last row group's dictionary + * page with a byte flipped past its checksum (pqx_page, pqx_crc) */ + /* PQX_FARDATA: data_page_offset past the file's data; PQX_INDICT: + * data_page_offset one byte into the dictionary page (skeptic round 4: + * the decoder reads a chunk from its dictionary page for + * total_compressed_size bytes and never uses it) */ + /* PQX_LATE: the fallback after 7/8 of the rows; PQX_NOSTATS: no encoding stats; + * PQX_LIESTATS: stats that leave out the PLAIN pages; PQX_ZSTD: codec 6 in the + * footer (pages stored as written); PQX_HUGERAW: total_uncompressed_size + * INT64_MAX - 4096 in the footer (the pages as written) */ +static int64_t pqx_rows = 1, pqx_groups = 1; /* the file the functions describe */ +/* pqx_empty >= 0: that row group has no rows (the others share them), its + * chunks written as pyarrow writes a zero-row group's: a dictionary + * column's an empty dictionary page and data_page_offset 0 */ +static int64_t pqx_empty = -1; +static int64_t pqx_lo(int64_t rows, int64_t groups, int64_t g) { + if (pqx_empty < 0 || groups < 2) return rows * g / groups; + return rows * (g > pqx_empty ? g - 1 : g) / (groups - 1); +} +static void pqx_lit(pq_buf* o, const uint8_t* p, size_t n) { + while (n) { + size_t k = n < 65536 ? n : 65536; + if (k <= 60) pb_byte(o, (uint8_t)((k - 1) << 2)); + else if (k <= 256) { pb_byte(o, 60 << 2); pb_byte(o, (uint8_t)(k - 1)); } + else { pb_byte(o, 61 << 2); uint16_t x = (uint16_t)(k - 1); pb_bytes(o, &x, 2); } + pb_bytes(o, p, k); p += k; n -= k; + } +} +static void pqx_snappy(pq_buf* o, const uint8_t* s, size_t n) { + pb_var(o, n); + int32_t tab[4096]; + for (int i = 0; i < 4096; i++) tab[i] = -1; + size_t lit = 0, i = 0; + while (i + 4 <= n) { + uint32_t v; memcpy(&v, s + i, 4); + uint32_t h = (v * 2654435761u) >> 20; + int32_t c = tab[h]; tab[h] = (int32_t)i; + if (c >= 0 && i - (size_t)c <= 65535 && !memcmp(s + c, s + i, 4)) { + pqx_lit(o, s + lit, i - lit); + size_t len = 4; + while (len < 64 && i + len < n && s[(size_t)c + len] == s[i + len]) len++; + pb_byte(o, (uint8_t)(((len - 1) << 2) | 2)); + uint16_t off = (uint16_t)(i - (size_t)c); pb_bytes(o, &off, 2); + i += len; lit = i; + } else i++; + } + pqx_lit(o, s + lit, n - lit); +} +/* pqx_page's checksums (PQX_CRC, PQX_CRCFLIP): 0 none; 1 each page's + * CRC-32 in its header (PageHeader 4); 2 that, and a dictionary page's + * first string has one byte flipped after its checksum was taken (a page + * gone bad on disk), the string it then reads kept in pqx_flipped; 3 that, + * and a data page's last byte flipped so. pqx_xflip: the x column's pages, + * -2 (the default) without checksums, -1 with them, g >= 0 with them and + * row group g's flipped. pqx_pfault[g]: what goes wrong in row group g of + * the first symbol column (PQX_PF_CRCFLIP its dictionary page flipped past + * its checksum, the column written PQX_CRC; PQX_PF_BADDICT its dictionary + * page encoded 3), two of them in different row groups for the order the + * import reports them in. */ +enum { PQX_PF_CRCFLIP = 1, PQX_PF_BADDICT = 2 }; +static int64_t pqx_xflip = -2; +static unsigned pqx_pfault[16]; +static int pqx_crc = 0; +static char pqx_flipped[256]; +static uint32_t pqx_flipped_len = 0; +/* A page (kind 0 a v1 data page, 2 the dictionary): header and payload, + * compressed when snappy; *raw adds what total_uncompressed_size counts. */ +static void pqx_page(pq_buf* f, int kind, const pq_buf* body, int64_t count, int enc, bool snappy, int64_t* raw) { + pq_buf z = {0}; + const pq_buf* pay = body; + if (snappy) { pqx_snappy(&z, body->p, body->n); pay = &z; if (z.bad) f->bad = true; } + size_t h0 = f->n; + int last = 0; + pb_i(f, &last, 1, PB_I32, kind); + pb_i(f, &last, 2, PB_I32, (int64_t)body->n); + pb_i(f, &last, 3, PB_I32, (int64_t)pay->n); + if (pqx_crc) pb_i(f, &last, 4, PB_I32, (int32_t)ray_crc32(0, pay->p, pay->n)); + int l = 0; + if (kind == 2) { + pb_field(f, &last, 7, PB_STRUCT); + pb_i(f, &l, 1, PB_I32, count); pb_i(f, &l, 2, PB_I32, enc); pb_byte(f, 0); + } else { + pb_field(f, &last, 5, PB_STRUCT); + pb_i(f, &l, 1, PB_I32, count); pb_i(f, &l, 2, PB_I32, enc); + pb_i(f, &l, 3, PB_I32, 3); pb_i(f, &l, 4, PB_I32, 3); pb_byte(f, 0); + } + pb_byte(f, 0); + *raw += (int64_t)(f->n - h0) + (int64_t)body->n; + size_t at = f->n; + pb_bytes(f, pay->p, pay->n); + if (pqx_crc == 3 && kind == 0 && pay->n > 0 && !f->bad) f->p[at + pay->n - 1] ^= 0x20; + if (pqx_crc == 2 && kind == 2 && !snappy && pay->n > 5 && !f->bad) { + uint32_t len; memcpy(&len, pay->p, 4); + if (len > 0 && len < sizeof(pqx_flipped) && 4 + (size_t)len <= pay->n) { + f->p[at + 4] ^= 0x20; /* the first string's first byte, its case flipped */ + memcpy(pqx_flipped, f->p + at + 4, len); pqx_flipped_len = len; + } + } + ray_sys_free(z.p); +} +static uint32_t pqx_dict_id(const pq_buf* dict, const pq_buf* doff, const char* s, uint32_t len) { + uint32_t nd = (uint32_t)(doff->n / 4), id = 0; + for (; id < nd; id++) { + uint32_t o; memcpy(&o, doff->p + id * 4, 4); + uint32_t l; memcpy(&l, dict->p + o, 4); + if (l == len && !memcmp(dict->p + o + 4, s, len)) break; + } + return id; +} +static bool pqx_synth(const char* path, int64_t rows, int64_t groups, int n, const char* const* names, + const pq_synth_fn* fns, const unsigned* flags) { + pq_buf f = {0}; + int64_t nc = n + 1, cells = groups * nc; + int64_t* start = (int64_t*)ray_sys_alloc((size_t)cells * sizeof(int64_t)); + int64_t* dpo = (int64_t*)ray_sys_alloc((size_t)cells * sizeof(int64_t)); + int64_t* dio = (int64_t*)ray_sys_alloc((size_t)cells * sizeof(int64_t)); + int64_t* stored = (int64_t*)ray_sys_alloc((size_t)cells * sizeof(int64_t)); + int64_t* rawt = (int64_t*)ray_sys_alloc((size_t)cells * sizeof(int64_t)); + if (!start || !dpo || !dio || !stored || !rawt) return false; + pqx_rows = rows; pqx_groups = groups; + pb_bytes(&f, "PAR1", 4); + char buf[256]; + for (int64_t g = 0; g < groups; g++) { + int64_t lo = pqx_lo(rows, groups, g), hi = pqx_lo(rows, groups, g + 1); + for (int64_t c = 0; c < nc; c++) { + int64_t i = g * nc + c; + start[i] = (int64_t)f.n; rawt[i] = 0; dio[i] = -1; + pqx_crc = 0; + if (c == 0) { + pq_buf v = {0}; + for (int64_t r = lo; r < hi; r++) { int32_t x = (int32_t)r; pb_bytes(&v, &x, 4); } + dpo[i] = (int64_t)f.n; + pqx_crc = pqx_xflip == -2 ? 0 : pqx_xflip == g ? 3 : 1; + pqx_page(&f, 0, &v, hi - lo, 0, false, &rawt[i]); + if (v.bad) f.bad = true; + ray_sys_free(v.p); + stored[i] = (int64_t)f.n - start[i]; + continue; + } + unsigned fl = flags[c - 1]; + unsigned pf = c == 1 && g < 16 ? pqx_pfault[g] : 0; + pqx_crc = !(fl & PQX_CRC) ? 0 : ((fl & PQX_CRCFLIP) && g == groups - 1) || (pf & PQX_PF_CRCFLIP) ? 2 : 1; + bool snappy = (fl & PQX_SNAPPY) != 0, dicted = (fl & (PQX_DICT | PQX_FALLBACK)) != 0; + pq_synth_fn fn = fns[c - 1]; + int64_t mid = !dicted ? lo : (fl & PQX_FALLBACK) && hi - lo >= 2 ? lo + (hi - lo) * ((fl & PQX_LATE) ? 7 : 4) / 8 : hi; + pq_buf dict = {0}, doff = {0}; + if (dicted) { + for (int64_t r = lo; r < mid; r++) { + uint32_t len = 0; + const char* s = fn(r, buf, &len); + if (!s || pqx_dict_id(&dict, &doff, s, len) < doff.n / 4) continue; + uint32_t o = (uint32_t)dict.n; pb_bytes(&doff, &o, 4); pb_bytes(&dict, &len, 4); pb_bytes(&dict, s, len); + } + dio[i] = (int64_t)f.n; + pqx_page(&f, 2, &dict, (int64_t)(doff.n / 4), (fl & PQX_BADDICT) || (pf & PQX_PF_BADDICT) ? 3 : 0, snappy, &rawt[i]); + } + dpo[i] = (int64_t)f.n; + for (int part = 0; part < 2; part++) { + int64_t a = part ? mid : lo, b = part ? hi : mid; + if (b <= a) continue; + bool ids = part == 0; + pq_buf levels = {0}, values = {0}, body = {0}; + int64_t n8 = (b - a + 7) / 8; + uint8_t bits = 0; + pb_var(&levels, (uint64_t)(n8 * 2 + 1)); + uint32_t nd = (uint32_t)(doff.n / 4), bw = 1; + while (bw < 32 && ((uint64_t)1 << bw) < nd) bw++; + if (ids) pb_byte(&values, (uint8_t)bw); + for (int64_t r = a; r < a + n8 * 8; r++) { + uint32_t len = 0; + const char* s = r < b ? fn(r, buf, &len) : NULL; + if (s) { + bits |= (uint8_t)(1u << ((r - a) & 7)); + if (!ids) { pb_bytes(&values, &len, 4); pb_bytes(&values, s, len); } + else { + uint32_t id = pqx_dict_id(&dict, &doff, s, len); + pb_var(&values, 2); pb_bytes(&values, &id, (bw + 7) / 8); + } + } + if (((r - a) & 7) == 7) { pb_byte(&levels, bits); bits = 0; } + } + uint32_t ln = (uint32_t)levels.n; + pb_bytes(&body, &ln, 4); pb_bytes(&body, levels.p, levels.n); pb_bytes(&body, values.p, values.n); + if (levels.bad || values.bad || body.bad) f.bad = true; + pqx_page(&f, 0, &body, b - a, ids ? 8 : 0, snappy, &rawt[i]); + ray_sys_free(levels.p); ray_sys_free(values.p); ray_sys_free(body.p); + } + if (g == pqx_empty && dicted) dpo[i] = 0; /* no data page: pyarrow writes offset 0 */ + if (dict.bad || doff.bad) f.bad = true; + ray_sys_free(dict.p); ray_sys_free(doff.p); + stored[i] = (int64_t)f.n - start[i]; + } + } + pqx_crc = 0; + int64_t footer = (int64_t)f.n; + int last = 0; + pb_i(&f, &last, 1, PB_I32, 1); + pb_field(&f, &last, 2, PB_LIST); pb_list(&f, (int)nc + 1, PB_STRUCT); + { int l = 0; pb_i(&f, &l, 3, PB_I32, 0); pb_field(&f, &l, 4, PB_BIN); pb_bin(&f, "schema", 6); pb_i(&f, &l, 5, PB_I32, nc); pb_byte(&f, 0); } + { int l = 0; pb_i(&f, &l, 1, PB_I32, 1); pb_i(&f, &l, 3, PB_I32, 0); pb_field(&f, &l, 4, PB_BIN); pb_bin(&f, "x", 1); pb_byte(&f, 0); } + for (int c = 0; c < n; c++) { + int l = 0; + pb_i(&f, &l, 1, PB_I32, 6); pb_i(&f, &l, 3, PB_I32, 1); + pb_field(&f, &l, 4, PB_BIN); pb_bin(&f, names[c], strlen(names[c])); pb_i(&f, &l, 6, PB_I32, 0); pb_byte(&f, 0); + } + pb_i(&f, &last, 3, PB_I64, rows); + pb_field(&f, &last, 4, PB_LIST); pb_list(&f, (int)groups, PB_STRUCT); + for (int64_t g = 0; g < groups; g++) { + int64_t cnt = pqx_lo(rows, groups, g + 1) - pqx_lo(rows, groups, g), total = 0; + int l = 0; + pb_field(&f, &l, 1, PB_LIST); pb_list(&f, (int)nc, PB_STRUCT); + for (int64_t c = 0; c < nc; c++) { + int64_t i = g * nc + c; + const char* nm = c ? names[c - 1] : "x"; + int lc = 0, lm = 0; + pb_i(&f, &lc, 2, PB_I64, start[i]); + pb_field(&f, &lc, 3, PB_STRUCT); + pb_i(&f, &lm, 1, PB_I32, c ? 6 : 1); + if (dio[i] >= 0) { pb_field(&f, &lm, 2, PB_LIST); pb_list(&f, 3, PB_I32); pb_zz(&f, 0); pb_zz(&f, 3); pb_zz(&f, 8); } + else { pb_field(&f, &lm, 2, PB_LIST); pb_list(&f, 2, PB_I32); pb_zz(&f, 0); pb_zz(&f, 3); } + pb_field(&f, &lm, 3, PB_LIST); pb_list(&f, 1, PB_BIN); pb_bin(&f, nm, strlen(nm)); + pb_i(&f, &lm, 4, PB_I32, c && (flags[c - 1] & PQX_ZSTD) ? 6 : c && (flags[c - 1] & PQX_SNAPPY) ? 1 : 0); + pb_i(&f, &lm, 5, PB_I64, cnt); + pb_i(&f, &lm, 6, PB_I64, c && (flags[c - 1] & PQX_HUGERAW) ? INT64_MAX - 4096 + : c && (flags[c - 1] & PQX_ZERORAW) ? 0 : rawt[i]); + pb_i(&f, &lm, 7, PB_I64, stored[i]); + pb_i(&f, &lm, 9, PB_I64, c && (flags[c - 1] & PQX_FARDATA) && dio[i] >= 0 ? footer + 4096 + : c && (flags[c - 1] & PQX_INDICT) && dio[i] >= 0 ? dio[i] + 1 : dpo[i]); + if (dio[i] >= 0) pb_i(&f, &lm, 11, PB_I64, dio[i]); + if (c && !(flags[c - 1] & PQX_NOSTATS)) + pb_enc_stats(&f, &lm, dio[i] >= 0, dio[i] >= 0, + (!(flags[c - 1] & PQX_DICT) || (flags[c - 1] & PQX_FALLBACK)) && !(flags[c - 1] & PQX_LIESTATS)); + pb_byte(&f, 0); + pb_byte(&f, 0); + total += stored[i]; + } + pb_i(&f, &l, 2, PB_I64, total); + pb_i(&f, &l, 3, PB_I64, cnt); + pb_byte(&f, 0); + } + pb_field(&f, &last, 6, PB_BIN); pb_bin(&f, "rayforce test", 13); + pb_byte(&f, 0); + uint32_t flen = (uint32_t)(f.n - (size_t)footer); + pb_bytes(&f, &flen, 4); pb_bytes(&f, "PAR1", 4); + bool ok = !f.bad; + FILE* out = ok ? fopen(path, "wb") : NULL; + ok = out && fwrite(f.p, 1, f.n, out) == f.n; + if (out && fclose(out)) ok = false; + ray_sys_free(f.p); + ray_sys_free(start); ray_sys_free(dpo); ray_sys_free(dio); ray_sys_free(stored); ray_sys_free(rawt); + return ok; +} +/* An import of a pqx_synth file: its columns in the file's order, x the + * row, every symbol row the function's string (a null and "" both the empty + * symbol), the first difference told; nulls[c] gets column c's null flag. */ +static bool pqx_check(const char* dir, int64_t rows, int n, const char* const* names, const pq_synth_fn* fns, + const char* what, int* nulls) { + char sym[200]; snprintf(sym, sizeof(sym), "%s/.sym", dir); + ray_t* t = ray_read_splayed(dir, sym); + if (!t || RAY_IS_ERR(t)) { fprintf(stderr, " [%s] read failed\n", what); if (t) ray_error_free(t); return false; } + bool ok = ray_table_nrows(t) == rows && ray_table_ncols(t) == n + 1; + if (!ok) fprintf(stderr, " [%s] shape %lldx%lld\n", what, (long long)ray_table_nrows(t), (long long)ray_table_ncols(t)); + for (int c = 0; ok && c <= n; c++) { + const char* nm = c ? names[c - 1] : "x"; + if (ray_table_col_name(t, c) != ray_sym_intern(nm, strlen(nm))) { fprintf(stderr, " [%s] column %d is not %s\n", what, c, nm); ok = false; } + } + for (int64_t r = 0; ok && r < rows; r++) + if (((int32_t*)ray_data(ray_table_get_col_idx(t, 0)))[r] != r) { fprintf(stderr, " [%s] x row %lld\n", what, (long long)r); ok = false; } + char buf[256]; + for (int c = 1; ok && c <= n; c++) { + ray_t* s = ray_table_get_col_idx(t, c); + if (nulls) nulls[c - 1] = (s->attrs & RAY_ATTR_HAS_NULLS) != 0; + for (int64_t r = 0; ok && r < rows; r++) { + uint32_t len = 0; + const char* want = fns[c - 1](r, buf, &len); + if (!want) len = 0; + ray_t* text = ray_sym_vec_cell(s, r); + ok = text && ray_str_len(text) == len && (!len || !memcmp(ray_str_ptr(text), want, len)); + if (!ok) fprintf(stderr, " [%s] col %s row %lld: want %.*s, got %.*s\n", what, names[c - 1], (long long)r, + (int)len, want ? want : "", text ? (int)ray_str_len(text) : 0, text ? ray_str_ptr(text) : ""); + } + } + ray_release(t); + return ok; +} +/* The columns of the mixed-column test: a low-cardinality one (dictionary, + * snappy, long strings of one prefix), a high-cardinality one (PLAIN) that + * repeats the first's every fifth row, one whose writer fell back to PLAIN + * mid-chunk and that repeats the second's strings (unique ones too), a hot + * key whose dictionary grows row group by row group and that meets the + * first's strings, and long unique strings snappy compresses well; nulls + * and "" in several. */ +static const char* pqx_lowcard(int64_t r, char* buf, uint32_t* len) { + if (r % 31 == 0) return NULL; + if (r % 37 == 0) { *len = 0; return buf; } + *len = (uint32_t)snprintf(buf, 256, "k%02lld-one-prefix-for-the-compressor", (long long)((r * 7) % 40)); + return buf; +} +static const char* pqx_highcard(int64_t r, char* buf, uint32_t* len) { + if (r % 5 == 0) return pqx_lowcard(r + 1, buf, len); + if (r % 41 == 0) { *len = 0; return buf; } + if (r % 43 == 0) return NULL; + *len = (uint32_t)snprintf(buf, 256, "u%06lld-high", (long long)r); + return buf; +} +static const char* pqx_fallback(int64_t r, char* buf, uint32_t* len) { + if (r % 4 == 0) return pqx_highcard(r + 7, buf, len); + if (r % 53 == 0) return NULL; + *len = (uint32_t)snprintf(buf, 256, "m%04lld", (long long)((r * 13) % 1500)); + return buf; +} +static const char* pqx_hot(int64_t r, char* buf, uint32_t* len) { + int64_t g = r * pqx_groups / pqx_rows; + if (r % 9 == 0) return pqx_lowcard(r, buf, len); + if (r % 10 < 7) { *len = (uint32_t)snprintf(buf, 256, "HOT"); return buf; } + *len = (uint32_t)snprintf(buf, 256, "d%lld", (long long)(r % (5 + 60 * g))); + return buf; +} +static const char* pqx_unique(int64_t r, char* buf, uint32_t* len) { + int n = snprintf(buf, 256, "e%08lld", (long long)r); + memset(buf + n, 'z', 80); + *len = (uint32_t)n + 80; + return buf; +} +/* The footer's bound on what the direct import holds for a column + * (pq_vocab_bounds, the trace's vocab_bytes) is an upper bound: at least + * the symbol file the direct import writes, for a snappy dictionary of long + * strings that share a prefix (its stored bytes far below its strings'), a + * writer's PLAIN fallback over the chunk's last eighth of the rows (with + * the encoding stats, and without them), and PLAIN pages only. And not a + * blanket one: a dictionary of forty strings with the stats saying no data + * page holds values stays small however many rows its ids cover. The + * trace says which columns are dictionaries and ids only (dict_only), the + * only ones a grouped import may still take direct. */ +static const char* pqx_prefixed(int64_t r, char* buf, uint32_t* len) { + memset(buf, 'P', 190); + *len = 190 + (uint32_t)snprintf(buf + 190, 60, "%09lld", (long long)(r % 1000)); + return buf; +} +static const char* pqx_late(int64_t r, char* buf, uint32_t* len) { + int64_t at = r % 8000; /* the row in its row group of 8000 */ + if (at < 7000) { *len = (uint32_t)snprintf(buf, 256, "q%lld", (long long)(r % 10)); return buf; } + buf[0] = (char)(33 + (r / 8836) % 94); buf[1] = (char)(33 + (r / 94) % 94); buf[2] = (char)(33 + r % 94); + *len = 3; + return buf; +} +/* A row in a thousand one of five strings, the rest null. */ +static const char* pqx_sparse_fallback(int64_t r, char* buf, uint32_t* len) { + if (r % 1000) return NULL; + *len = (uint32_t)snprintf(buf, 256, "z%lld", (long long)((r / 1000) % 5)); + return buf; +} +static test_result_t test_pq_sym_vocab_bound(void) { + pq_sym_env_clear(); + const char* nm[1] = {"p"}; + const char* fnames[2] = {"x","p"}; + char src[160], dir[160], sym[200]; + snprintf(src, sizeof(src), "/tmp/rayforce-pqv-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pqv-%d", (int)getpid()); + snprintf(sym, sizeof(sym), "%s/.sym", dir); + int64_t tids[2] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 2); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + TEST_ASSERT_EQ_I(pq_pool(2), RAY_OK); + static const struct { const char* what; pq_synth_fn fn; unsigned flags; int64_t rows; bool small; } cases[] = { + {"snappy dictionary", pqx_prefixed, PQX_DICT | PQX_SNAPPY, 20000, false}, + {"late PLAIN fallback", pqx_late, PQX_FALLBACK | PQX_LATE, 16000, false}, + {"late PLAIN fallback, no stats", pqx_late, PQX_FALLBACK | PQX_LATE | PQX_NOSTATS, 16000, false}, + {"PLAIN", pqx_late, 0, 16000, false}, + {"forty strings", pqx_lowcard, PQX_DICT, 40000, true}, + }; + int bad = 0; + for (size_t k = 0; k < sizeof(cases) / sizeof(cases[0]); k++) { + pq_synth_fn fn[1] = {cases[k].fn}; + unsigned fl[1] = {cases[k].flags}; + TEST_ASSERT_TRUE(pqx_synth(src, cases[k].rows, 2, 1, nm, fn, fl)); + pq_set_symmode("direct"); + ray_t* res = pq_traced_import(src, dir, types, trace, cap); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + TEST_ASSERT_TRUE(pqx_check(dir, cases[k].rows, 1, nm, fn, cases[k].what, NULL)); + FILE* f = fopen(sym, "rb"); + long size = -1; + if (f) { fseek(f, 0, SEEK_END); size = ftell(f); fclose(f); } + double bound = pq_trace_sum(trace, "vocab_bytes", NULL); + fprintf(stderr, " %s: bound %.0f B, .sym %ld B, %lld symbols\n", cases[k].what, bound, size, (long long)pq_sym_count(dir)); + /* the records' bytes and the direct import's own per string (an + * offset, a hash slot, at least 40 bytes) */ + if (size <= 0 || bound < (double)size + 40.0 * (double)pq_sym_count(dir)) bad++; + if (cases[k].small && bound > 64 * 1024) bad++; + /* dictionary pages and ids only: the stats saying no data page holds values */ + if (pq_trace_line_num(trace, "parquet symcol: col=p ", "dict_only") != (cases[k].flags & PQX_FALLBACK || !(cases[k].flags & PQX_DICT) ? 0 : 1)) { + fprintf(stderr, " %s: dict_only %.0f\n", cases[k].what, pq_trace_line_num(trace, "parquet symcol: col=p ", "dict_only")); + bad++; + } + pq_remove_native(dir, fnames, 2); + } +#if defined(DEBUG) + /* A column whose chunks hold values in data pages (a fallback, though + * nearly all its rows are null and its bound small) next to long unique + * strings, with memory such that its bound is within a sixty-fourth and + * the text past a quarter: it goes grouped all the same (a direct pass + * gives such strings positions in the workers' order), the other too. */ + { + const char* nm2[2] = {"p","q"}; + const char* fn2names[3] = {"x","p","q"}; + pq_synth_fn fn2[2] = {pqx_sparse_fallback, pqx_unique}; + unsigned fl2[2] = {PQX_FALLBACK, 0}; + int64_t tids3[3] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + ray_t* types3 = ray_vec_from_raw(RAY_SYM, tids3, 3); + TEST_ASSERT_TRUE(pqx_synth(src, 20000, 2, 2, nm2, fn2, fl2)); + pq_set_symmode("direct"); + ray_t* res = pq_traced_import(src, dir, types3, trace, cap); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + pq_remove_native(dir, fn2names, 3); + double bp = pq_trace_line_num(trace, "parquet symcol: col=p ", "vocab_bytes"); + double text = pq_trace_line_num(trace, "parquet symcol: col=p ", "text_bytes") + + pq_trace_line_num(trace, "parquet symcol: col=q ", "text_bytes"); + char ramv[32]; snprintf(ramv, sizeof(ramv), "%lld", (long long)(bp * 64)); + if (bp <= 0 || bp * 64 / 4 >= text) { fprintf(stderr, " sparse fallback: no memory size fits: p %.0f, text %.0f\n", bp, text); bad++; } + pq_set_env("RAY_PQ_SYM_RAM", ramv); + res = pq_traced_import(src, dir, types3, trace, cap); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + TEST_ASSERT_TRUE(pqx_check(dir, 20000, 2, nm2, fn2, "sparse fallback", NULL)); + bool p_grouped = pq_trace_line_has(trace, "parquet symcol: col=p ", " mode=grouped"); + fprintf(stderr, " sparse fallback: bound %.0f B, p %s\n", bp, p_grouped ? "grouped" : "direct"); + if (!p_grouped) bad++; + pq_remove_native(dir, fn2names, 3); + ray_release(types3); + } +#endif + ray_sys_free(trace); + ray_release(types); unlink(src); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +} +/* A hundred strings, and ten. */ +static const char* pqx_card100(int64_t r, char* buf, uint32_t* len) { + *len = (uint32_t)snprintf(buf, 256, "m%03lld", (long long)((r * 13) % 100)); + return buf; +} +static const char* pqx_card10(int64_t r, char* buf, uint32_t* len) { + if (r % 17 == 0) return NULL; + *len = (uint32_t)snprintf(buf, 256, "w%lld", (long long)((r * 3) % 10)); + return buf; +} +/* The column-by-column decision's caps, with the memory it assumes set from + * the columns' bounds (RAY_PQ_SYM_RAM, debug builds): a dictionary column + * whose bound is past a sixty-fourth of memory goes grouped though it would + * fit the sixteenth the direct ones share; two dictionary columns within + * both go direct, the whole import then direct (no grouped pass), their + * dictionaries seeded in row-group order: one worker's files the same with + * the row groups taken last to first. */ +static test_result_t test_pq_sym_direct_caps(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160], ref[160], a[240], b[240]; + snprintf(src, sizeof(src), "/tmp/rayforce-pqcap-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pqcap-%d", (int)getpid()); + snprintf(ref, sizeof(ref), "/tmp/rayforce-pqcap-%d-ref", (int)getpid()); + const char* fnames[3] = {"x","p","q"}; + const char* nm[2] = {"p","q"}; + int64_t tids[3] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + int bad = 0; + for (int k = 0; k < 2; k++) { + /* 0: p a hundred strings, q a string a row; 1: p forty, q ten */ + pq_synth_fn fns[2] = {k ? pqx_lowcard : pqx_card100, k ? pqx_card10 : pqx_highcard}; + unsigned fl[2] = {PQX_DICT, k ? PQX_DICT : 0}; + int64_t rows = k ? 40000 : 20000; + TEST_ASSERT_TRUE(pqx_synth(src, rows, 2, 2, nm, fns, fl)); + pq_set_symmode("direct"); + ray_t* res = pq_traced_import(src, dir, types, trace, cap); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + int64_t words = pq_sym_count(dir); + pq_remove_native(dir, fnames, 3); + double bp = pq_trace_line_num(trace, "parquet symcol: col=p ", "vocab_bytes"); + double bq = pq_trace_line_num(trace, "parquet symcol: col=q ", "vocab_bytes"); + double text = pq_trace_line_num(trace, "parquet symcol: col=p ", "text_bytes") + + pq_trace_line_num(trace, "parquet symcol: col=q ", "text_bytes"); + /* 0: p's bound a thirty-second of memory; 1: the larger one's a + * sixty-fourth (the two within a sixteenth) */ + double big = bp > bq ? bp : bq; + int64_t sram = k ? (int64_t)(big * 64) : (int64_t)(bp * 32); + char ramv[32]; snprintf(ramv, sizeof(ramv), "%lld", (long long)sram); + if (bp <= 0 || (double)sram / 4 >= text || (!k && bq <= (double)sram / 16)) { + fprintf(stderr, " caps %d: no memory size fits: p %.0f, q %.0f, text %.0f\n", k, bp, bq, text); + bad++; + } + for (int run = 0; run < 2; run++) { + const char* out = run ? dir : ref; + pq_set_env("RAY_PQ_SYM_RAM", ramv); + if (run) pq_set_env("RAY_PQ_DIRECT_REVERSE", "1"); + res = pq_traced_import(src, out, types, trace, cap); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + TEST_ASSERT_TRUE(pqx_check(out, rows, 2, nm, fns, k ? "caps 1" : "caps 0", NULL)); + if (pq_sym_count(out) != words) { fprintf(stderr, " caps %d: %lld symbols, direct %lld\n", k, (long long)pq_sym_count(out), (long long)words); bad++; } + bool p_direct = pq_trace_line_has(trace, "parquet symcol: col=p ", " mode=direct"); + bool q_direct = pq_trace_line_has(trace, "parquet symcol: col=q ", " mode=direct"); + int passes = 0; + (void)pq_trace_sum(trace, "rec_bytes", &passes); + bool seeded = strstr(trace, "parquet symseed:") != NULL; + fprintf(stderr, " caps %d/%d: p %s, q %s, %d grouped passes%s\n", k, run, p_direct ? "direct" : "grouped", + q_direct ? "direct" : "grouped", passes, seeded ? ", seeded" : ""); + if (k ? !p_direct || !q_direct || passes != 0 || !seeded : p_direct || q_direct || passes != 2) bad++; + } + if (k) { + bool same = true; + snprintf(a, sizeof(a), "%s/.sym", ref); snprintf(b, sizeof(b), "%s/.sym", dir); + if (!pq_same_file(a, b)) same = false; + for (int c = 1; c < 3; c++) { + snprintf(a, sizeof(a), "%s/%s", ref, fnames[c]); snprintf(b, sizeof(b), "%s/%s", dir, fnames[c]); + if (!pq_same_file(a, b)) same = false; + } + if (!same) { fprintf(stderr, " caps 1: files differ with the row groups reversed\n"); bad++; } + } + pq_remove_native(dir, fnames, 3); pq_remove_native(ref, fnames, 3); + unlink(src); + } + ray_pool_destroy(); + ray_sys_free(trace); + ray_release(types); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* A file of no row groups, forced grouped: imported, no rows; a step + * failing (resolve still runs, over no tasks) reports its error, publishes + * nothing and keeps no memory, run after run. */ +static test_result_t test_pq_sym_grouped_empty(void) { +#if !defined(DEBUG) + SKIP("failure injection is a debug-build knob"); +#else + pq_sym_env_clear(); + const char* nm[1] = {"p"}; + const char* fn2[2] = {"x","p"}; + pq_synth_fn fn[1] = {pqx_unique}; + unsigned fl[1] = {0}; + char src[160], dir[160], partial[240]; + snprintf(src, sizeof(src), "/tmp/rayforce-pqe-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pqe-%d", (int)getpid()); + snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + TEST_ASSERT_TRUE(pqx_synth(src, 0, 0, 1, nm, fn, fl)); + int64_t tids[2] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 2); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + const char* steps[] = {NULL, "p2"}; + int bad = 0; + for (int i = 0; i < 2; i++) { + size_t base = 0; + for (int k = 0; k < 4; k++) { + pq_set_symmode("grouped"); + pq_set_env("RAY_PQ_SYM_INJECT", steps[i]); + ray_t* res = ray_parquet_splayed_typed(src, dir, types); + pq_sym_env_clear(); + bool failed = !res || RAY_IS_ERR(res); + bool published = access(dir, F_OK) == 0; + if (failed != (steps[i] != NULL) || published == failed || (!failed && res->i64 != 0)) { + fprintf(stderr, " empty file, inject %s: %s, %s\n", steps[i] ? steps[i] : "none", + failed ? (res ? ray_err_code(res) : "null") : "imported", published ? "published" : "nothing published"); + bad++; + } + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + pq_remove_native(partial, fn2, 2); pq_remove_native(dir, fn2, 2); + ray_mem_stats_t st; ray_mem_stats(&st); + if (k == 1) base = st.bytes_allocated; + if (k == 3 && st.bytes_allocated > base) { + fprintf(stderr, " empty file, inject %s: heap %+lld B\n", steps[i] ? steps[i] : "none", + (long long)st.bytes_allocated - (long long)base); + bad++; + } + } + } + ray_pool_destroy(); + ray_release(types); unlink(src); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* Which way each symbol column went, from the trace's symcol lines: 'D' or + * 'G' in the file's column order, '?' when the trace does not say. */ +static void pqx_modes(const char* trace, int n, const char* const* names, char* out) { + for (int c = 0; c < n; c++) { + char line[64]; snprintf(line, sizeof(line), "parquet symcol: col=%s ", names[c]); + out[c] = pq_trace_line_has(trace, line, " mode=direct") ? 'D' : pq_trace_line_has(trace, line, " mode=grouped") ? 'G' : '?'; + } + out[n] = 0; +} +/* Direct and grouped columns side by side: five symbol columns (pqx_*) + * whose strings meet across columns, imported with the memory the decision + * assumes swept (RAY_PQ_SYM_RAM, debug builds) so that different sets go + * direct, then with every order of new positions, hash groups, windows, a + * small dedupe arena, none of the hash and column by column, on one worker + * and four. Every row as the function has it, the columns in the file's + * order (the direct ones are imported first), the symbol file the direct + * import's size (no string twice, none lost), the null flags the direct + * import's, and every grouped record's writeback started by its window. + * Mixed or forced grouped, the files do not depend on the workers. Then each + * injected failure of a mixed import, and repeated imports keeping no + * memory. The default run is a subset of the matrix; PQX_FULL=1 runs all + * of it (PQX_ROWS, PQX_GROUPS, PQX_RAM, PQX_TRACE change it; PQX_DET runs a + * probe of its own instead). */ +static test_result_t test_pq_symgrp_mixed_columns(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + enum { N = 5 }; + const char* names[N] = {"b","a","e","d","c"}; + const pq_synth_fn fns[N] = {pqx_highcard, pqx_lowcard, pqx_unique, pqx_hot, pqx_fallback}; + const unsigned flags[N] = {0, PQX_DICT | PQX_SNAPPY, PQX_SNAPPY, PQX_DICT | PQX_SNAPPY, PQX_FALLBACK}; + const char* fnames[N + 1] = {"x","b","a","e","d","c"}; + const int64_t rows = getenv("PQX_ROWS") ? atoll(getenv("PQX_ROWS")) : 6000; + const int64_t groups = getenv("PQX_GROUPS") ? atoll(getenv("PQX_GROUPS")) : 3; + char src[160], dir[160], ref[160], what[200], a[240], b[240]; + snprintf(src, sizeof(src), "/tmp/rayforce-pqx-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pqx-%d", (int)getpid()); + snprintf(ref, sizeof(ref), "/tmp/rayforce-pqx-%d-ref", (int)getpid()); + TEST_ASSERT_TRUE(pqx_synth(src, rows, groups, N, names, fns, flags)); + int64_t tids[N + 1]; + tids[0] = ray_sym_intern("I32", 3); + for (int c = 1; c <= N; c++) tids[c] = ray_sym_intern("SYM", 3); + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, N + 1); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + int bad = 0; + /* the direct import: the vocabulary's size and the null flags */ + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + pq_set_symmode("direct"); + ray_t* res = ray_parquet_splayed_typed(src, dir, types); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + int dn[N] = {0}, gn[N] = {0}; + TEST_ASSERT_TRUE(pqx_check(dir, rows, N, names, fns, "direct", dn)); + int64_t words = pq_sym_count(dir); + pq_remove_native(dir, fnames, N + 1); + /* PQX_DET=1: whether the direct import's files depend on the workers + * (one worker against four, three times), printed only */ + for (int k = 0; getenv("PQX_DET") && k < 3; k++) { + for (int cores = 1; cores <= 4; cores += 3) { + TEST_ASSERT_EQ_I(pq_pool(cores), RAY_OK); + pq_set_symmode("direct"); + res = ray_parquet_splayed_typed(src, cores == 1 ? ref : dir, types); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + } + bool same = true; + snprintf(a, sizeof(a), "%s/.sym", ref); snprintf(b, sizeof(b), "%s/.sym", dir); + if (!pq_same_file(a, b)) same = false; + for (int c = 1; c <= N; c++) { + snprintf(a, sizeof(a), "%s/%s", ref, fnames[c]); snprintf(b, sizeof(b), "%s/%s", dir, fnames[c]); + if (!pq_same_file(a, b)) same = false; + } + fprintf(stderr, " mixed_columns: direct import, 1 vs 4 workers, try %d: files %s\n", k, same ? "the same" : "differ"); + pq_remove_native(dir, fnames, N + 1); pq_remove_native(ref, fnames, N + 1); + } + /* the decision swept: a set of columns direct, the rest grouped (a pool + * a worker count) */ + char seen[16][N + 1], mixram[16][32]; + int nmix = 0; + int nseen = 0, mixed = 0; + /* the default run sweeps on one worker; PQX_FULL=1 on one and four */ + bool full = getenv("PQX_FULL") != NULL; + for (int cores = 1; cores <= (full ? 4 : 1); cores += 3) { + TEST_ASSERT_EQ_I(pq_pool(cores), RAY_OK); + for (int k = 0; k < 28; k++) { /* half powers of two from 16 KB */ + int64_t m = (int64_t)16384 << (k / 2); + char ram[32]; snprintf(ram, sizeof(ram), "%lld", (long long)(k & 1 ? m * 181 / 128 : m)); + pq_set_env("RAY_PQ_SYM_RAM", ram); + res = pq_traced_import(src, dir, types, trace, cap); + pq_sym_env_clear(); + char modes[N + 1]; pqx_modes(trace, N, names, modes); + if (getenv("PQX_TRACE") && k == 0 && cores == 1) fprintf(stderr, "%s", trace); + snprintf(what, sizeof(what), "ram=%s cores=%d modes=%s", ram, cores, modes); + if (!res || RAY_IS_ERR(res)) { + fprintf(stderr, " [%s] import failed: %s\n", what, res ? ray_err_code(res) : "null"); + if (res) ray_error_free(res); + char partial[240]; snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + pq_remove_native(partial, fnames, N + 1); + bad++; continue; + } + ray_release(res); + if (!pqx_check(dir, rows, N, names, fns, what, gn)) bad++; + if (pq_sym_count(dir) != words) { fprintf(stderr, " [%s] symbols %lld, direct %lld\n", what, (long long)pq_sym_count(dir), (long long)words); bad++; } + if (memcmp(gn, dn, sizeof(dn))) { fprintf(stderr, " [%s] null flags differ from the direct import's\n", what); bad++; } + int nd = 0, ng = 0; + for (int c = 0; c < N; c++) { nd += modes[c] == 'D'; ng += modes[c] == 'G'; } + if (nd && ng) mixed++; + bool known = false; + for (int s = 0; s < nseen; s++) if (!strcmp(seen[s], modes)) known = true; + if (!known && nseen < 16) { + memcpy(seen[nseen++], modes, N + 1); + fprintf(stderr, " mixed_columns: ram=%s modes %s (b a e d c)\n", ram, modes); + if (nd && ng && nmix < 16) snprintf(mixram[nmix++], sizeof(mixram[0]), "%s", ram); + } + pq_remove_native(dir, fnames, N + 1); + } + } + if (mixed < (full ? 4 : 2) || nseen < 3 || !nmix) { fprintf(stderr, " mixed_columns: %d mixed imports, %d decisions\n", mixed, nseen); bad++; } + if (!nmix) snprintf(mixram[nmix++], sizeof(mixram[0]), "%s", "1048576"); + /* a mixed decision with every knob of the grouped import, and forced + * grouped: one worker's files, then four workers' the same bytes */ + const char* orders[] = {"rows","shards","freq","rowsflat"}; + for (int cores = 1; cores <= 4; cores += 3) { + TEST_ASSERT_EQ_I(pq_pool(cores), RAY_OK); + for (int run = 0; run < 48; run++) { + int o = run % 4, knob = (run / 4) % 4; + bool forced = run >= 32; + /* the default run: neither none of the hash nor the small arena + * with six bits of it (the collision tests have them), a window a + * task with four groups forced grouped only; PQX_FULL=1 all of it */ + if (!full && (knob >= 2 || (!forced && knob == 1))) continue; + /* the first mixed decision of the sweep, then the last */ + const char* ram_mixed = getenv("PQX_RAM") ? getenv("PQX_RAM") : mixram[run < 16 ? 0 : nmix - 1]; + const char* window = knob & 1 ? "1" : knob == 2 ? "4096" : NULL; + const char* bits = knob == 2 ? "0" : knob == 3 ? "6" : NULL; + const char* groupsv = knob & 1 ? "4" : NULL; + const char* arena = knob == 3 ? "200" : NULL; + /* one worker's files kept, a run each, for four workers' */ + snprintf(ref, sizeof(ref), "/tmp/rayforce-pqx-%d-ref-%d", (int)getpid(), run); + const char* out = cores == 1 ? ref : dir; + pq_set_env("RAY_PQ_SYM_RAM", ram_mixed); + if (forced) pq_set_symmode("grouped"); + if (o == 1) pq_set_layout("1"); /* column by column, the direct ones too */ + pq_set_env("RAY_PQ_SYM_ORDER", orders[o]); + pq_set_env("RAY_PQ_SYM_WINDOW", window); + pq_set_env("RAY_PQ_SYM_HASH_BITS", bits); + pq_set_env("RAY_PQ_SYM_GROUPS", groupsv); + pq_set_env("RAY_PQ_SYM_ARENA", arena); + res = pq_traced_import(src, out, types, trace, cap); + pq_sym_env_clear(); + char modes[N + 1]; pqx_modes(trace, N, names, modes); + snprintf(what, sizeof(what), "%s %s window=%s bits=%s groups=%s arena=%s cores=%d modes=%s", forced ? "forced" : "auto", + orders[o], window ? window : "-", bits ? bits : "-", groupsv ? groupsv : "-", arena ? arena : "-", cores, modes); + if (!res || RAY_IS_ERR(res)) { + fprintf(stderr, " [%s] import failed: %s\n", what, res ? ray_err_code(res) : "null"); + if (res) ray_error_free(res); + char partial[240]; snprintf(partial, sizeof(partial), "%s.parquet-partial", out); + pq_remove_native(partial, fnames, N + 1); + bad++; continue; + } + ray_release(res); + if (!forced && (!strchr(modes, 'D') || !strchr(modes, 'G'))) { fprintf(stderr, " [%s] not a mixed decision\n", what); bad++; } + /* every record's writeback started by its window: exactly the + * records' bytes where a window's records lie side by side */ + int gpasses = 0; + double recb = pq_trace_sum(trace, "rec_bytes", &gpasses), wbb = pq_trace_sum(trace, "wb_bytes", NULL); + if (gpasses < 2 || !(o == 0 || o == 3 ? wbb == recb : wbb >= recb)) { + fprintf(stderr, " [%s] %d grouped passes, rec_bytes %.0f, wb_bytes %.0f\n", what, gpasses, recb, wbb); + bad++; + } + if (!pqx_check(out, rows, N, names, fns, what, gn)) bad++; + if (pq_sym_count(out) != words) { fprintf(stderr, " [%s] symbols %lld, direct %lld\n", what, (long long)pq_sym_count(out), (long long)words); bad++; } + if (memcmp(gn, dn, sizeof(dn))) { fprintf(stderr, " [%s] null flags differ from the direct import's\n", what); bad++; } + if (cores > 1) { + bool same = true; + snprintf(a, sizeof(a), "%s/.sym", ref); snprintf(b, sizeof(b), "%s/.sym", dir); + if (!pq_same_file(a, b)) same = false; + for (int c = 1; c <= N; c++) { + snprintf(a, sizeof(a), "%s/%s", ref, fnames[c]); snprintf(b, sizeof(b), "%s/%s", dir, fnames[c]); + if (!pq_same_file(a, b)) same = false; + } + /* the direct passes of a mixed import too: their dictionaries + * are interned in row-group order first (pq_seed_dicts) */ + if (!same) { fprintf(stderr, " [%s] files differ from one worker's\n", what); bad++; } + pq_remove_native(dir, fnames, N + 1); + pq_remove_native(ref, fnames, N + 1); + } + } + } + /* a mixed decision failing in each step of its grouped passes (a direct + * pass before them): an error, nothing published, and on one worker no + * memory kept, run after run (the heap's and the system allocator's + * bytes after the second run and the last: the third, the fifth with + * PQX_FULL=1); then the import itself as many times */ + const char* steps[] = {"r1","p2","load","reload","r2","write","settle","cancel",NULL}; + char partial[240]; snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + for (int i = 0; i < 9; i++) { + size_t base = 0, sbase = 0; + int runs = full ? 5 : 3; /* the memory compared after the second and the last */ + for (int k = 0; k < runs; k++) { + pq_set_env("RAY_PQ_SYM_RAM", mixram[nmix - 1]); + pq_set_env("RAY_PQ_SYM_WINDOW", "1"); + pq_set_env("RAY_PQ_SYM_INJECT", steps[i]); + res = ray_parquet_splayed_typed(src, dir, types); + pq_sym_env_clear(); + bool failed = !res || RAY_IS_ERR(res); + bool cancel = failed && res && !strcmp(ray_err_code(res), "cancel"); + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + ray_clear_interrupt(); + bool published = access(dir, F_OK) == 0; + if (failed != (steps[i] != NULL) || (steps[i] && published) || cancel != (i == 7)) { + fprintf(stderr, " mixed_columns: inject %s: failed=%d cancel=%d published=%d\n", steps[i] ? steps[i] : "none", + failed, cancel, published); + bad++; + } + pq_remove_native(partial, fnames, N + 1); + pq_remove_native(dir, fnames, N + 1); + ray_mem_stats_t st; ray_mem_stats(&st); + if (k == 1) { base = st.bytes_allocated; sbase = st.sys_current; } + if (k == runs - 1 && (st.bytes_allocated > base + 512 || st.sys_current > sbase + (8u << 10))) { + fprintf(stderr, " mixed_columns: inject %s: heap %+lld B sys %+lld B\n", steps[i] ? steps[i] : "none", + (long long)st.bytes_allocated - (long long)base, (long long)st.sys_current - (long long)sbase); + bad++; + } + } + } + ray_pool_destroy(); + ray_sys_free(trace); + ray_release(types); unlink(src); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* Skeptic probes (pqio round 3). The column files and .sym of two imports, + * byte for byte; the ones that differ named. */ +static bool sk_files_same(const char* ref, const char* dir, const char* const* fnames, int n) { + char a[240], b[240]; + snprintf(a, sizeof(a), "%s/.sym", ref); snprintf(b, sizeof(b), "%s/.sym", dir); + bool same = pq_same_file(a, b); + if (!same) fprintf(stderr, " differs: .sym\n"); + for (int c = 0; c < n; c++) { + snprintf(a, sizeof(a), "%s/%s", ref, fnames[c]); snprintf(b, sizeof(b), "%s/%s", dir, fnames[c]); + if (!pq_same_file(a, b)) { same = false; fprintf(stderr, " differs: %s\n", fnames[c]); } + } + return same; +} +/* The memory (RAY_PQ_SYM_RAM) that makes p and q (dictionary columns) direct + * and the import grouped: from a forced direct import's trace, sixty-four + * times the larger bound, the text past a quarter of it. 0 when none fits. */ +static int64_t sk_mixed_ram(const char* src, const char* dir, ray_t* types, const char* const* fnames, int nf, + char* trace, size_t cap, int64_t* words) { + pq_set_symmode("direct"); + ray_t* res = pq_traced_import(src, dir, types, trace, cap); + pq_sym_env_clear(); + bool ok = res && !RAY_IS_ERR(res); + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + if (words) *words = ok ? pq_sym_count(dir) : -1; + pq_remove_native(dir, (const char**)fnames, nf); + double bp = pq_trace_line_num(trace, "parquet symcol: col=p ", "vocab_bytes"); + double bq = pq_trace_line_num(trace, "parquet symcol: col=q ", "vocab_bytes"); + double text = pq_trace_sum(trace, "text_bytes", NULL); + /* an unbounded column (a chunk of no size: never direct) sets nothing */ + if (bp >= 0x1p62) bp = 0; + if (bq >= 0x1p62) bq = 0; + double big = bp > bq ? bp : bq; + int64_t sram = (int64_t)(big * 64) + 1024; + fprintf(stderr, " sk: bounds p %.0f q %.0f text %.0f -> ram %lld\n", bp, bq, text, (long long)sram); + return big > 0 && (double)sram / 4 < text ? sram : 0; +} +/* A mixed import (p, q dictionary columns direct and seeded, u grouped) and, + * without u, an import every column of which qualifies (direct throughout, + * seeded), on 1, 2, 4 and 8 workers, and with the direct passes' row groups + * reversed on 1, 4 and 8: every run the same files as one worker's. */ +static test_result_t test_pq_sk_mixed_workers(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160], ref[160]; + snprintf(src, sizeof(src), "/tmp/rayforce-sk3w-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-sk3w-%d", (int)getpid()); + snprintf(ref, sizeof(ref), "/tmp/rayforce-sk3w-%d-ref", (int)getpid()); + const char* fnames[4] = {"x","p","q","u"}; + const char* nm[3] = {"p","q","u"}; + pq_synth_fn fns[3] = {pqx_lowcard, pqx_card100, pqx_unique}; + unsigned fl[3] = {PQX_DICT | PQX_SNAPPY, PQX_DICT, 0}; + int64_t tids[4] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + int bad = 0; + for (int v = 0; v < 2; v++) { + int n = v ? 2 : 3; + /* all-direct: ten times the rows, the ids' text past a quarter of the + * memory that keeps the dictionaries' bounds within a sixty-fourth */ + const int64_t rows = v ? 240000 : 24000; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, n + 1); + TEST_ASSERT_TRUE(pqx_synth(src, rows, 6, n, nm, fns, fl)); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + int64_t words = 0; + int64_t sram = sk_mixed_ram(src, dir, types, fnames, n + 1, trace, cap, &words); + TEST_ASSERT_TRUE(sram > 0); + char ramv[32]; snprintf(ramv, sizeof(ramv), "%lld", (long long)sram); + static const struct { int cores; bool rev; } runs[] = {{1,false},{2,false},{4,false},{8,false},{1,true},{4,true},{8,true}}; + for (size_t k = 0; k < sizeof(runs) / sizeof(runs[0]); k++) { + const char* out = k ? dir : ref; + TEST_ASSERT_EQ_I(pq_pool(runs[k].cores), RAY_OK); + pq_set_env("RAY_PQ_SYM_RAM", ramv); + if (runs[k].rev) pq_set_env("RAY_PQ_DIRECT_REVERSE", "1"); + ray_t* res = pq_traced_import(src, out, types, trace, cap); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + char what[64]; snprintf(what, sizeof(what), "sk workers %s %d%s", v ? "all-direct" : "mixed", runs[k].cores, runs[k].rev ? " rev" : ""); + if (!pqx_check(out, rows, n, nm, fns, what, NULL)) bad++; + bool pd = pq_trace_line_has(trace, "parquet symcol: col=p ", " mode=direct"); + bool qd = pq_trace_line_has(trace, "parquet symcol: col=q ", " mode=direct"); + bool ug = v || pq_trace_line_has(trace, "parquet symcol: col=u ", " mode=grouped"); + bool seeded = strstr(trace, "parquet symseed:") != NULL; + bool same = !k || sk_files_same(ref, out, fnames + 1, n); + fprintf(stderr, " [%s] p %s q %s u %s%s, %lld symbols (direct %lld)%s\n", what, pd ? "D" : "G", qd ? "D" : "G", + v ? "-" : ug ? "G" : "D", seeded ? " seeded" : "", (long long)pq_sym_count(out), (long long)words, same ? "" : ", FILES DIFFER"); + /* honest dictionaries: the seeding saw every string */ + if (pq_trace_line_num(trace, "parquet symdirect:", "seed_miss") != 0) bad++; + if (!pd || !qd || !ug || !seeded || !same || pq_sym_count(out) != words) bad++; + if (k) pq_remove_native(dir, fnames, n + 1); + } + pq_remove_native(ref, fnames, n + 1); + unlink(src); + ray_release(types); + } + ray_pool_destroy(); + ray_sys_free(trace); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* Footers that would make a chunk look dictionary-only when it is not: 1, a + * total_uncompressed_size of 0, a chunk of rows of no size: unsure, so q + * goes grouped and every run writes one worker's files; 0, encoding stats + * that leave out its PLAIN pages (a writer's fallback past the dictionary; + * malformed, and only the pages themselves would tell): q goes direct and + * seeded, and the trace counts the strings its passes add that the seeding + * did not see (seed_miss, their positions the workers'). Values right in + * both; whether the files differ is printed. */ +static test_result_t test_pq_sk_lying_stats(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160], ref[160]; + snprintf(src, sizeof(src), "/tmp/rayforce-sk3l-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-sk3l-%d", (int)getpid()); + snprintf(ref, sizeof(ref), "/tmp/rayforce-sk3l-%d-ref", (int)getpid()); + const char* fnames[4] = {"x","p","q","u"}; + const char* nm[3] = {"p","q","u"}; + int64_t tids[4] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 4); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + const int64_t rows = 48000; + int bad = 0; + for (int v = 0; v < 2; v++) { + snprintf(src, sizeof(src), "/tmp/rayforce-sk3l-%d-%d.parquet", (int)getpid(), v); + pq_synth_fn fns[3] = {pqx_lowcard, v ? pqx_hot : pqx_late, pqx_unique}; /* hot: dictionaries that differ by row group */ + unsigned fl[3] = {PQX_DICT | PQX_SNAPPY, v ? PQX_DICT | PQX_ZERORAW : PQX_FALLBACK | PQX_LIESTATS, 0}; + TEST_ASSERT_TRUE(pqx_synth(src, rows, 6, 3, nm, fns, fl)); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + int64_t words = 0; + int64_t sram = sk_mixed_ram(src, dir, types, fnames, 4, trace, cap, &words); + double bq = pq_trace_line_num(trace, "parquet symcol: col=q ", "vocab_bytes"); + double donly = pq_trace_line_num(trace, "parquet symcol: col=q ", "dict_only"); + TEST_ASSERT_TRUE(sram > 0); + char ramv[32]; snprintf(ramv, sizeof(ramv), "%lld", (long long)sram); + static const struct { int cores; bool rev; } runs[] = {{1,false},{4,false},{8,false},{1,true}}; + int differ = 0; + for (size_t k = 0; k < sizeof(runs) / sizeof(runs[0]); k++) { + const char* out = k ? dir : ref; + TEST_ASSERT_EQ_I(pq_pool(runs[k].cores), RAY_OK); + pq_set_env("RAY_PQ_SYM_RAM", ramv); + if (runs[k].rev) pq_set_env("RAY_PQ_DIRECT_REVERSE", "1"); + ray_t* res = pq_traced_import(src, out, types, trace, cap); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + char what[64]; snprintf(what, sizeof(what), "sk lying %s %d%s", v ? "raw=0" : "stats", runs[k].cores, runs[k].rev ? " rev" : ""); + if (!pqx_check(out, rows, 3, nm, fns, what, NULL)) bad++; + bool qd = pq_trace_line_has(trace, "parquet symcol: col=q ", " mode=direct"); + bool pd = pq_trace_line_has(trace, "parquet symcol: col=p ", " mode=direct"); + double miss = pq_trace_line_num(trace, "parquet symdirect:", "seed_miss"); + bool same = !k || sk_files_same(ref, out, fnames + 1, 3); + if (!same) differ++; + char sym[200]; snprintf(sym, sizeof(sym), "%s/.sym", out); + FILE* f = fopen(sym, "rb"); long size = -1; + if (f) { fseek(f, 0, SEEK_END); size = ftell(f); fclose(f); } + fprintf(stderr, " [%s] q %s (dict_only %.0f, bound %.0f B), seed_miss %.0f, .sym %ld B, %lld symbols%s\n", what, + qd ? "direct" : "grouped", donly, bq, miss, size, (long long)pq_sym_count(out), same ? "" : ", FILES DIFFER from one worker's"); + if (!pd || pq_sym_count(out) != words) bad++; + if (v && (qd || donly != 0 || bq < 0x1p62 || miss != 0 || !same)) bad++; /* unsure: unbounded */ + if (!v && (!qd || miss <= 0)) bad++; + if (k) pq_remove_native(dir, fnames, 4); + } + fprintf(stderr, " sk lying %s: %d of %d runs differ from one worker's files\n", v ? "raw=0" : "stats", differ, + (int)(sizeof(runs) / sizeof(runs[0])) - 1); + pq_remove_native(ref, fnames, 4); + if (getenv("SK_KEEP")) fprintf(stderr, " sk lying: kept %s (RAY_PQ_SYM_RAM=%s)\n", src, ramv); else unlink(src); + } + ray_pool_destroy(); + ray_sys_free(trace); + ray_release(types); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* A row group of no rows amid the others, written as pyarrow writes one (a + * dictionary column's chunk an empty dictionary page and data_page_offset + * 0): nothing to decode, so it neither unbounds a dictionary column nor + * stops its seeding. p and q go direct and seeded, u grouped, on one and + * four workers alike; and a small file of the same make goes direct. */ +static test_result_t test_pq_symgrp_empty_group(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160], ref[160]; + snprintf(src, sizeof(src), "/tmp/rayforce-pqeg-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pqeg-%d", (int)getpid()); + snprintf(ref, sizeof(ref), "/tmp/rayforce-pqeg-%d-ref", (int)getpid()); + const char* fnames[4] = {"x","p","q","u"}; + const char* nm[3] = {"p","q","u"}; + pq_synth_fn fns[3] = {pqx_lowcard, pqx_card100, pqx_unique}; + unsigned fl[3] = {PQX_DICT | PQX_SNAPPY, PQX_DICT, 0}; + int64_t tids[4] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 4); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + const int64_t rows = 24000; + pqx_empty = 3; + bool made = pqx_synth(src, rows, 7, 3, nm, fns, fl); + pqx_empty = -1; + TEST_ASSERT_TRUE(made); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + int64_t words = 0; + int64_t sram = sk_mixed_ram(src, dir, types, fnames, 4, trace, cap, &words); + double op = pq_trace_line_num(trace, "parquet symcol: col=p ", "dict_only"); + double oq = pq_trace_line_num(trace, "parquet symcol: col=q ", "dict_only"); + TEST_ASSERT_TRUE(sram > 0); + int bad = 0; + if (op != 1 || oq != 1) { fprintf(stderr, " empty group: dict_only p %.0f q %.0f\n", op, oq); bad++; } + char ramv[32]; snprintf(ramv, sizeof(ramv), "%lld", (long long)sram); + static const int cores[] = {1, 4}; + for (size_t k = 0; k < sizeof(cores) / sizeof(cores[0]); k++) { + const char* out = k ? dir : ref; + TEST_ASSERT_EQ_I(pq_pool(cores[k]), RAY_OK); + pq_set_env("RAY_PQ_SYM_RAM", ramv); + ray_error_clear(); + ray_t* res = pq_traced_import(src, out, types, trace, cap); + pq_sym_env_clear(); + bool ok = res && !RAY_IS_ERR(res); + if (!ok) fprintf(stderr, " empty group %d: %s\n", cores[k], ray_error_msg() ? ray_error_msg() : "(no message)"); + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + TEST_ASSERT_TRUE(ok); + char what[64]; snprintf(what, sizeof(what), "empty group %d", cores[k]); + if (!pqx_check(out, rows, 3, nm, fns, what, NULL)) bad++; + bool pd = pq_trace_line_has(trace, "parquet symcol: col=p ", " mode=direct"); + bool qd = pq_trace_line_has(trace, "parquet symcol: col=q ", " mode=direct"); + bool ug = pq_trace_line_has(trace, "parquet symcol: col=u ", " mode=grouped"); + bool seeded = strstr(trace, "parquet symseed:") != NULL; + double miss = pq_trace_line_num(trace, "parquet symdirect:", "seed_miss"); + bool same = !k || sk_files_same(ref, out, fnames + 1, 3); + fprintf(stderr, " [%s] p %s q %s u %s%s, seed_miss %.0f, %lld symbols (direct %lld)%s\n", what, pd ? "D" : "G", + qd ? "D" : "G", ug ? "G" : "D", seeded ? " seeded" : "", miss, (long long)pq_sym_count(out), (long long)words, + same ? "" : ", FILES DIFFER"); + if (!pd || !qd || !ug || !seeded || miss != 0 || !same || pq_sym_count(out) != words) bad++; + if (k) pq_remove_native(dir, fnames, 4); + } + pq_remove_native(ref, fnames, 4); + /* nor does its chunk of u, PLAIN and of no size (no page), make a small + * file's text unbounded: the import goes direct throughout */ + pqx_empty = 3; + made = pqx_synth(src, 2400, 7, 3, nm, fns, fl); + pqx_empty = -1; + TEST_ASSERT_TRUE(made); + pq_set_env("RAY_PQ_SYM_RAM", "16777216"); + ray_t* res = pq_traced_import(src, dir, types, trace, cap); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + if (!pqx_check(dir, 2400, 3, nm, fns, "empty group, small", NULL)) bad++; + bool ud = pq_trace_line_has(trace, "parquet symcol: col=u ", " mode=direct"); + if (!ud || strstr(trace, "parquet symseed:")) { fprintf(stderr, " empty group, small: u %s\n", ud ? "direct, seeded" : "grouped"); bad++; } + pq_remove_native(dir, fnames, 4); + unlink(src); + ray_pool_destroy(); + ray_sys_free(trace); + ray_release(types); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* A mixed import over a degenerate hash (RAY_PQ_SYM_HASH_BITS=0: every + * string of the grouped column in one hash group, each new one compared + * with those before it): p and q direct and seeded, u grouped (PLAIN, few + * distinct strings, which keeps the compares few under the sanitizers), on + * one worker and on two: the same files, every row right. */ +static test_result_t test_pq_symgrp_degenerate_hash(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160], ref[160]; + snprintf(src, sizeof(src), "/tmp/rayforce-pqdh-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pqdh-%d", (int)getpid()); + snprintf(ref, sizeof(ref), "/tmp/rayforce-pqdh-%d-ref", (int)getpid()); + const char* fnames[4] = {"x","p","q","u"}; + const char* nm[3] = {"p","q","u"}; + pq_synth_fn fns[3] = {pqx_lowcard, pqx_card100, pqx_lowcard}; + unsigned fl[3] = {PQX_DICT | PQX_SNAPPY, PQX_DICT, 0}; + int64_t tids[4] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 4); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + const int64_t rows = 18000; + TEST_ASSERT_TRUE(pqx_synth(src, rows, 6, 3, nm, fns, fl)); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + int64_t words = 0; + int64_t sram = sk_mixed_ram(src, dir, types, fnames, 4, trace, cap, &words); + TEST_ASSERT_TRUE(sram > 0); + char ramv[32]; snprintf(ramv, sizeof(ramv), "%lld", (long long)sram); + int bad = 0; + for (int cores = 1; cores <= 2; cores++) { + const char* out = cores == 1 ? ref : dir; + TEST_ASSERT_EQ_I(pq_pool(cores), RAY_OK); + pq_set_env("RAY_PQ_SYM_RAM", ramv); + pq_set_env("RAY_PQ_SYM_HASH_BITS", "0"); + ray_t* res = pq_traced_import(src, out, types, trace, cap); + pq_sym_env_clear(); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + char what[64]; snprintf(what, sizeof(what), "degenerate hash %d", cores); + if (!pqx_check(out, rows, 3, nm, fns, what, NULL)) bad++; + bool pd = pq_trace_line_has(trace, "parquet symcol: col=p ", " mode=direct"); + bool qd = pq_trace_line_has(trace, "parquet symcol: col=q ", " mode=direct"); + bool ug = pq_trace_line_has(trace, "parquet symcol: col=u ", " mode=grouped"); + bool seeded = strstr(trace, "parquet symseed:") != NULL; + double collisions = pq_trace_sum(trace, "collisions", NULL); + bool same = cores == 1 || sk_files_same(ref, out, fnames + 1, 3); + fprintf(stderr, " [%s] p %s q %s u %s%s, %.0f collisions, %lld symbols (direct %lld)%s\n", what, pd ? "D" : "G", + qd ? "D" : "G", ug ? "G" : "D", seeded ? " seeded" : "", collisions, (long long)pq_sym_count(out), + (long long)words, same ? "" : ", FILES DIFFER"); + if (!pd || !qd || !ug || !seeded || collisions <= 0 || !same || pq_sym_count(out) != words) bad++; + } + pq_remove_native(dir, fnames, 4); + pq_remove_native(ref, fnames, 4); + unlink(src); + ray_pool_destroy(); + ray_sys_free(trace); + ray_release(types); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* Whether the file at `path` holds the n bytes `s`: 1, 0, -1 when it + * cannot be read. */ +static int pq_file_has(const char* path, const char* s, size_t n) { + FILE* f = fopen(path, "rb"); + if (!f) return -1; + char buf[65536 + 256]; + size_t keep = 0, got; + int found = 0; + while (!found && n && (got = fread(buf + keep, 1, sizeof(buf) - keep, f)) > 0) { + size_t have = keep + got; + for (size_t i = 0; !found && i + n <= have; i++) found = !memcmp(buf + i, s, n); + keep = have < n - 1 ? have : n - 1; /* a match across the read boundary */ + memmove(buf, buf + have - keep, keep); + } + fclose(f); + return found; +} +/* A dictionary column the reader cannot decode: a codec it does not take + * (ZSTD, 6), a dictionary page of an encoding it does not know (3), or one + * whose checksum (a file written with page CRCs) its bytes no longer match, + * a byte of its first string flipped. The import reports the decoder's own + * reason and the column, forced direct and as a mixed import whose + * dictionary column is seeded first (the error then the seeding's, the same + * words); nothing is published, and the symbol file the failed import + * leaves in its staging directory holds no string of the page gone bad, + * but row group 0's (the seeding fails at the bad page, the last row + * group's). The direct import on one worker, two and four: the message + * the same whichever worker read the bad page. And a + * dictionary column whose checksums hold imports both ways, the mixed import + * seeded, every row and the vocabulary the direct import's. */ +static test_result_t test_pq_sk_codec_message(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160], partial[240]; + snprintf(src, sizeof(src), "/tmp/rayforce-sk3c-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-sk3c-%d", (int)getpid()); + snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + const char* fnames[4] = {"x","p","q","u"}; + const char* nm[3] = {"p","q","u"}; + pq_synth_fn fns[3] = {pqx_lowcard, pqx_card100, pqx_unique}; + int64_t tids[4] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 4); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + TEST_ASSERT_EQ_I(pq_pool(2), RAY_OK); + int bad = 0; + static const struct { unsigned flags; const char* want; } cases[] = { + {PQX_DICT | PQX_ZSTD, "unsupported compression codec"}, + {PQX_DICT | PQX_BADDICT, "invalid dictionary page"}, + {PQX_DICT | PQX_CRC | PQX_CRCFLIP, "page checksum mismatch"}, + {PQX_DICT | PQX_CRC, NULL}, /* checksums that hold: imported both ways, the mixed one seeded */ + }; + /* the first string of row group 0's dictionary of p (row 0 is null) */ + char g0buf[256]; uint32_t g0len = 0; + const char* g0 = pqx_lowcard(1, g0buf, &g0len); + for (size_t v = 0; v < sizeof(cases) / sizeof(cases[0]); v++) { + unsigned fl[3] = {cases[v].flags, PQX_DICT, 0}; + TEST_ASSERT_TRUE(pqx_synth(src, 24000, 6, 3, nm, fns, fl)); + int64_t words = -1; + int64_t sram = sk_mixed_ram(src, dir, types, fnames, 4, trace, cap, &words); + pq_remove_native(partial, fnames, 4); + TEST_ASSERT_TRUE(sram > 0); + char ramv[32]; snprintf(ramv, sizeof(ramv), "%lld", (long long)sram); + char first[256] = ""; + /* direct on one worker, two and four (the bad page read by any of + * them), then mixed on two */ + for (int run = 0; run < 4; run++) { + bool mixed = run == 3; + int cores = mixed ? 2 : 1 << run; + TEST_ASSERT_EQ_I(pq_pool(cores), RAY_OK); + if (mixed) pq_set_env("RAY_PQ_SYM_RAM", ramv); else pq_set_symmode("direct"); + ray_error_clear(); + ray_t* res = pq_traced_import(src, dir, types, trace, cap); + pq_sym_env_clear(); + const char* msg = ray_error_msg(); + bool failed = !res || RAY_IS_ERR(res); + bool pd = pq_trace_line_has(trace, "parquet symcol: col=p ", " mode=direct"); + if (!cases[v].want) { + bool ok = !failed && pqx_check(dir, 24000, 3, nm, fns, mixed ? "sk codec crc mixed" : "sk codec crc direct", NULL); + bool seeded = strstr(trace, "parquet symseed:") != NULL; + double entries = pq_trace_line_num(trace, "parquet symseed:", "entries"); + double miss = pq_trace_line_num(trace, "parquet symdirect:", "seed_miss"); + fprintf(stderr, " sk codec %zu %s %d: %s%s, seeded %.0f entries, seed_miss %.0f, %lld symbols (direct %lld)\n", v, + mixed ? "mixed" : "direct", cores, ok ? "imported" : "FAILED: ", ok ? "" : msg ? msg : "(no message)", + seeded ? entries : 0.0, miss, (long long)pq_sym_count(dir), (long long)words); + if (!ok || !pd || pq_sym_count(dir) != words) bad++; + if (mixed && (!seeded || entries <= 0 || miss != 0)) bad++; + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + pq_remove_native(partial, fnames, 4); pq_remove_native(dir, fnames, 4); + continue; + } + fprintf(stderr, " sk codec %zu %s %d: %s: %s%s\n", v, mixed ? "mixed" : "direct", cores, failed ? "failed" : "imported", + msg ? msg : "(no message)", mixed ? "" : pd ? " (p direct)" : " (p grouped)"); + /* the mixed import fails in its seeding, before its symcol lines: + * the seeding checks what it interns as the decoder would (no + * page the pass then refuses is interned first: no symseed line) */ + if (!failed || !msg || !strstr(msg, cases[v].want) || !strstr(msg, "(column p)") || (!mixed && !pd)) bad++; + if (!run && msg) snprintf(first, sizeof(first), "%s", msg); + if (run && (!msg || strcmp(first, msg))) bad++; /* the same words on any worker, and seeding */ + if (mixed && strstr(trace, "parquet symseed:")) bad++; + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + if (access(dir, F_OK) == 0) { fprintf(stderr, " sk codec %zu: published\n", v); bad++; } + if (cases[v].flags & PQX_CRCFLIP) { + char sym[300]; snprintf(sym, sizeof(sym), "%s/.sym", partial); + int has = pqx_flipped_len ? pq_file_has(sym, pqx_flipped, pqx_flipped_len) : 1; + fprintf(stderr, " sk codec %zu %s %d: the staged .sym %s\n", v, mixed ? "mixed" : "direct", cores, + has < 0 ? "is not there" : has ? "HOLDS the bad page's string" : "holds no string of the bad page"); + if (has > 0) bad++; + /* and the seeding failed where the bad page is, the last row group: + * row group 0's dictionaries, good, went in before it */ + int got0 = mixed && g0 ? pq_file_has(sym, g0, g0len) : 1; + if (mixed) fprintf(stderr, " sk codec %zu mixed: row group 0's strings %s\n", v, got0 > 0 ? "seeded" : "NOT seeded"); + if (got0 <= 0) bad++; + } + pq_remove_native(partial, fnames, 4); pq_remove_native(dir, fnames, 4); + } + if (getenv("SK_KEEP")) fprintf(stderr, " sk codec: kept %s\n", src); else unlink(src); + } + ray_pool_destroy(); + ray_sys_free(trace); + ray_release(types); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* A footer whose total_uncompressed_size is out of all proportion (INT64_MAX + * - 4096) on a PLAIN symbol column, next to a dictionary column, imported + * with memory that makes the import grouped: the dictionary column direct + * and seeded, the PLAIN one grouped, every row right. Run in a child (no + * pool workers: fork-safe) whose exit says whether the import got through + * the bound's arithmetic and the decision. */ +static test_result_t test_pq_sk_huge_raw(void) { +#if !defined(DEBUG) || defined(RAY_OS_WINDOWS) || defined(RAY_OS_WASM) + SKIP("the memory the decision assumes is a debug-build knob; fork"); +#else + pq_sym_env_clear(); + char src[160], dir[160], partial[240]; + snprintf(src, sizeof(src), "/tmp/rayforce-sk3h-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-sk3h-%d", (int)getpid()); + snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + const char* fnames[4] = {"x","p","q","u"}; + const char* nm[3] = {"p","q","u"}; + pq_synth_fn fns[3] = {pqx_lowcard, pqx_highcard, pqx_unique}; + unsigned fl[3] = {PQX_DICT, PQX_HUGERAW, 0}; + int64_t tids[4] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 4); + /* five row groups: an odd count of wrapped per-chunk bounds sums negative */ + const int64_t rows = 20000; + TEST_ASSERT_TRUE(pqx_synth(src, rows, 5, 3, nm, fns, fl)); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); /* no worker threads */ + int bad = 0; + for (int run = 0; run < 2; run++) { + /* 0: grouped by the memory assumed (seeding, the direct caps); + * 1: forced direct, the reference */ + fflush(stderr); + pid_t pid = fork(); + TEST_ASSERT_TRUE(pid >= 0); + if (!pid) { + if (run) pq_set_symmode("direct"); else pq_set_env("RAY_PQ_SYM_RAM", "1073741824"); + ray_t* res = ray_parquet_splayed_typed(src, dir, types); + bool ok = res && !RAY_IS_ERR(res); + const char* msg = ray_error_msg(); + fprintf(stderr, " sk huge raw (%s, child): %s%s%s\n", run ? "direct" : "auto, 1 GB", ok ? "imported" : "failed: ", + ok ? "" : (res ? ray_err_code(res) : "null"), ok ? "" : (msg ? msg : "")); + if (ok) ok = pqx_check(dir, rows, 3, nm, fns, "sk huge raw", NULL); + fflush(stderr); + _exit(ok ? 0 : 1); + } + int status = 0; + TEST_ASSERT_EQ_I(waitpid(pid, &status, 0), pid); + bool clean = WIFEXITED(status) && WEXITSTATUS(status) == 0; + fprintf(stderr, " sk huge raw %s: child %s %d\n", run ? "direct" : "auto", WIFEXITED(status) ? "exit" : "signal", + WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)); + if (!clean) bad++; + (void)ray_test_rm_rf(partial); (void)ray_test_rm_rf(dir); + (void)fnames; + } + if (getenv("SK_KEEP")) fprintf(stderr, " sk huge raw: kept %s\n", src); else unlink(src); + ray_pool_destroy(); + ray_release(types); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* Skeptic probes (pqio round 4). A column whose chunks have no size + * (total_uncompressed_size 0: unsure, unbounded by pq_chunk_vocab) beside a + * small honest dictionary column, in a file whose sized text is within a + * quarter of the memory assumed. The unsure column should go grouped, as + * the per-column rule has it, whatever the other columns' text: 0, q a + * dictionary of a hundred strings, 16 MB assumed; 1 and 2, q PLAIN unique + * 88-byte strings (100,000 rows, 8.8 MB of them), 1 MB assumed, with its + * sizes honest (1: the control, grouped) and of no size (2). */ +static test_result_t test_pq_sk4_unsure_small_text(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160]; + snprintf(src, sizeof(src), "/tmp/rayforce-sk4u-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-sk4u-%d", (int)getpid()); + const char* fnames[3] = {"x","p","q"}; + const char* nm[2] = {"p","q"}; + int64_t tids[3] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + TEST_ASSERT_EQ_I(pq_pool(2), RAY_OK); + int bad = 0; + for (int v = 0; v < 3; v++) { + pq_synth_fn fns[2] = {pqx_lowcard, v ? pqx_unique : pqx_card100}; + unsigned fl[2] = {PQX_DICT | PQX_SNAPPY, v == 0 ? PQX_DICT | PQX_ZERORAW : v == 1 ? 0u : (unsigned)PQX_ZERORAW}; + const int64_t rows = v ? 100000 : 24000; + const char* ram = v ? "1048576" : "16777216"; + TEST_ASSERT_TRUE(pqx_synth(src, rows, 6, 2, nm, fns, fl)); + pq_set_env("RAY_PQ_SYM_RAM", ram); + ray_t* res = pq_traced_import(src, dir, types, trace, cap); + pq_sym_env_clear(); + bool ok = res && !RAY_IS_ERR(res); + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + char what[32]; snprintf(what, sizeof(what), "sk4 unsure %d", v); + if (!ok || !pqx_check(dir, rows, 2, nm, fns, what, NULL)) bad++; + bool qg = pq_trace_line_has(trace, "parquet symcol: col=q ", " mode=grouped"); + double vq = pq_trace_line_num(trace, "parquet symcol: col=q ", "vocab_bytes"); + double dq = pq_trace_line_num(trace, "parquet symcol: col=q ", "dict_only"); + double tq = pq_trace_line_num(trace, "parquet symcol: col=q ", "text_bytes"); + double text = pq_trace_sum(trace, "text_bytes", NULL); + double tab = pq_trace_line_num(trace, "parquet symimp:", "tab_mb"); + double rec = pq_trace_line_num(trace, "parquet symimp:", "rec_mb"); + fprintf(stderr, " [%s] text %.0f B (q %.0f) of %s B assumed, q vocab %.3g B dict_only %.0f: q %s;" + " import dictionary tab_mb %.1f rec_mb %.1f\n", what, text, tq, ram, vq, dq, + qg ? "grouped" : "DIRECT", tab, rec); + if (!qg) bad++; + pq_remove_native(dir, fnames, 3); + if (v == 2 && getenv("SK_KEEP")) fprintf(stderr, " sk4 unsure: kept %s\n", src); else unlink(src); + } + ray_pool_destroy(); + ray_sys_free(trace); + ray_release(types); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* A mixed import (p, q direct and seeded, u grouped) and an all-direct one + * (no u) over a file with a zero-row group (pyarrow's layout) and a row + * group whose q chunk holds nulls only (an empty dictionary page, ids of no + * value): on 1, 2, 4 and 8 workers, the direct passes reversed on 1, 4 and + * 8; every run the same files as one worker's, every row right, the + * seeding seeing every string. */ +static int64_t sk4_null_lo = 0, sk4_null_hi = 0; +static const char* sk4_nullgrp(int64_t r, char* buf, uint32_t* len) { + if (r >= sk4_null_lo && r < sk4_null_hi) return NULL; + return pqx_card100(r, buf, len); +} +static test_result_t test_pq_sk4_null_group_workers(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160], ref[160]; + snprintf(src, sizeof(src), "/tmp/rayforce-sk4n-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-sk4n-%d", (int)getpid()); + snprintf(ref, sizeof(ref), "/tmp/rayforce-sk4n-%d-ref", (int)getpid()); + const char* fnames[4] = {"x","p","q","u"}; + const char* nm[3] = {"p","q","u"}; + pq_synth_fn fns[3] = {pqx_lowcard, sk4_nullgrp, pqx_unique}; + unsigned fl[3] = {PQX_DICT | PQX_SNAPPY, PQX_DICT, 0}; + int64_t tids[4] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + int bad = 0; + for (int v = 0; v < 2; v++) { + int n = v ? 2 : 3; + const int64_t rows = v ? 240000 : 24000; + /* seven row groups, the fourth (3) of no rows: group 2 is rows [2/6, 3/6) */ + sk4_null_lo = rows * 2 / 6; sk4_null_hi = rows * 3 / 6; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, n + 1); + pqx_empty = 3; + bool made = pqx_synth(src, rows, 7, n, nm, fns, fl); + pqx_empty = -1; + TEST_ASSERT_TRUE(made); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + int64_t words = 0; + int64_t sram = sk_mixed_ram(src, dir, types, fnames, n + 1, trace, cap, &words); + TEST_ASSERT_TRUE(sram > 0); + char ramv[32]; snprintf(ramv, sizeof(ramv), "%lld", (long long)sram); + static const struct { int cores; bool rev; } runs[] = {{1,false},{2,false},{4,false},{8,false},{1,true},{4,true},{8,true}}; + for (size_t k = 0; k < sizeof(runs) / sizeof(runs[0]); k++) { + const char* out = k ? dir : ref; + TEST_ASSERT_EQ_I(pq_pool(runs[k].cores), RAY_OK); + pq_set_env("RAY_PQ_SYM_RAM", ramv); + if (runs[k].rev) pq_set_env("RAY_PQ_DIRECT_REVERSE", "1"); + ray_t* res = pq_traced_import(src, out, types, trace, cap); + pq_sym_env_clear(); + bool ok = res && !RAY_IS_ERR(res); + if (!ok) fprintf(stderr, " sk4 null group: %s\n", ray_error_msg() ? ray_error_msg() : "(no message)"); + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + TEST_ASSERT_TRUE(ok); + char what[64]; snprintf(what, sizeof(what), "sk4 null group %s %d%s", v ? "all-direct" : "mixed", runs[k].cores, runs[k].rev ? " rev" : ""); + int nulls[3] = {0, 0, 0}; + if (!pqx_check(out, rows, n, nm, fns, what, nulls)) bad++; + bool pd = pq_trace_line_has(trace, "parquet symcol: col=p ", " mode=direct"); + bool qd = pq_trace_line_has(trace, "parquet symcol: col=q ", " mode=direct"); + bool ug = v || pq_trace_line_has(trace, "parquet symcol: col=u ", " mode=grouped"); + bool seeded = strstr(trace, "parquet symseed:") != NULL; + double miss = pq_trace_line_num(trace, "parquet symdirect:", "seed_miss"); + bool same = !k || sk_files_same(ref, out, fnames + 1, n); + /* the grouped pass's first reservation gave the shard tables back + * (no lookup in flight there): the trace's index bytes are none */ + double ikb = v ? 0 : pq_trace_line_num(trace, "parquet symgrp:", "imp_index_kb"); + fprintf(stderr, " [%s] p %s q %s u %s%s, seed_miss %.0f, q nulls %d, imp_index_kb %.0f, %lld symbols (direct %lld)%s\n", what, + pd ? "D" : "G", qd ? "D" : "G", v ? "-" : ug ? "G" : "D", seeded ? " seeded" : "", miss, nulls[1], ikb, + (long long)pq_sym_count(out), (long long)words, same ? "" : ", FILES DIFFER"); + if (!pd || !qd || !ug || !seeded || miss != 0 || !same || !nulls[1] || ikb != 0 || pq_sym_count(out) != words) bad++; + if (k) pq_remove_native(dir, fnames, n + 1); + } + pq_remove_native(ref, fnames, n + 1); + unlink(src); + ray_release(types); + } + ray_pool_destroy(); + ray_sys_free(trace); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* A dictionary column (p) whose data_page_offset does not point at its + * first data page: past the file's data (0), one byte into its dictionary + * page (1). The decoder reads a chunk from its dictionary page for + * total_compressed_size bytes and never uses that offset, so the forced + * direct import takes the file. The mixed import (p direct and seeded, u + * grouped) should take it too, or fail as the decoder would. */ +static test_result_t test_pq_sk4_data_offset(void) { +#if !defined(DEBUG) + SKIP("the memory the decision assumes is a debug-build knob"); +#else + pq_sym_env_clear(); + char src[160], dir[160], partial[240]; + snprintf(src, sizeof(src), "/tmp/rayforce-sk4d-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-sk4d-%d", (int)getpid()); + snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + const char* fnames[4] = {"x","p","q","u"}; + const char* nm[3] = {"p","q","u"}; + pq_synth_fn fns[3] = {pqx_lowcard, pqx_card100, pqx_unique}; + int64_t tids[4] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 4); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + TEST_ASSERT_EQ_I(pq_pool(2), RAY_OK); + int bad = 0; + for (int v = 0; v < 2; v++) { + unsigned fl[3] = {PQX_DICT | (v ? (unsigned)PQX_INDICT : (unsigned)PQX_FARDATA), PQX_DICT, 0}; + const int64_t rows = 24000; + TEST_ASSERT_TRUE(pqx_synth(src, rows, 6, 3, nm, fns, fl)); + /* forced direct: no seeding */ + pq_set_symmode("direct"); + ray_error_clear(); + ray_t* res = pq_traced_import(src, dir, types, trace, cap); + pq_sym_env_clear(); + bool dok = res && !RAY_IS_ERR(res); + char dmsg[256]; snprintf(dmsg, sizeof(dmsg), "%s", dok ? "imported" : ray_error_msg() ? ray_error_msg() : "(no message)"); + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + if (dok && !pqx_check(dir, rows, 3, nm, fns, "sk4 data offset direct", NULL)) dok = false; + double bp = pq_trace_line_num(trace, "parquet symcol: col=p ", "vocab_bytes"); + double bq = pq_trace_line_num(trace, "parquet symcol: col=q ", "vocab_bytes"); + double text = pq_trace_sum(trace, "text_bytes", NULL); + pq_remove_native(dir, fnames, 4); pq_remove_native(partial, fnames, 4); + /* the memory that makes p and q direct and the import grouped (sk_mixed_ram) */ + double big = bp > bq ? bp : bq; + int64_t sram = (int64_t)(big * 64) + 1024; + char ramv[32]; snprintf(ramv, sizeof(ramv), "%lld", (long long)sram); + pq_set_env("RAY_PQ_SYM_RAM", ramv); + ray_error_clear(); + res = pq_traced_import(src, dir, types, trace, cap); + pq_sym_env_clear(); + bool mok = res && !RAY_IS_ERR(res); + char mmsg[256]; snprintf(mmsg, sizeof(mmsg), "%s", mok ? "imported" : ray_error_msg() ? ray_error_msg() : "(no message)"); + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + bool seeded = strstr(trace, "parquet symseed:") != NULL; + fprintf(stderr, " [sk4 data offset %s] text %.0f ram %lld; direct: %s; mixed%s: %s\n", v ? "in dict" : "past data", text, + (long long)sram, dmsg, seeded ? " (seeded)" : "", mmsg); + if (dok && !mok) bad++; + pq_remove_native(dir, fnames, 4); pq_remove_native(partial, fnames, 4); + if (getenv("SK_KEEP")) { + char kept[200]; snprintf(kept, sizeof(kept), "/tmp/rayforce-sk4d-%d-%d.parquet", (int)getpid(), v); + if (rename(src, kept) == 0) fprintf(stderr, " sk4 data offset: kept %s (RAY_PQ_SYM_RAM=%s)\n", kept, ramv); + } + } + unlink(src); + ray_pool_destroy(); + ray_sys_free(trace); + ray_release(types); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#endif +} +/* The same undecodable dictionary page (encoding 3, PQX_BADDICT) in p, the + * import forced direct and forced grouped: both fail, and the grouped + * message should carry the decoder's reason and the column as the direct + * one does. So too a codec the reader does not take (ZSTD), which the + * chunk's checks before its pages refuse; and a dictionary page whose + * checksum fails, in the last row group only, which a pool worker as likely + * as not reads (its message carried to the thread that reports it), the + * parted import's row-group tasks too. And two pages that fail, in row + * groups 1 and 3 of p, each way round: every run reports row group 1's, + * whichever task failed first or was noted last. */ +static test_result_t test_pq_sk4_grouped_message(void) { + pq_sym_env_clear(); + char src[160], dir[160], partial[240]; + snprintf(src, sizeof(src), "/tmp/rayforce-sk4g-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-sk4g-%d", (int)getpid()); + snprintf(partial, sizeof(partial), "%s.parquet-partial", dir); + const char* fnames[3] = {"x","p","q"}; + const char* nm[2] = {"p","q"}; + pq_synth_fn fns[2] = {pqx_lowcard, pqx_card100}; + int64_t tids[3] = {ray_sym_intern("I32", 3), ray_sym_intern("SYM", 3), ray_sym_intern("SYM", 3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + TEST_ASSERT_EQ_I(pq_pool(2), RAY_OK); + int bad = 0; + /* f1, f3: the faults of row groups 1 and 3 (pqx_pfault); want: the + * message every run must report, the lower row group's */ + static const struct { unsigned flags, f1, f3; const char* want; } cases[] = { + {PQX_DICT | PQX_BADDICT, 0, 0, NULL}, + {PQX_DICT | PQX_ZSTD, 0, 0, NULL}, + {PQX_DICT | PQX_CRC | PQX_CRCFLIP, 0, 0, NULL}, + {PQX_DICT | PQX_CRC, PQX_PF_CRCFLIP, PQX_PF_BADDICT, "page checksum mismatch (column p)"}, + {PQX_DICT | PQX_CRC, PQX_PF_BADDICT, PQX_PF_CRCFLIP, "invalid dictionary page (column p)"}, + }; + for (size_t v = 0; v < sizeof(cases) / sizeof(cases[0]); v++) { + unsigned fl[2] = {cases[v].flags, PQX_DICT}; + pqx_pfault[1] = cases[v].f1; pqx_pfault[3] = cases[v].f3; + bool made = pqx_synth(src, 12000, 4, 2, nm, fns, fl); + pqx_pfault[1] = pqx_pfault[3] = 0; + TEST_ASSERT_TRUE(made); + char msgs[4][256]; + static const char* what[4] = {"direct", "grouped", "grouped", "parted"}; + for (int run = 0; run < 4; run++) { /* direct, grouped on two workers, grouped on four, parted on four */ + int cores = run >= 2 ? 4 : 2; + TEST_ASSERT_EQ_I(pq_pool(cores), RAY_OK); + if (run < 3) pq_set_symmode(run ? "grouped" : "direct"); + ray_error_clear(); + ray_t* res = run < 3 ? ray_parquet_splayed_typed(src, dir, types) : ray_parquet_parted_typed(src, dir, "t", types); + pq_sym_env_clear(); + bool failed = !res || RAY_IS_ERR(res); + const char* msg = ray_error_msg(); + snprintf(msgs[run], sizeof(msgs[run]), "%s", msg ? msg : "(no message)"); + fprintf(stderr, " [sk4 message %zu %s %d] %s: %s\n", v, what[run], cores, failed ? "failed" : "imported", msgs[run]); + if (!failed || !strstr(msgs[run], "(column p)") || (cases[v].want && strcmp(msgs[run], cases[v].want))) bad++; + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + if (run < 3) { pq_remove_native(dir, fnames, 3); pq_remove_native(partial, fnames, 3); } + else { (void)ray_test_rm_rf(partial); (void)ray_test_rm_rf(dir); } + } + for (int run = 1; run < 4; run++) if (strcmp(msgs[0], msgs[run]) != 0) bad++; + } + unlink(src); + ray_pool_destroy(); + ray_release(types); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +} +/* A page gone bad (a checksum that fails) in x's chunk of the last row + * group only, which a pool worker as likely as not reads: the reader + * (.parquet.read), a scan's projection and its streamed aggregate report + * the decoder's reason and the column on two workers and four, as on one + * (the worker's message carried to the thread that reports the error). */ +static void pq_lang_setup(void) { ray_runtime_create(0, NULL); } +static void pq_lang_teardown(void) { ray_runtime_destroy(__RUNTIME); } +static test_result_t test_pq_worker_messages(void) { + char src[160]; + snprintf(src, sizeof(src), "/tmp/rayforce-pqwm-%d.parquet", (int)getpid()); + const char* nm[1] = {"p"}; + pq_synth_fn fns[1] = {pqx_lowcard}; + unsigned fl[1] = {PQX_DICT}; + pqx_xflip = 3; + bool made = pqx_synth(src, 12000, 4, 1, nm, fns, fl); + pqx_xflip = -2; + TEST_ASSERT_TRUE(made); + char scan[400], agg[400]; + snprintf(scan, sizeof(scan), "(select {from: (.parquet.scan \"%s\") x: x})", src); + snprintf(agg, sizeof(agg), "(select {from: (.parquet.scan \"%s\") s: (sum x)})", src); + static const char* what[3] = {"read", "scan", "aggregate"}; + const char* want = "page checksum mismatch (column x)"; + int bad = 0; + static const int cores[] = {1, 2, 4}; + for (size_t k = 0; k < sizeof(cores) / sizeof(cores[0]); k++) { + TEST_ASSERT_EQ_I(pq_pool(cores[k]), RAY_OK); + for (int path = 0; path < 3; path++) { + ray_error_clear(); + ray_t* res = path == 0 ? ray_parquet_read(src, NULL) : ray_eval_str(path == 1 ? scan : agg); + const char* msg = ray_error_msg(); + bool failed = !res || RAY_IS_ERR(res); + fprintf(stderr, " [worker message %s %d] %s: %s\n", what[path], cores[k], failed ? "failed" : "read", + msg ? msg : "(no message)"); + if (!failed || !msg || !strstr(msg, want)) bad++; + if (res) { if (RAY_IS_ERR(res)) ray_error_free(res); else ray_release(res); } + } + } + ray_pool_destroy(); + unlink(src); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +} const test_entry_t parquet_entries[] = { + {"parquet/sk4_grouped_message",test_pq_sk4_grouped_message,pq_setup,pq_teardown}, + {"parquet/worker_messages",test_pq_worker_messages,pq_lang_setup,pq_lang_teardown}, + {"parquet/sk4_unsure_small_text",test_pq_sk4_unsure_small_text,pq_setup,pq_teardown}, + {"parquet/sk4_data_offset",test_pq_sk4_data_offset,pq_setup,pq_teardown}, + {"parquet/sk4_null_group_workers",test_pq_sk4_null_group_workers,pq_setup,pq_teardown}, + {"parquet/sk_huge_raw",test_pq_sk_huge_raw,pq_setup,pq_teardown}, + {"parquet/sk_mixed_workers",test_pq_sk_mixed_workers,pq_setup,pq_teardown}, + {"parquet/sk_lying_stats",test_pq_sk_lying_stats,pq_setup,pq_teardown}, + {"parquet/symgrp_empty_group",test_pq_symgrp_empty_group,pq_setup,pq_teardown}, + {"parquet/symgrp_degenerate_hash",test_pq_symgrp_degenerate_hash,pq_setup,pq_teardown}, + {"parquet/sk_codec_message",test_pq_sk_codec_message,pq_setup,pq_teardown}, {"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}, @@ -521,7 +3652,27 @@ const test_entry_t parquet_entries[] = { {"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/native_dictionary",test_pq_native_dictionary,pq_setup,pq_teardown}, {"parquet/group_native",test_pq_group_native,pq_setup,pq_teardown}, + {"parquet/sym_grouped",test_pq_sym_grouped,pq_setup,pq_teardown}, + {"parquet/sym_grouped_collisions",test_pq_sym_grouped_collisions,pq_setup,pq_teardown}, + {"parquet/sym_grouped_layout",test_pq_sym_grouped_layout,pq_setup,pq_teardown}, + {"parquet/sym_mixed_modes",test_pq_sym_mixed_modes,pq_setup,pq_teardown}, + {"parquet/sym_grouped_failures",test_pq_sym_grouped_failures,pq_setup,pq_teardown}, + {"parquet/dict_page_size",test_pq_dict_page_size,pq_setup,pq_teardown}, + {"parquet/import_no_growth",test_pq_import_no_growth,pq_setup,pq_teardown}, + {"parquet/symgrp_collision_determinism",test_pq_sym_grouped_collision_determinism,pq_setup,pq_teardown}, + {"parquet/symgrp_cancel_code",test_pq_sym_grouped_cancel_code,pq_setup,pq_teardown}, + {"parquet/symgrp_edges",test_pq_sym_grouped_edges,pq_setup,pq_teardown}, + {"parquet/symgrp_fail_leaks",test_pq_sym_grouped_fail_leaks,pq_setup,pq_teardown}, + {"parquet/symgrp_rowgroups",test_pq_sym_grouped_rowgroups,pq_setup,pq_teardown}, + {"parquet/symgrp_mixed_columns",test_pq_symgrp_mixed_columns,pq_setup,pq_teardown}, + {"parquet/sym_vocab_bound",test_pq_sym_vocab_bound,pq_setup,pq_teardown}, + {"parquet/sym_grouped_empty",test_pq_sym_grouped_empty,pq_setup,pq_teardown}, + {"parquet/sym_direct_caps",test_pq_sym_direct_caps,pq_setup,pq_teardown}, +#if defined(__linux__) + {"parquet/chunk_flush_error",test_pq_chunk_flush_error,pq_setup,pq_teardown}, +#endif {"parquet/splayed_inline_indexes",test_pq_splayed_inline_indexes,pq_setup,pq_teardown}, {"parquet/parallel",test_pq_parallel,pq_setup,pq_teardown}, {"parquet/range",test_pq_range,pq_setup,pq_teardown}, diff --git a/test/test_platform.c b/test/test_platform.c index 4e0e0abed..6be7c5525 100644 --- a/test/test_platform.c +++ b/test/test_platform.c @@ -21,6 +21,10 @@ * SOFTWARE. */ +/* open, mkdir, getpid: POSIX beyond C17. */ +#if !defined(_GNU_SOURCE) && !defined(_WIN32) +#define _GNU_SOURCE +#endif #include "test.h" #include #include @@ -28,6 +32,11 @@ #include "mem/heap.h" #include #include +#include +#include +#include +#include +#include /* ---- test_vm_alloc_free ------------------------------------------------ */ @@ -113,6 +122,49 @@ static test_result_t test_cgroup_mem_limit(void) { PASS(); } +#ifdef RAY_OS_LINUX +static void plat_write(const char* dir, const char* name, const char* text) { + char path[256]; + snprintf(path, sizeof(path), "%s/%s", dir, name); + int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (fd < 0) return; + ssize_t n = write(fd, text, strlen(text)); + (void)n; + close(fd); +} +static void plat_unlink(const char* dir, const char* name) { + char path[256]; + snprintf(path, sizeof(path), "%s/%s", dir, name); + unlink(path); +} +#endif + +/* The cgroup directory goes with the limit: there is one exactly when a + * limit is in force. Its memory.stat is read for what reading does — the + * kernel flushes the cgroup's statistics — here in a directory of the + * test's own too, and a directory without the file reads nothing. */ +static test_result_t test_cgroup_stat_flush(void) { + char dir[512]; + bool has = ray_os_cgroup_mem_dir(dir, sizeof(dir)); + TEST_ASSERT(has == (ray_os_cgroup_mem_limit() > 0), "a cgroup directory exactly with a limit"); + if (has) TEST_ASSERT(ray_os_cgroup_stat_flush(dir), "and its statistics read"); + TEST_ASSERT(!ray_os_cgroup_stat_flush(NULL) && !ray_os_cgroup_stat_flush(""), + "no cgroup: nothing read"); +#ifdef RAY_OS_LINUX + char tmp[64]; + snprintf(tmp, sizeof(tmp), "/tmp/rayforce_cg_%d", (int)getpid()); + TEST_ASSERT(mkdir(tmp, 0700) == 0, "a cgroup directory of our own"); + bool none = !ray_os_cgroup_stat_flush(tmp); + plat_write(tmp, "memory.stat", "anon 1\nfile 2\n"); + bool read = ray_os_cgroup_stat_flush(tmp); + plat_unlink(tmp, "memory.stat"); + rmdir(tmp); + TEST_ASSERT(none, "no memory.stat: nothing read"); + TEST_ASSERT(read, "its memory.stat read"); +#endif + PASS(); +} + /* ---- Suite definition -------------------------------------------------- */ const test_entry_t platform_entries[] = { @@ -121,6 +173,7 @@ const test_entry_t platform_entries[] = { { "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 }, + { "platform/cgroup_stat_flush", test_cgroup_stat_flush, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_pool.c b/test/test_pool.c index 86472f36b..d6dc1ae2a 100644 --- a/test/test_pool.c +++ b/test/test_pool.c @@ -32,6 +32,7 @@ #include "core/poll.h" #include "core/platform.h" #include "core/timer.h" +#include "core/profile.h" /* ray_profile_now_ns: bounded waits */ #include "mem/heap.h" #include "ops/ops.h" #include @@ -408,10 +409,20 @@ static void pool_count_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t typedef struct { ray_t* blocks[64]; uint32_t owner[64]; /* worker_id that allocated blocks[i]; 0 = main */ + ray_sem_t worker_started; + _Atomic(bool) worker_seen; } pool_alloc_ctx_t; static void pool_alloc_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { pool_alloc_ctx_t* c = (pool_alloc_ctx_t*)ctx; + /* Main cannot drain every task before a worker wakes. At least one + * worker must allocate, regardless of scheduler timing. */ + if (worker_id == 0) { + if (!atomic_load_explicit(&c->worker_seen, memory_order_acquire)) + ray_sem_wait(&c->worker_started); + } else if (!atomic_exchange_explicit(&c->worker_seen, true, memory_order_acq_rel)) { + ray_sem_signal(&c->worker_started); + } for (int64_t i = start; i < end && i < 64; i++) { c->blocks[i] = ray_alloc(256u << 10); /* 256 KB from the caller's heap */ c->owner[i] = worker_id; @@ -425,41 +436,51 @@ static test_result_t test_dispatch_reclaims_worker_blocks(void) { ray_err_t err = ray_pool_create(&pool, 3); TEST_ASSERT_EQ_I(err, RAY_OK); - /* ray_pool_create returns before the workers have started; a worker - * publishes its heap once it has run ray_heap_init. Wait for all three - * on that published state, so every slot below is a real heap. */ + /* A worker publishes its heap once it has run ray_heap_init (and + * ray_pool_create waits for that). Wait for all three on that + * published state, so every slot below is a real heap; one that never + * shows (its heap init failed) fails the test within a bound rather + * than hanging it. */ + int64_t until = ray_profile_now_ns() + (int64_t)30 * 1000000000; for (uint32_t w = 0; w < pool.n_workers; w++) - while (!atomic_load(&pool.worker_heaps[w])) RAY_CPU_RELAX(); + while (!atomic_load(&pool.worker_heaps[w])) { + if (ray_profile_now_ns() > until) { ray_pool_free(&pool); FAIL("a worker published no heap"); } + RAY_CPU_RELAX(); + } - /* Rounds of "workers allocate, main frees" until a round in which at - * least one block really came from a worker (main is worker 0 and can - * take every task when the others are slow to wake). Rounds are cheap; - * 64 of them without a worker allocation would mean the pool is not - * running its workers at all. */ pool_alloc_ctx_t ctx = {0}; + err = ray_sem_init(&ctx.worker_started, 0); + if (err != RAY_OK) ray_pool_free(&pool); + TEST_ASSERT_EQ_I(err, RAY_OK); + int worker_blocks = 0; - for (int round = 0; round < 64 && worker_blocks == 0; round++) { - ray_pool_dispatch_n(&pool, pool_alloc_fn, &ctx, 64); - for (int i = 0; i < 64; i++) { - TEST_ASSERT_NOT_NULL(ctx.blocks[i]); - if (ctx.owner[i] != 0) worker_blocks++; - ray_free(ctx.blocks[i]); /* cross-thread for worker blocks */ - ctx.blocks[i] = NULL; - } + bool all_allocated = true; + ray_pool_dispatch_n(&pool, pool_alloc_fn, &ctx, 64); + for (int i = 0; i < 64; i++) { + if (!ctx.blocks[i]) { all_allocated = false; continue; } + if (ctx.owner[i] != 0) worker_blocks++; + ray_free(ctx.blocks[i]); /* cross-thread for worker blocks */ } - TEST_ASSERT(worker_blocks > 0, "some blocks were allocated by workers"); - /* Those frees happened after the last dispatch ended, so the blocks sit + /* Those frees happened after the dispatch ended, so the blocks sit * on their owners' foreign lists now; the next dispatch hands them back. */ pool_count_ctx_t cctx = {0}; ray_pool_dispatch_n(&pool, pool_count_fn, &cctx, 4); + bool have_heaps = true, foreign_empty = true; for (uint32_t w = 0; w < pool.n_workers; w++) { ray_heap_t* wh = (ray_heap_t*)atomic_load(&pool.worker_heaps[w]); - TEST_ASSERT_NOT_NULL(wh); - TEST_ASSERT_NULL(atomic_load(&wh->foreign)); + if (!wh) have_heaps = false; + else if (atomic_load(&wh->foreign)) foreign_empty = false; } + /* Assertions return from the test: join workers before any can fail, + * so no live worker retains a pointer to this stack's pool/context. */ ray_pool_free(&pool); + ray_sem_destroy(&ctx.worker_started); + TEST_ASSERT(all_allocated, "all task blocks were allocated"); + TEST_ASSERT(worker_blocks > 0, "some blocks were allocated by workers"); + TEST_ASSERT(have_heaps, "all worker heaps were published"); + TEST_ASSERT(foreign_empty, "dispatch reclaimed every worker foreign list"); PASS(); } @@ -815,6 +836,79 @@ static test_result_t test_pool_init_total(void) { PASS(); } +/* -------------------------------------------------------------------------- + * Test: a new pool's workers are all started when it is handed out. + * + * A worker reads the environment as it starts (ray_heap_init's getenv); a + * caller's setenv right after the pool is made must not race those reads + * (glibc may free the environment array under a getenv). So every worker + * has published its heap by the time ray_pool_init_total returns, pool + * after pool. + * -------------------------------------------------------------------------- */ + +static test_result_t test_pool_workers_started(void) { + int missing = 0; + for (int round = 0; round < 20; round++) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(8), RAY_OK); + ray_pool_t* pool = ray_pool_get(); + TEST_ASSERT_NOT_NULL(pool); + for (uint32_t i = 0; i < pool->n_workers; i++) + if (!atomic_load_explicit(&pool->worker_heaps[i], memory_order_acquire)) missing++; +#if defined(__linux__) || defined(__APPLE__) + setenv("RAY_TEST_POOL_STARTED", round & 1 ? "1" : "0", 1); + unsetenv("RAY_TEST_POOL_STARTED"); +#endif + } + TEST_ASSERT_EQ_I(missing, 0); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init(0), RAY_OK); + PASS(); +} + +#if defined(__linux__) +#include +#include +/* Skeptic probe (round 3): a pool whose worker threads cannot be created + * (RLIMIT_NPROC below the user's thread count, in a child) fails to come + * up and returns — the creator's wait for the workers' start is not + * reached for threads that never ran — and a pool of one thread still + * comes up after it. */ +static test_result_t test_pool_sk_spawn_fails(void) { + /* The child starts pool threads after forking a multi-threaded + * process, which ThreadSanitizer refuses. */ +#if defined(__SANITIZE_THREAD__) + SKIP("ThreadSanitizer cannot start threads after a multi-threaded fork"); +#elif defined(__has_feature) +# if __has_feature(thread_sanitizer) + SKIP("ThreadSanitizer cannot start threads after a multi-threaded fork"); +# endif +#endif + fflush(stderr); + pid_t pid = fork(); + TEST_ASSERT_TRUE(pid >= 0); + if (!pid) { + struct rlimit rl; + if (getrlimit(RLIMIT_NPROC, &rl) != 0) _exit(10); + rl.rlim_cur = 1; + if (setrlimit(RLIMIT_NPROC, &rl) != 0) _exit(11); + ray_pool_t pool; + ray_err_t e = ray_pool_create(&pool, 16); + if (e == RAY_OK) { ray_pool_free(&pool); _exit(12); } /* not limited (root?) */ + ray_pool_t one; + if (ray_pool_create(&one, 1) != RAY_OK) _exit(0); /* still refused: fine */ + ray_pool_free(&one); + _exit(0); + } + int status = 0; + TEST_ASSERT_EQ_I(waitpid(pid, &status, 0), pid); + if (WIFEXITED(status) && WEXITSTATUS(status) == 12) SKIP("RLIMIT_NPROC not enforced here"); + TEST_ASSERT_TRUE(WIFEXITED(status)); + TEST_ASSERT_EQ_I(WEXITSTATUS(status), 0); + PASS(); +} +#endif + /* -------------------------------------------------------------------------- * Test: ray_pool_free(NULL) is a no-op (covers the early-return guard). * -------------------------------------------------------------------------- */ @@ -1653,6 +1747,658 @@ static test_result_t test_auto_all_logical_cpus(void) { } #endif +#if defined(__linux__) +#include +#include +#include +#include +#include +#include + +/* -------------------------------------------------------------------------- + * Test: scan read-ahead requests the registered rows from storage. + * + * A column file is evicted from the page cache, registered, and walked by + * tasks that read a page of it here and there at most, with the kernel's + * own read-ahead on faults off (MADV_RANDOM): the rest of its pages can + * only become resident because the pool asked the kernel for them. A + * dispatch over exactly its rows is read ahead per ticket; a dispatch_n + * task reports its position through ray_pool_scan_at; the chunks a gate + * rules out are never requested. Skipped where eviction has no effect + * (tmpfs keeps its pages) or read-ahead is turned off (RAY_SCAN_PREFETCH=0). + * -------------------------------------------------------------------------- */ +#define PF_ROWS ((int64_t)1 << 20) /* 8 MiB of int64 */ +#define PF_PAGES (PF_ROWS * 8 / 4096) +#define PF_TASKS 8 +#define PF_LOG2 16 /* gate chunk: 64K rows, 512 KiB */ +/* per process, so concurrent runs of the suite do not share the files */ +static char pf_path_a[96], pf_path_b[96]; +static void pf_paths(void) { + if (pf_path_a[0]) return; + snprintf(pf_path_a, sizeof(pf_path_a), "/tmp/rayforce_test_scan_ahead.%d.col", (int)getpid()); + snprintf(pf_path_b, sizeof(pf_path_b), "/tmp/rayforce_test_scan_ahead_b.%d.col", (int)getpid()); +} +#define PF_PATH (pf_paths(), pf_path_a) +#define PF_PATH_B (pf_paths(), pf_path_b) + +/* Ticket task: reads the middle row of its rows of column A (ctx), one + * page of the sixteen a ticket spans — the one the next call of its thread + * looks at to tell whether A is read. */ +static _Atomic int64_t pf_sink; /* read sink, written by every worker */ +static void pf_touch(void* ctx, uint32_t w, int64_t s, int64_t e) { + (void)w; + pf_sink += ((const int64_t*)ctx)[s + (e - s) / 2]; +} + +/* dispatch_n task t walks rows [t*per, (t+1)*per) of column A (ctx), + * reading only the first 8192 of them; the rest is left to read-ahead. */ +static void pf_walk(void* ctx, uint32_t w, int64_t s, int64_t e) { + (void)w; + const int64_t* a = (const int64_t*)ctx; + const int64_t per = PF_ROWS / PF_TASKS; + for (int64_t t = s; t < e; t++) + for (int64_t r = t * per; r < (t + 1) * per; r += 8192) { + ray_pool_scan_at(PF_ROWS, r, (t + 1) * per); + if (r == t * per) { + int64_t sum = 0; + for (int64_t i = r; i < r + 8192; i += 512) sum += a[i]; + pf_sink += sum; + } + } +} + +/* As pf_walk over columns A and B (ctx: their bases), block by block: the + * middle row of A in the first block, the middle row of B in each block + * from the seventh on. A block's call looks at the middle of the block + * before, so B is found unread at the calls of blocks 1-4. */ +static void pf_walk_late(void* ctx, uint32_t w, int64_t s, int64_t e) { + (void)w; + const int64_t* const* col = (const int64_t* const*)ctx; + const int64_t per = PF_ROWS / PF_TASKS; + for (int64_t t = s; t < e; t++) + for (int64_t r = t * per, k = 0; r < (t + 1) * per; r += 8192, k++) { + ray_pool_scan_at(PF_ROWS, r, (t + 1) * per); + if (k == 0) pf_sink += col[0][r + 4096]; + if (k >= 6) pf_sink += col[1][r + 4096]; + } +} + +/* As pf_walk, naming column A (ctx) as the one read and reading none of it. */ +static void pf_walk_named(void* ctx, uint32_t w, int64_t s, int64_t e) { + (void)w; + const int64_t per = PF_ROWS / PF_TASKS; + for (int64_t t = s; t < e; t++) + for (int64_t r = t * per; r < (t + 1) * per; r += 8192) + ray_pool_scan_col_at(ctx, PF_ROWS, r, (t + 1) * per); +} + +/* One task over every gate chunk of column A (ctx) — even chunks pass the + * gate: a call at each chunk's start; from the fifth gated-in chunk on, a + * second call half way through, with the row between the two calls read. */ +static void pf_walk_gaps(void* ctx, uint32_t w, int64_t s, int64_t e) { + (void)w; (void)s; (void)e; + const int64_t* a = (const int64_t*)ctx; + const int64_t chunk = (int64_t)1 << PF_LOG2; + int in = 0; + for (int64_t c0 = 0; c0 < PF_ROWS; c0 += chunk) { + ray_pool_scan_at(PF_ROWS, c0, PF_ROWS); + if ((c0 / chunk) % 2 || in++ < 4) continue; + pf_sink += a[c0 + chunk / 4]; + ray_pool_scan_at(PF_ROWS, c0 + chunk / 2, PF_ROWS); + } +} + +static bool pf_evict_one(const char* path) { + int fd = open(path, O_RDONLY); + if (fd < 0) return false; + bool ok = fdatasync(fd) == 0 && posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED) == 0; + close(fd); + return ok; +} +static bool pf_evict(void) { return pf_evict_one(PF_PATH) && pf_evict_one(PF_PATH_B); } + +/* Map a column file with the kernel's read-ahead on faults off: a page + * read through the mapping brings no neighbours in with it. */ +static uint8_t* pf_map(const char* path, size_t* size) { + uint8_t* p = (uint8_t*)ray_vm_map_file(path, size); + if (p) posix_madvise(p, *size, POSIX_MADV_RANDOM); + return p; +} + +/* No sampled page of [p, p+n) is resident. */ +static bool pf_none_resident(const uint8_t* p, size_t n) { + for (size_t off = 0; off < n; off += n / 16) + if (ray_vm_resident(p + off, 4096)) return false; + return true; +} + +/* Pages this process has read stay mapped and are not evicted: drop both + * columns' mappings, evict the files, map them again and re-register. */ +/* Finish every read before eviction. mincore reports an in-flight page as + * absent until it is uptodate, so probing residency first can skip exactly + * the reads that need draining. Fault every page, including those absent + * from the residency snapshot, then unmap and evict before the next case. */ +static void pf_settle(const uint8_t* p, size_t n) { + /* This mapping is about to be discarded; allow read-ahead while draining + * so cold pages do not each require a separate synchronous read. */ + posix_madvise((void*)p, n, POSIX_MADV_NORMAL); + for (size_t off = 0; off < n; off += 4096) + pf_sink += p[off]; +} + +static bool pf_reset(uint8_t** base, size_t* size, uint8_t** bbase, size_t* bsize, + ray_pool_scan_t* scan) { + pf_settle(*base, *size); + pf_settle(*bbase, *bsize); + ray_vm_unmap_file(*base, *size); + ray_vm_unmap_file(*bbase, *bsize); + *base = *bbase = NULL; + if (!pf_evict()) return false; + *base = pf_map(PF_PATH, size); + *bbase = pf_map(PF_PATH_B, bsize); + if (!*base || !*bbase) return false; + scan->base[0] = *base; + scan->base[1] = *bbase; + return pf_none_resident(*base, *size) && pf_none_resident(*bbase, *bsize); +} + +/* Resident pages of [p, p+n), probed one by one. */ +static int64_t pf_resident_pages(const uint8_t* p, size_t n) { + int64_t k = 0; + for (size_t off = 0; off < n; off += 4096) k += ray_vm_resident(p + off, 1); + return k; +} + +/* Bounded wait (~10 s) for `want` pages of [p, p+n) to be resident. */ +static bool pf_wait_pages(const uint8_t* p, size_t n, int64_t want) { + for (int i = 0; i < 2000; i++) { + if (pf_resident_pages(p, n) >= want) return true; + struct timespec ts = { 0, 5000000 }; + nanosleep(&ts, NULL); + } + return false; +} + +/* Bounded wait for the kernel to finish the reads: every sampled page of + * [p, p+n) resident. Returns false after ~10 s. */ +static bool pf_wait_resident(const void* p, size_t n) { + for (int i = 0; i < 20000; i++) { + if (ray_vm_resident(p, n)) return true; + struct timespec ts = { 0, 500000 }; + nanosleep(&ts, NULL); + } + return false; +} + +static test_result_t test_scan_read_ahead(void) { + ray_heap_init(); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + ray_pool_t* pool = ray_pool_get(); + TEST_ASSERT_NOT_NULL(pool); + test_result_t res = { TEST_PASS, NULL }; + uint8_t* base = NULL; + uint8_t* bbase = NULL; + size_t size = 0, bsize = 0; + + const char* paths[2] = { PF_PATH, PF_PATH_B }; + for (int k = 0; k < 2; k++) { + FILE* f = fopen(paths[k], "wb"); + TEST_ASSERT_NOT_NULL(f); + for (int64_t i = 0; i < PF_ROWS; i++) fwrite(&i, sizeof(i), 1, f); + fclose(f); + } + base = pf_map(PF_PATH, &size); + bbase = pf_map(PF_PATH_B, &bsize); + TEST_ASSERT_NOT_NULL(base); + TEST_ASSERT_NOT_NULL(bbase); + TEST_ASSERT_EQ_U(size, (uint64_t)PF_ROWS * 8); + + if (!pool->scan_bytes) { res = (test_result_t){ TEST_SKIP, "RAY_SCAN_PREFETCH=0" }; goto out; } + if (!pf_evict() || ray_vm_resident(base, size) || !pf_none_resident(bbase, bsize)) { + res = (test_result_t){ TEST_SKIP, "page cache eviction has no effect here" }; + goto out; + } + + /* Column B is registered but no dispatch below reads it: it must never + * be requested. */ + ray_pool_scan_t scan = { .base = { base, bbase }, .esz = { 8, 8 }, .n = 2, .rows = PF_ROWS }; + const ray_pool_scan_t* prev = ray_pool_scan_set(&scan); + + /* Per ticket: a dispatch over exactly the registered rows (range mode + * only; the shared cursor hands consecutive tickets to different + * threads, so there is no per-thread run to read ahead of). A ticket + * reads one page of A: enough for its thread to see A read, while the + * other pages come in only by request — all but those of the first + * ticket, before which nothing was seen read. */ + if (pool->steal) { + ray_pool_dispatch(pool, pf_touch, base, PF_ROWS); + if (!pf_wait_pages(base, size, PF_PAGES * 7 / 8)) { + res = (test_result_t){ TEST_FAIL, "per-ticket read-ahead left the rows unread" }; + goto restore; + } + if (!pf_none_resident(bbase, bsize)) { + res = (test_result_t){ TEST_FAIL, "per-ticket read-ahead requested a column no ticket read" }; + goto restore; + } + if (!pf_reset(&base, &size, &bbase, &bsize, &scan)) { res = (test_result_t){ TEST_FAIL, "evict" }; goto restore; } + } + + /* Reported positions: dispatch_n tasks walking row ranges, reading the + * first rows of each; the rest of A is requested, B is not. */ + ray_pool_dispatch_n(pool, pf_walk, base, PF_TASKS); + if (!pf_wait_resident(base, size)) { + res = (test_result_t){ TEST_FAIL, "task-reported read-ahead left the rows unread" }; + goto restore; + } + if (!pf_none_resident(bbase, bsize)) { + res = (test_result_t){ TEST_FAIL, "task-reported read-ahead requested a column no task read" }; + goto restore; + } + if (!pf_reset(&base, &size, &bbase, &bsize, &scan)) { res = (test_result_t){ TEST_FAIL, "evict" }; goto restore; } + + /* A column read sparsely: B is first read in the seventh block of each + * task, after four probes found it unread. It is never probed again, + * so never requested; A, read in the first block, is. */ + const uint8_t* cols[2] = { base, bbase }; + ray_pool_dispatch_n(pool, pf_walk_late, cols, PF_TASKS); + if (!pf_wait_pages(base, size, PF_PAGES * 7 / 8)) { + res = (test_result_t){ TEST_FAIL, "a column read from the first block was not requested" }; + goto restore; + } + if (pf_resident_pages(bbase, bsize) > PF_PAGES / 8) { + res = (test_result_t){ TEST_FAIL, "a column found unread four times was requested" }; + goto restore; + } + if (!pf_reset(&base, &size, &bbase, &bsize, &scan)) { res = (test_result_t){ TEST_FAIL, "evict" }; goto restore; } + + /* A task that names the column it reads has it requested from its first + * call, without reading any of it. */ + ray_pool_dispatch_n(pool, pf_walk_named, base, PF_TASKS); + if (!pf_wait_pages(base, size, PF_PAGES * 15 / 16)) { + res = (test_result_t){ TEST_FAIL, "a named column was not requested" }; + goto restore; + } + if (!pf_none_resident(bbase, bsize)) { + res = (test_result_t){ TEST_FAIL, "a column no task named was requested" }; + goto restore; + } + if (!pf_reset(&base, &size, &bbase, &bsize, &scan)) { res = (test_result_t){ TEST_FAIL, "evict" }; goto restore; } + + /* Gate: only even chunks may pass, so odd chunks are never requested. */ + uint64_t gate = 0; + const int64_t n_chunks = PF_ROWS >> PF_LOG2; + for (int64_t c = 0; c < n_chunks; c += 2) gate |= UINT64_C(1) << c; + scan.gate = &gate; + scan.gate_log2 = PF_LOG2; + ray_pool_dispatch_n(pool, pf_walk, base, PF_TASKS); + const size_t chunk = ((size_t)1 << PF_LOG2) * 8; + for (int64_t c = 0; c < n_chunks; c++) { + const uint8_t* p = base + (size_t)c * chunk; + if (c % 2 == 0 && !pf_wait_resident(p, chunk)) { + res = (test_result_t){ TEST_FAIL, "a gated-in chunk was not read" }; + goto restore; + } + if (c % 2 == 1 && ray_vm_resident(p + chunk / 2, 4096)) { + res = (test_result_t){ TEST_FAIL, "a gated-out chunk was read" }; + goto restore; + } + } + if (!pf_reset(&base, &size, &bbase, &bsize, &scan)) { res = (test_result_t){ TEST_FAIL, "evict" }; goto restore; } + + /* A gated-out chunk ends the run: the first call past it does not probe + * the rows the gate skipped (which nobody reads). Single calls between + * gaps there then cost the column no probes, and the run that reads it + * gets it requested — the later gated-in chunks, past what was read. */ + ray_pool_dispatch_n(pool, pf_walk_gaps, base, 1); + for (int64_t c = 10; c < n_chunks; c += 2) { + if (!pf_wait_resident(base + (size_t)c * chunk + chunk / 2, chunk / 2)) { + res = (test_result_t){ TEST_FAIL, "probes across gated-out chunks kept the column from being requested" }; + goto restore; + } + } + + /* Outside a dispatch the hooks have nothing registered to act on. */ + ray_pool_scan_at(PF_ROWS, 0, PF_ROWS); + ray_pool_scan_col_at(base, PF_ROWS, 0, PF_ROWS); + +restore: + ray_pool_scan_set(prev); +out: + if (base) ray_vm_unmap_file(base, size); + if (bbase) ray_vm_unmap_file(bbase, bsize); + remove(PF_PATH); + remove(PF_PATH_B); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init(0), RAY_OK); + ray_heap_destroy(); + (void)pf_sink; /* read the sink once, or clang flags it set but never used */ + return res; +} + +/* -------------------------------------------------------------------------- + * Test: what a thread saw of a dispatch does not outlive the pool. + * + * The main thread runs tasks of each dispatch and keeps, per thread, the + * columns it saw read and the rows it requested, under the generation of + * that dispatch. ray_pool_destroy zeroes the pool, and the pool made after + * it numbers its own dispatches: none of them may take that state for its + * own. Column B, read by the old pool's first dispatch and not by the new + * pool's first, must not be requested by the latter. + * -------------------------------------------------------------------------- */ + +/* As pf_walk over columns A and B (ctx: their bases): one page of each in + * the first block of every task. */ +static void pf_walk_both(void* ctx, uint32_t w, int64_t s, int64_t e) { + (void)w; + const int64_t* const* col = (const int64_t* const*)ctx; + const int64_t per = PF_ROWS / PF_TASKS; + for (int64_t t = s; t < e; t++) + for (int64_t r = t * per; r < (t + 1) * per; r += 8192) { + ray_pool_scan_at(PF_ROWS, r, (t + 1) * per); + if (r == t * per) pf_sink += col[0][r + 4096] + col[1][r + 4096]; + } +} + +static test_result_t test_scan_read_ahead_new_pool(void) { + ray_heap_init(); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + ray_pool_t* pool = ray_pool_get(); + TEST_ASSERT_NOT_NULL(pool); + test_result_t res = { TEST_PASS, NULL }; + uint8_t* base = NULL; + uint8_t* bbase = NULL; + size_t size = 0, bsize = 0; + + const char* paths[2] = { PF_PATH, PF_PATH_B }; + for (int k = 0; k < 2; k++) { + FILE* f = fopen(paths[k], "wb"); + TEST_ASSERT_NOT_NULL(f); + for (int64_t i = 0; i < PF_ROWS; i++) fwrite(&i, sizeof(i), 1, f); + fclose(f); + } + base = pf_map(PF_PATH, &size); + bbase = pf_map(PF_PATH_B, &bsize); + TEST_ASSERT_NOT_NULL(base); + TEST_ASSERT_NOT_NULL(bbase); + + if (!pool->scan_bytes) { res = (test_result_t){ TEST_SKIP, "RAY_SCAN_PREFETCH=0" }; goto out; } + if (!pf_evict() || ray_vm_resident(base, size) || !pf_none_resident(bbase, bsize)) { + res = (test_result_t){ TEST_SKIP, "page cache eviction has no effect here" }; + goto out; + } + + ray_pool_scan_t scan = { .base = { base, bbase }, .esz = { 8, 8 }, .n = 2, .rows = PF_ROWS }; + const ray_pool_scan_t* prev = ray_pool_scan_set(&scan); + const uint8_t* cols[2] = { base, bbase }; + ray_pool_dispatch_n(pool, pf_walk_both, cols, PF_TASKS); + + ray_pool_destroy(); + if (ray_pool_init_total(4) != RAY_OK || !(pool = ray_pool_get())) { + res = (test_result_t){ TEST_FAIL, "pool init" }; + goto restore; + } + if (!pf_reset(&base, &size, &bbase, &bsize, &scan)) { res = (test_result_t){ TEST_FAIL, "evict" }; goto restore; } + ray_pool_dispatch_n(pool, pf_walk, base, PF_TASKS); + if (!pf_wait_resident(base, size)) { + res = (test_result_t){ TEST_FAIL, "task-reported read-ahead left the rows unread" }; + goto restore; + } + if (!pf_none_resident(bbase, bsize)) { + res = (test_result_t){ TEST_FAIL, "a column only the old pool's dispatch read was requested" }; + goto restore; + } + +restore: + ray_pool_scan_set(prev); +out: + if (base) ray_vm_unmap_file(base, size); + if (bbase) ray_vm_unmap_file(bbase, bsize); + remove(PF_PATH); + remove(PF_PATH_B); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init(0), RAY_OK); + ray_heap_destroy(); + return res; +} + +/* -------------------------------------------------------------------------- + * Test: the passes of a query that first read a mapped column request it. + * + * A splayed table is written, evicted from the page cache and opened, and + * the column under test gets the kernel's read-ahead on faults turned off + * (MADV_RANDOM): each of its pages the query reads without having asked + * for it first is a major fault of its own. The pass that first reads the + * column asks for it: the scatter of the dense partitioned route (`sum v + * by k`, 256K key slots), the holistic reduce of the indexed route (`med w + * by k`), the gathers of a filtered group that compacts its rows (`count + * distinct x` and `med w` by g, where v > 30) and the pass of a filtered + * group over the selected rows (`sum w` by g, where v > 30). A column the select + * names and no pass reads is not asked for, however much of its start the + * kernel read along with its header. A per-group count distinct over rows + * a filter on a sorted column keeps together asks for the pages of those + * rows only, not for the whole column. + * -------------------------------------------------------------------------- */ +static char pq_dir[96], pq_tbl[104]; +static void pq_paths(void) { + if (pq_dir[0]) return; + snprintf(pq_dir, sizeof(pq_dir), "/tmp/rayforce_test_scan_q.%d", (int)getpid()); + snprintf(pq_tbl, sizeof(pq_tbl), "%s/t/", pq_dir); +} +#define PQ_DIR (pq_paths(), pq_dir) +#define PQ_TBL (pq_paths(), pq_tbl) + +static bool pq_ok(const char* src) { + ray_t* r = ray_eval_str(src); + bool ok = r && !RAY_IS_ERR(r); + if (r) ray_release(r); + return ok; +} + +/* Evict every file of the table. */ +static bool pq_evict(void) { + DIR* d = opendir(PQ_TBL); + if (!d) return false; + bool ok = true; + struct dirent* e; + char path[512]; + while ((e = readdir(d))) { + snprintf(path, sizeof(path), "%s%s", PQ_TBL, e->d_name); + struct stat st; + if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) ok &= pf_evict_one(path); + } + closedir(d); + return ok; +} + +/* Remove the tree at `path` (a table written again keeps generations). */ +static void pq_rm(const char* path) { + struct stat st; + if (lstat(path, &st) != 0) return; + if (S_ISDIR(st.st_mode)) { + DIR* d = opendir(path); + if (d) { + struct dirent* e; + char sub[512]; + while ((e = readdir(d))) { + if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue; + snprintf(sub, sizeof(sub), "%s/%s", path, e->d_name); + pq_rm(sub); + } + closedir(d); + } + rmdir(path); + } else { + remove(path); + } +} + +/* Open the table cold as M, with the kernel's read-ahead on faults off for + * column `name`; its data through *p, *n. 1 when eviction has no effect + * here, -1 on an error. */ +static int pq_open_cold(const char* name, const uint8_t** p, size_t* n) { + if (!pq_ok("(set M 0)") || !pq_evict()) return -1; + char src[192]; + snprintf(src, sizeof(src), "(set M (.db.splayed.get \"%s\"))", PQ_TBL); + if (!pq_ok(src)) return -1; + snprintf(src, sizeof(src), "(at M '%s)", name); + ray_t* col = ray_eval_str(src); + if (!col || RAY_IS_ERR(col) || col->mmod != 1 || col->len < 2048) { + if (col) ray_release(col); + return -1; + } + *p = (const uint8_t*)ray_data(col); + *n = (size_t)col->len * 8; + ray_release(col); /* M holds it */ + uintptr_t a = (uintptr_t)*p & ~(uintptr_t)4095; + posix_madvise((void*)a, (uintptr_t)*p + *n - a, POSIX_MADV_RANDOM); + /* Opening reads the header, and the kernel the pages after it. */ + return pf_none_resident(*p + (512 << 10), *n - (512 << 10)) ? 0 : 1; +} + +static long pq_majflt(void) { + struct rusage u; + getrusage(RUSAGE_SELF, &u); + return u.ru_majflt; +} + +static test_result_t test_scan_read_ahead_queries(void) { + char prev_prefetch[32] = ""; + bool prefetch_off = false; + { + const char* e = getenv("RAY_SCAN_PREFETCH"); + if (e) snprintf(prev_prefetch, sizeof(prev_prefetch), "%s", e); + } + ray_runtime_t* rt = ray_runtime_create(0, NULL); + TEST_ASSERT_NOT_NULL(rt); + uint32_t cores = ray_pool_total_workers(ray_pool_get()); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + test_result_t res = { TEST_PASS, NULL }; + static char msg[160]; + const uint8_t* p = NULL; + size_t n = 0; + int rc; + + if (!ray_pool_scan_on()) { res = (test_result_t){ TEST_SKIP, "RAY_SCAN_PREFETCH=0" }; goto out; } + char pq_set_src[192]; + snprintf(pq_set_src, sizeof(pq_set_src), "(.db.splayed.set \"%s\" T)", PQ_TBL); + pq_rm(PQ_DIR); + if (!pq_ok("(set N 1048576)") || + !pq_ok("(set T (table [k v w g x d] (list (% (* (til N) 7919) 262144) (* (til N) 3)" + " (* 0.5 (til N)) (% (til N) 100) (% (* (til N) 13) 50000) (/ (til N) 1024))))") || + !pq_ok(pq_set_src) || !pq_ok("(set T 0)")) { + res = (test_result_t){ TEST_FAIL, "table" }; + goto out; + } + + static const struct { const char* col; const char* query; const char* pass; } q[] = { + { "v", "(count (select {from: M s: (sum v) by: k}))", "dense partition scatter" }, + { "w", "(count (select {from: M m: (med w) by: k}))", "indexed holistic reduce" }, + { "w", "(count (select {from: M c: (count (distinct x)) m: (med w) by: g where: (> v 30)}))", + "filtered group gather" }, + { "w", "(count (select {from: M s: (sum w) by: g where: (> v 30)}))", "filtered dense group" }, + }; + for (size_t i = 0; i < sizeof(q) / sizeof(q[0]); i++) { + if ((rc = pq_open_cold(q[i].col, &p, &n))) { + res = rc > 0 ? (test_result_t){ TEST_SKIP, "page cache eviction has no effect here" } + : (test_result_t){ TEST_FAIL, "open" }; + goto out; + } + long before = pq_majflt(); + if (!pq_ok(q[i].query)) { res = (test_result_t){ TEST_FAIL, q[i].query }; goto out; } + long faults = pq_majflt() - before; + if (faults > (long)(n / 4096 / 4)) { + snprintf(msg, sizeof(msg), "%s: %ld major faults over %zu pages of %s", + q[i].pass, faults, n / 4096, q[i].col); + res = (test_result_t){ TEST_FAIL, msg }; + goto out; + } + } + + /* `count w` reads none of w, which the select registers all the same: + * the pages at its start the kernel read along with the header must not + * pass for a pass reading it, or the thread over the first rows asks + * for the next window of w. */ + if ((rc = pq_open_cold("w", &p, &n))) { + res = rc > 0 ? (test_result_t){ TEST_SKIP, "page cache eviction has no effect here" } + : (test_result_t){ TEST_FAIL, "open" }; + goto out; + } + if (!pq_ok("(count (select {from: M c: (count w) s: (sum v) by: g}))")) { + res = (test_result_t){ TEST_FAIL, "count w" }; + goto out; + } + if (pf_resident_pages(p + (512 << 10), n - (1024 << 10)) > 0) { + res = (test_result_t){ TEST_FAIL, "a column no pass read was requested" }; + goto out; + } + + /* d sorted, 1024 rows a value: the filter keeps the last 16K rows, the + * last 128 KiB of x. Nothing before them may be asked for (the start + * of the file was read with its header). */ + if ((rc = pq_open_cold("x", &p, &n))) { + res = rc > 0 ? (test_result_t){ TEST_SKIP, "page cache eviction has no effect here" } + : (test_result_t){ TEST_FAIL, "open" }; + goto out; + } + if (!pq_ok("(count (select {from: M c: (count (distinct x)) s: (sum v) by: g where: (within d [1008 1023])}))")) { + res = (test_result_t){ TEST_FAIL, "clustered count distinct" }; + goto out; + } + if (pf_resident_pages(p + n / 4, n / 2) > 0) { + res = (test_result_t){ TEST_FAIL, "count distinct over clustered rows asked for pages none of them is on" }; + goto out; + } + + /* RAY_SCAN_PREFETCH=0: nothing is asked for, so each page a query reads + * is faulted in by the query itself. The filter keeps one row in 4096, + * each on its own page of w, which w's held-back read would ask for; a + * per-group distinct count samples 1024 rows of its value column first + * (all of x but the 128 pages opening it read). */ + { + static const struct { const char* col; const char* query; const char* pass; long pages; } off[] = { + { "w", "(count (select {from: M s: (sum w) by: g where: (== (% v 4096) 7)}))", + "held-back column", 256 }, + { "x", "(count (select {from: M c: (count (distinct x)) by: g}))", + "distinct-count sample", 1920 }, + }; + setenv("RAY_SCAN_PREFETCH", "0", 1); + prefetch_off = true; + ray_pool_destroy(); + for (size_t i = 0; i < sizeof(off) / sizeof(off[0]); i++) { + if ((rc = pq_open_cold(off[i].col, &p, &n))) { + res = rc > 0 ? (test_result_t){ TEST_SKIP, "page cache eviction has no effect here" } + : (test_result_t){ TEST_FAIL, "open" }; + goto out; + } + long before = pq_majflt(); + if (!pq_ok(off[i].query)) { res = (test_result_t){ TEST_FAIL, off[i].query }; goto out; } + long faults = pq_majflt() - before; + if (faults < off[i].pages * 3 / 4) { + snprintf(msg, sizeof(msg), "%s asked for pages with read-ahead off: %ld major faults over %ld pages read of %s", + off[i].pass, faults, off[i].pages, off[i].col); + res = (test_result_t){ TEST_FAIL, msg }; + goto out; + } + } + } + +out: + if (prefetch_off) { + if (prev_prefetch[0]) setenv("RAY_SCAN_PREFETCH", prev_prefetch, 1); + else unsetenv("RAY_SCAN_PREFETCH"); + } + pq_ok("(set M 0)"); + pq_rm(PQ_DIR); + ray_runtime_destroy(rt); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(cores), RAY_OK); + return res; +} +#endif + const test_entry_t pool_entries[] = { #if defined(__linux__) || defined(__APPLE__) { "pool/auto_all_logical_cpus", test_auto_all_logical_cpus, NULL, NULL }, @@ -1675,6 +2421,10 @@ const test_entry_t pool_entries[] = { { "pool/zero_workers", test_pool_zero_workers, NULL, NULL }, { "pool/total_workers", test_pool_total_workers, NULL, NULL }, { "pool/init_total", test_pool_init_total, NULL, NULL }, + { "pool/workers_started", test_pool_workers_started, NULL, NULL }, +#if defined(__linux__) + { "pool/sk_spawn_fails", test_pool_sk_spawn_fails, NULL, NULL }, +#endif { "pool/free_null", test_pool_free_null, NULL, NULL }, { "pool/init_idempotent", test_pool_init_idempotent, NULL, NULL }, { "pool/destroy_reinit", test_pool_destroy_and_reinit, NULL, NULL }, @@ -1697,6 +2447,9 @@ const test_entry_t pool_entries[] = { { "pool/epoll_sel_cap_growth", test_epoll_sel_cap_growth, NULL, NULL }, { "pool/epoll_hup_branch", test_epoll_hup_branch, NULL, NULL }, { "pool/epoll_hup_no_errfn", test_epoll_hup_no_errfn, NULL, NULL }, + { "pool/scan_read_ahead", test_scan_read_ahead, NULL, NULL }, + { "pool/scan_read_ahead_new_pool", test_scan_read_ahead_new_pool, NULL, NULL }, + { "pool/scan_read_ahead_queries", test_scan_read_ahead_queries, NULL, NULL }, #endif { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_runtime.c b/test/test_runtime.c index d100fdb0f..c3a11cddd 100644 --- a/test/test_runtime.c +++ b/test/test_runtime.c @@ -319,7 +319,8 @@ static test_result_t test_oom_sentinel_is_well_formed(void) { /* 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. */ + * default watermark must resolve to it less the page-cache room: a quarter, + * at least 3 GiB, at most half (#712). */ 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); @@ -333,8 +334,12 @@ static test_result_t test_ram_limit_caps_total_ram(void) { 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); + int64_t room = limit / 4; + if (room < (INT64_C(3) << 30)) room = INT64_C(3) << 30; + if (room > limit / 2) room = limit / 2; + int64_t want = limit - room; + TEST_ASSERT_EQ_I(ray_heap_anon_watermark(), want); + ray_heap_set_anon_watermark(previous == want ? 0 : previous); ray_runtime_destroy(rt); PASS(); } diff --git a/test/test_select_merge.c b/test/test_select_merge.c new file mode 100644 index 000000000..7f019f63c --- /dev/null +++ b/test/test_select_merge.c @@ -0,0 +1,219 @@ +/* Nested select composition: admission and serialized differential checks. */ +#include "test.h" +#include "lang/eval.h" +#include "lang/env.h" +#include "ops/internal.h" +#include "store/serde.h" +#include "core/runtime.h" + +extern ray_runtime_t* __RUNTIME; +static void setup(void) { ray_runtime_create(0, NULL); } +static void teardown(void) { ray_runtime_destroy(__RUNTIME); } + +static void drop(ray_t* x) { + if (x && RAY_IS_ERR(x)) ray_error_free(x); + else if (x) ray_release(x); +} + +/* `do` preserves evaluation but hides each literal nested select from the + * rewrite. The reference exercises the old materializing execution path. */ +static void materialized(const char* src, char* dst) { + while (*src) { + if (!strncmp(src, "from: (select", 13)) { + memcpy(dst, "from: (do ", 10); dst += 10; src += 6; + const char* start = src; + int depth = 0; + do { if (*src == '(') depth++; if (*src == ')') depth--; src++; } while (*src && depth); + size_t len = (size_t)(src - start); + char inner[4096]; + memcpy(inner, start, len); inner[len] = 0; + materialized(inner, dst); dst += strlen(dst); + *dst++ = ')'; + } else *dst++ = *src++; + } + *dst = 0; +} + +static test_result_t test_select_merge_cases(void) { + ray_t* t = ray_eval_str("(set T (table [a b k p s text] (list [0 1 1 0 1] [1 1 0 1 1] [0 1 0 1 0] [1.0 2.0 0Nf 4.0 5.0] [' alpha beta alpha beta] [\"\" \"a\" \"b\" \"a\" \"b\"])))"); + TEST_ASSERT(t && !RAY_IS_ERR(t), "fixture"); drop(t); + t = ray_eval_str("(set T (take T 10000))"); + TEST_ASSERT(t && !RAY_IS_ERR(t), "multi-morsel fixture"); drop(t); + const struct { const char* query; bool merge; } cases[] = { + {"{from: (select {from: T where: (== a 1)}) where: (== b 1) total: (sum p)}", false}, + {"{from: (select {from: T where: (== a 1)}) where: (== b 1) by:k total: (sum p)}", true}, + {"{from: (select {from: T where: (== a 1) a:a b:b k:k p:p s:s text:text q:(* p 2)}) by:k total:(sum q)}", true}, + {"{from: (select {from: T where: (== a 1) p:p k:k}) take: 2}", true}, + {"{from: (select {from: T a:a b:b k:k p:p s:s text:text}) where:(== a 1) total:(sum p)}", true}, + {"{from: (select {from: T where:(== s 'beta)}) where:(== text \"b\") p:p s:s text:text}", true}, + {"{from: (select {from: T where:(== a 9)}) p:p s:s text:text}", true}, + {"{from: (select {from: T where:(== a 9) a:a p:p}) where:(> p 3) total:(sum p)}", false}, + {"{from: (select {from: T k:k q:(* p 2) r:(* q 3)}) by:k total:(sum r) asc:k}", true}, + {"{from: (select {from: T p:p q:(- p 0.7)}) where:(== p 0Nf) total:(sum q)}", false}, + {"{from: (select {from: T q:(+ a 1)}) total:(sum q)}", false}, + {"{from: (select {from: T z:p k:k}) total:(sum z)}", true}, + {"{from: (select {from: T z:p k:k}) total:(sum 'z)}", true}, + {"{from: (select {from: T k:k q:(* p 2)}) total:(sum q) desc:total take:1}", true}, + {"{from: (select {from: T k:k q:(* p 2)}) where:(> q 3)}", false}, + {"{from: (select {from: (select {from: T where:(== a 1)}) where:(== b 1)}) total:(sum p)}", false}, + {"{from: (select {from: T where:(== a 1)}) p:p desc:p take:2}", true}, + /* Aggregates/windows/length changes cannot move across an outer filter. */ + {"{from: (select {from: T p:p q:(- p (avg p))}) where:(> p 1) q:q}", false}, + {"{from: (select {from: T p:p q:(sums p)}) where:(> p 1) q:q}", false}, + {"{from: (select {from: T p:p q:(reverse p)}) where:(> p 1) q:q}", false}, + {"{from: (select {from: T p:p q:42}) where:(> p 1) q:q}", false}, + {"{from: (select {from: T p:p q:(/ p 0)}) where:(> p 1) q:q}", false}, + /* Preserve missing names, dropped outputs, lexical scope and errors. */ + {"{from: (select {from: T p:p}) a:a}", false}, + {"{from: (select {from: T p:p missing:missing}) p:p}", false}, + {"{from: (select {from: T p:p bad:(as 'I64 text)}) p:p}", false}, + {"{from: (select {from: T p:p q:(* p 2)}) p:p}", false}, + {"{from: (select {from: T p:p}) s:'a}", false}, + {"{from: (select {from: T p:p}) asc:a}", false}, + {"{from: (select {from: T p:p}) q:(sum a)}", false}, + {"{from: (select {from: T a:(+ a 1) p:p}) where:(== a 1) p:p}", false}, + {"{from: (select {from: T q:(* p 2)}) p:(+ q 1) r:q}", false}, + {"{from: (select {from: T p:p}) q:(+ p 1) r:(+ q 1)}", false}, + {"{from: (select {from: T take:2}) p:p}", false}, + {"{from: (select {from: T desc:p}) p:p}", false}, + {"{from: (select {from: T by:k total:(sum p)}) total:total}", false}, + {"{from: (select {from: T where:(== a 1)}) where:(== b 1) take:2}", false}, + {"{from: (select {from: (do T) where:(== a 1)}) p:p}", false}, + {"{from: (select {from: T p:p}) by:a total:(sum p)}", false}, + {"{from: (select {from: T p:p}) where:(> a 1) p:p}", false}, + {"{from: (select {from: T p:p s:s text:text q:(* p 2)}) where:(== text \"b\") take:3}", false}, + {"{from: (select {from: T where:(> p 3)}) take:3}", false}, + }; + for (size_t i = 0; i < sizeof(cases)/sizeof(cases[0]); i++) { + char src[4096], ref[8192]; + snprintf(src, sizeof(src), "(quote %s)", cases[i].query); + ray_t* dict = ray_eval_str(src); + TEST_ASSERT(dict && !RAY_IS_ERR(dict), "query AST"); + ray_t* plan = ray_select_merge_plan(dict); + TEST_ASSERT_FMT((plan != NULL) == cases[i].merge, "admission case %zu: %s", i, cases[i].query); + drop(plan); drop(dict); + snprintf(src, sizeof(src), "(select %s)", cases[i].query); + materialized(src, ref); + ray_t* got = ray_eval_str(src); + char got_error[512] = {0}; + if (RAY_IS_ERR(got) && ray_error_msg()) snprintf(got_error, sizeof(got_error), "%s", ray_error_msg()); + ray_t* want = ray_eval_str(ref); + TEST_ASSERT_FMT(got && want && RAY_IS_ERR(got) == RAY_IS_ERR(want), "error parity case %zu", i); + if (RAY_IS_ERR(got)) { + TEST_ASSERT_FMT(got->slen == want->slen && !memcmp(got->sdata, want->sdata, got->slen), "error code case %zu", i); + const char* want_error = ray_error_msg(); + TEST_ASSERT_FMT(!strcmp(got_error, want_error ? want_error : ""), "error message case %zu: %s / %s", i, got_error, want_error ? want_error : ""); + } else { + ray_t* a = ray_ser(got), *b = ray_ser(want); + TEST_ASSERT(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b), "serialization"); + TEST_ASSERT_FMT(a->len == b->len && !memcmp(ray_data(a), ray_data(b), a->len), "result parity case %zu: %.1000s", i, src); + drop(a); drop(b); + } + drop(got); drop(want); + } + PASS(); +} + +static test_result_t test_select_merge_scopes(void) { + ray_t* t = ray_eval_str("(set T (table [a p] (list [0 1 1] [1.0 2.0 3.0])))"); + TEST_ASSERT(t && !RAY_IS_ERR(t), "fixture"); drop(t); + t = ray_eval_str("(set T (take T 10000))"); + TEST_ASSERT(t && !RAY_IS_ERR(t), "multi-morsel fixture"); drop(t); + ray_t* dict = ray_eval_str("(quote {from: (select {from:T where:(== a 1)}) where:(> p 0) by:a total:(sum p)})"); + TEST_ASSERT(dict && !RAY_IS_ERR(dict), "AST"); + ray_t* before = ray_ser(dict); + const char* names[] = {"a", "p", "==", "select", "T"}; + for (size_t i = 0; i < sizeof(names)/sizeof(names[0]); i++) { + ray_env_push_scope(); + ray_t* v = ray_i64(42); + ray_env_set_local(ray_sym_intern(names[i], strlen(names[i])), v); + drop(v); + ray_t* plan = ray_select_merge_plan(dict); + TEST_ASSERT(!plan, "lexical/builtin shadow is a merge barrier"); + ray_env_pop_scope(); + } + ray_t* plan = ray_select_merge_plan(dict); + TEST_ASSERT(plan && !RAY_IS_ERR(plan), "ordinary query merges"); drop(plan); + ray_t* after = ray_ser(dict); + TEST_ASSERT(before && after && !RAY_IS_ERR(before) && !RAY_IS_ERR(after), "AST serialization"); + TEST_ASSERT(before->len == after->len && !memcmp(ray_data(before), ray_data(after), before->len), "rewrite leaves shared AST unchanged"); + drop(before); drop(after); drop(dict); + /* A short alias chain can represent an exponentially large expression. */ + char source[2048]; + size_t len = (size_t)snprintf(source, sizeof(source), "(quote {from:(select {from:T q0:(+ p p)"); + for (int i = 1; i <= 20; i++) + len += (size_t)snprintf(source + len, sizeof(source) - len, " q%d:(+ q%d q%d)", i, i - 1, i - 1); + snprintf(source + len, sizeof(source) - len, "}) total:(sum q20)})"); + dict = ray_eval_str(source); + TEST_ASSERT(dict && !RAY_IS_ERR(dict), "alias chain AST"); + plan = ray_select_merge_plan(dict); + TEST_ASSERT(!plan, "bound alias expansion work"); drop(dict); + ray_t* r = ray_eval_str("(do (set calls 0) (select {from:(select {from:(do (set calls (+ calls 1)) T) where:(== a 1)}) total:(sum p)}) calls)"); + TEST_ASSERT(r && !RAY_IS_ERR(r) && r->type == -RAY_I64 && r->i64 == 1, "source evaluates once"); + drop(r); + PASS(); +} + +static test_result_t test_select_merge_review(void) { + ray_t* r = ray_eval_str("(set T (table [p b] (list (as 'F64 (til 20000)) (% (til 20000) 7))))"); + TEST_ASSERT(r && !RAY_IS_ERR(r), "ramp fixture"); drop(r); + r = ray_eval_str("(set D (take (table [f] (list [1.7976931348623157e308 -1.7976931348623157e308 1.0])) 10002))"); + TEST_ASSERT(r && !RAY_IS_ERR(r), "overflow fixture"); drop(r); + r = ray_eval_str("(set E (take (table [f g k] (list [1e300 1e10 -1e300 3.0] [1e300 2.0 1e300 4.0] [0 1 0 1])) 10000))"); + TEST_ASSERT(r && !RAY_IS_ERR(r), "product overflow fixture"); drop(r); + r = ray_eval_str("(set M (take (table [i] (list [4611686018427387904 1])) 10000))"); + TEST_ASSERT(r && !RAY_IS_ERR(r), "mixed intermediate fixture"); drop(r); + r = ray_eval_str("(set S (take T 10))"); + TEST_ASSERT(r && !RAY_IS_ERR(r), "small fixture"); drop(r); + const struct { const char* query; bool merge; } cases[] = { + {"{from: (select {from:D c:(+ f 1e300)}) total:(sum c)}", false}, + {"{from: (select {from:D c:(+ f 1e300)}) total:(avg c)}", false}, + {"{from: (select {from:E c:(* f g)}) total:(sum c)}", false}, + {"{from: (select {from:E c:(* f g)}) total:(avg c)}", false}, + {"{from: (select {from:E c:(* f f)}) total:(sum c)}", false}, + {"{from: (select {from:E k:k c:(* f g)}) by:k total:(sum c)}", false}, + {"{from: (select {from:E c:(* (* f 2) g)}) total:(sum c)}", false}, + {"{from: (select {from:M c:(* (* i 2) 1.0)}) total:(sum c)}", false}, + {"{from: (select {from:E c:(* f g)}) c:c}", true}, + {"{from: (select {from:T where:(== b 1)}) where:(> p 5) total:(sum p)}", false}, + {"{from: (select {from:T where:(< b 3)}) where:(> p 5) total:(avg p)}", false}, + {"{from: (select {from:T where:(== b 1)}) total:(sum p)}", false}, + {"{from: (select {from:T where:(> b 3)}) total:(count p)}", false}, + {"{from: (select {from:T where:(> p 19990.0)}) by:b total:(sum p)}", false}, + {"{from: (select {from:T where:(== p 15000.0)}) by:b total:(sum p)}", false}, + {"{from: (select {from:T where:(> p 20000.0)}) by:b total:(sum p)}", false}, + {"{from: (select {from:T where:(> p 20000.0)}) by:b p:p}", true}, + {"{from: (select {from:T where:(> p 19990.0)}) by:b p:p}", true}, + {"{from: (select {from:T where:(== p 63.0)}) by:b total:(sum p)}", true}, + {"{from: (select {from:T where:(== p 64.0)}) by:b total:(sum p)}", false}, + {"{from: (select {from: (select {from:T where:(> p 19990.0)}) by:b total:(sum p)}) total:total}", false}, + {"{from: (select {from:T q0:(* p 1.0001) q1:(+ q0 q0) q2:(+ q1 q1) q3:(+ q2 q2) q4:(+ q3 q3) q5:(+ q4 q4)}) where:(> q5 1) v:q5}", false}, + {"{from: (select {from:T q:(* p 2)}) a:q b:q}", false}, + {"{from: (select {from:S where:(> p 1)}) take:2}", false}, + }; + for (size_t i = 0; i < sizeof(cases)/sizeof(cases[0]); i++) { + char source[4096], reference[8192]; + snprintf(source, sizeof(source), "(quote %s)", cases[i].query); + ray_t* dict = ray_eval_str(source); + TEST_ASSERT(dict && !RAY_IS_ERR(dict), "review AST"); + ray_t* plan = ray_select_merge_plan(dict); + TEST_ASSERT_FMT((plan != NULL) == cases[i].merge, "review admission case %zu", i); + drop(plan); drop(dict); + snprintf(source, sizeof(source), "(select %s)", cases[i].query); + materialized(source, reference); + ray_t* got = ray_eval_str(source), *want = ray_eval_str(reference); + TEST_ASSERT_FMT(got && want && !RAY_IS_ERR(got) && !RAY_IS_ERR(want), "review query case %zu", i); + ray_t* a = ray_ser(got), *b = ray_ser(want); + TEST_ASSERT(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b), "review serialization"); + TEST_ASSERT_FMT(a->len == b->len && !memcmp(ray_data(a), ray_data(b), a->len), "review result case %zu", i); + drop(a); drop(b); drop(got); drop(want); + } + PASS(); +} + +const test_entry_t select_merge_entries[] = { + {"select_merge/cases", test_select_merge_cases, setup, teardown}, + {"select_merge/scopes", test_select_merge_scopes, setup, teardown}, + {"select_merge/review", test_select_merge_review, setup, teardown}, + {NULL, NULL, NULL, NULL}, +}; diff --git a/test/test_splay.c b/test/test_splay.c index 346f3fd75..6c12a2a92 100644 --- a/test/test_splay.c +++ b/test/test_splay.c @@ -44,6 +44,8 @@ #include "io/csv.h" /* ray_csv_save_splayed_named_opts */ #include "mem/sys.h" #include "core/pool.h" +#include "ops/idxop.h" /* hash indexes a save builds in place */ +#include #include #include #include @@ -1373,10 +1375,11 @@ 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); - /* Old readers can still open b; the new generation has only a. */ + /* The new generation has only a; the first write's b is removed with + * the rest of its columns (a reader that resolved them resolves again). */ char bpath[512]; snprintf(bpath, sizeof(bpath), "%s/b", dir); - TEST_ASSERT_EQ_I(access(bpath, F_OK), 0); + TEST_ASSERT_EQ_I(access(bpath, F_OK), -1); ray_t* loaded = ray_splay_load(dir, NULL); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); @@ -2556,27 +2559,10 @@ static test_result_t test_generation_prune_unlinks_symlink(void) { 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'); + /* The selected generation is the one the next publish removes. */ + char prune_dir[1024]; + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(dir, prune_dir, sizeof(prune_dir)), RAY_OK); + int n; TEST_ASSERT_EQ_I(ray_test_mkdir_p(victim), 0); FILE* f = fopen(victim_file, "wb"); @@ -2661,47 +2647,411 @@ static test_result_t test_generation_io_failures(void) { /* 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); + TEST_ASSERT_EQ_I(generation_dir_count(dir), 1); ray_release(next); ray_release(old); rm_rf(dir); PASS(); } -static test_result_t test_generation_retains_readers(void) { +/* Only the selected generation is kept. A table mapped before a replacement + * stays readable after its files are removed; a new read sees the new one. */ +static test_result_t test_generation_keeps_only_current(void) { const char* dir = TMP_SPLAY_BASE "/generation_readers"; 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]; + /* era 0: the first write's root files; era 1: a generation. */ + char resolved[1024], schema[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); + snprintf(schema, sizeof(schema), "%s/.d", resolved); + TEST_ASSERT_EQ_I(access(schema, F_OK), -1); +#ifndef _WIN32 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); +#endif ray_release(pinned); TEST_ASSERT_TRUE(generation_matches(dir, false, 9)); + TEST_ASSERT_TRUE(generation_matches(dir, true, 9)); + TEST_ASSERT_EQ_I(generation_dir_count(dir), 1); TEST_ASSERT_EQ_I(ray_splay_save(old, dir, NULL), RAY_OK); } - TEST_ASSERT_TRUE(generation_dir_count(dir) <= 2); + TEST_ASSERT_EQ_I(generation_dir_count(dir), 1); ray_release(next); ray_release(old); rm_rf(dir); PASS(); } +/* Names in dir other than "." and "..", sorted, joined by spaces. */ +static void dir_listing(const char* dir, char* out, size_t out_sz) { + char names[32][256]; + int count = 0; + out[0] = '\0'; + DIR* d = opendir(dir); + if (!d) return; + struct dirent* entry; + while ((entry = readdir(d)) && count < 32) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) + continue; + snprintf(names[count++], sizeof(names[0]), "%s", entry->d_name); + } + closedir(d); + for (int i = 0; i < count; i++) + for (int j = i + 1; j < count; j++) + if (strcmp(names[i], names[j]) > 0) { + char t[256]; + memcpy(t, names[i], sizeof(t)); + memcpy(names[i], names[j], sizeof(t)); + memcpy(names[j], t, sizeof(t)); + } + size_t used = 0; + for (int i = 0; i < count; i++) { + int n = snprintf(out + used, out_sz - used, "%s%s", i ? " " : "", names[i]); + if (n < 0 || (size_t)n >= out_sz - used) return; + used += (size_t)n; + } +} + +/* Issue 713: a table replaced three times holds one copy of itself. The + * first write's columns and their sidecars go at the first publish; the + * symfile and the lock file stay. */ +static test_result_t test_generation_first_write_removed(void) { + const char* dir = TMP_SPLAY_BASE "/generation_first_write"; + rm_rf(dir); + int64_t s_id = ray_sym_intern("s", 1); + ray_t* t = generation_pair(1); + ray_t* sv = ray_vec_new(RAY_SYM, 2); + int64_t a = ray_sym_intern("a", 1), b = ray_sym_intern("b", 1); + sv = ray_vec_append(sv, &a); + sv = ray_vec_append(sv, &b); + t = ray_table_add_col(t, s_id, sv); + ray_release(sv); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + char sym[1100]; + snprintf(sym, sizeof(sym), "%s/.sym", dir); + TEST_ASSERT_EQ_I(ray_splay_save(t, dir, sym), RAY_OK); + /* A sidecar of a first-write column goes with it. */ + FILE* f = fopen(TMP_SPLAY_BASE "/generation_first_write/x.link", "wb"); + TEST_ASSERT_NOT_NULL(f); + fputs("other", f); + fclose(f); + for (int i = 0; i < 3; i++) + TEST_ASSERT_EQ_I(ray_splay_save(t, dir, sym), RAY_OK); + + char listing[512]; + dir_listing(dir, listing, sizeof(listing)); + TEST_ASSERT_STR_EQ(listing, ".current .generations .sym .sym.lk .write.lock"); + TEST_ASSERT_EQ_I(generation_dir_count(dir), 1); + ray_t* loaded = ray_read_splayed(dir, sym); + TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); + TEST_ASSERT_EQ_I(ray_table_nrows(loaded), 2); + ray_t* ls = ray_table_get_col(loaded, s_id); + TEST_ASSERT_NOT_NULL(ls); + TEST_ASSERT_EQ_I(ls->type, RAY_SYM); + TEST_ASSERT_EQ_I(ls->len, 2); + ray_release(loaded); + ray_release(t); + rm_rf(dir); + PASS(); +} + +/* A table first written into a directory that holds other things (the + * database root of new/../db/) loses only the columns its schema named: + * not a partition, not a file named like no column of it. */ +static test_result_t test_generation_first_write_keeps_others(void) { + const char* dir = TMP_SPLAY_BASE "/generation_shared_root"; + rm_rf(dir); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(TMP_SPLAY_BASE "/generation_shared_root/2026.10.05/t"), 0); + FILE* f = fopen(TMP_SPLAY_BASE "/generation_shared_root/2026.10.05/t/keep", "wb"); + TEST_ASSERT_NOT_NULL(f); + fclose(f); + ray_t* one = generation_pair(1); + ray_t* two = generation_pair(2); + TEST_ASSERT_EQ_I(ray_splay_save(one, dir, NULL), RAY_OK); + f = fopen(TMP_SPLAY_BASE "/generation_shared_root/notes", "wb"); + TEST_ASSERT_NOT_NULL(f); + fclose(f); + TEST_ASSERT_EQ_I(ray_splay_save(two, dir, NULL), RAY_OK); + char listing[512]; + dir_listing(dir, listing, sizeof(listing)); + TEST_ASSERT_STR_EQ(listing, ".current .generations .write.lock 2026.10.05 notes"); + TEST_ASSERT_EQ_I(access(TMP_SPLAY_BASE "/generation_shared_root/2026.10.05/t/keep", F_OK), 0); + TEST_ASSERT_TRUE(generation_matches(dir, true, 2)); + ray_release(two); + ray_release(one); + rm_rf(dir); + PASS(); +} + +#ifndef _WIN32 +#include +#include +#include +#include + +/* The publisher of test_generation_reader_races, as a writer that keeps no + * previous generation: make a fresh generation (hard links to the template), + * select it, remove the one it replaced. Names are never reused, as the + * writer's are not. Plain libc only: it runs in a forked child. */ +static void generation_flip_child(const char* dir, const char* tmpl, int flips) { + const char* names[] = {".d", "x", "y"}; + struct timespec pause = {0, 100 * 1000}; + for (int i = 1; i <= flips; i++) { + char tmp[1100], cur[1100], path[1200], src[1200]; + snprintf(path, sizeof(path), "%s/.generations/g-%d", dir, i); + if (mkdir(path, 0755) != 0) _exit(1); + for (size_t k = 0; k < 3; k++) { + snprintf(src, sizeof(src), "%s/%s", tmpl, names[k]); + snprintf(path, sizeof(path), "%s/.generations/g-%d/%s", dir, i, names[k]); + if (link(src, path) != 0) _exit(1); + } + snprintf(tmp, sizeof(tmp), "%s/.current.tmp", dir); + snprintf(cur, sizeof(cur), "%s/.current", dir); + FILE* f = fopen(tmp, "wb"); + if (!f) _exit(1); + fprintf(f, ".generations/g-%d\n", i); + fclose(f); + if (rename(tmp, cur) != 0) _exit(1); + for (size_t k = 0; k < 3; k++) { + snprintf(path, sizeof(path), "%s/.generations/g-%d/%s", dir, i - 1, names[k]); + (void)unlink(path); + } + snprintf(path, sizeof(path), "%s/.generations/g-%d", dir, i - 1); + (void)rmdir(path); + nanosleep(&pause, NULL); + } + _exit(0); +} + +/* A reader whose generation is removed before it opened every file resolves + * again and reads the selected one: no read fails while another process + * publishes and prunes. */ +static test_result_t test_generation_reader_races(void) { + const char* dir = TMP_SPLAY_BASE "/generation_race"; + const char* tmpl = TMP_SPLAY_BASE "/generation_race_tmpl"; + rm_rf(dir); + rm_rf(tmpl); + ray_t* t = generation_pair(1); + TEST_ASSERT_EQ_I(ray_splay_save(t, dir, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(t, dir, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(t, tmpl, NULL), RAY_OK); + /* The child removes g-0 first: the table's own generation is moved there. */ + char resolved[1024], g0[1100]; + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(dir, resolved, sizeof(resolved)), RAY_OK); + snprintf(g0, sizeof(g0), "%s/.generations/g-0", dir); + TEST_ASSERT_EQ_I(rename(resolved, g0), 0); + FILE* f = fopen(TMP_SPLAY_BASE "/generation_race/.current", "wb"); + TEST_ASSERT_NOT_NULL(f); + fputs(".generations/g-0\n", f); + fclose(f); + + fflush(NULL); + pid_t child = fork(); + TEST_ASSERT_TRUE(child >= 0); + if (child == 0) generation_flip_child(dir, tmpl, 3000); + + int reads = 0, failures = 0, status = 0; + while (waitpid(child, &status, WNOHANG) == 0) { + ray_t* m = ray_read_splayed(dir, NULL); + if (!m || RAY_IS_ERR(m) || ray_table_nrows(m) != 2) failures++; + if (m && RAY_IS_ERR(m)) ray_error_free(m); else if (m) ray_release(m); + ray_t* c = ray_splay_load(dir, NULL); + if (!c || RAY_IS_ERR(c) || ray_table_nrows(c) != 2) failures++; + if (c && RAY_IS_ERR(c)) ray_error_free(c); else if (c) ray_release(c); + if (!ray_splay_has_schema(dir)) failures++; + reads++; + } + TEST_ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0); + TEST_ASSERT_TRUE(reads > 0); + TEST_ASSERT_EQ_I(failures, 0); + ray_release(t); + rm_rf(dir); + rm_rf(tmpl); + PASS(); +} + +/* The writer of test_generation_retry_releases_domain. .current is a FIFO, + * so each resolve of the reader waits here: the first gets g-1, the second + * (the reader asking whether the table moved on) gets g-2 once the symfile + * is gone, and every later one reads the plain file `last` puts in place. + * Plain libc only: it runs in a forked child. */ +static void held_domain_child(const char* cur, const char* next, + const char* last, const char* sym) { + const char* gens[] = {".generations/g-1\n", ".generations/g-2\n"}; + const char* repl[] = {next, last}; + for (int i = 0; i < 2; i++) { + int fd = open(cur, O_WRONLY); + if (fd < 0) _exit(1); + if (i == 1 && unlink(sym) != 0) _exit(1); + if (rename(repl[i], cur) != 0) _exit(1); + size_t len = strlen(gens[i]); + if (write(fd, gens[i], len) != (ssize_t)len) _exit(1); + close(fd); + } + _exit(0); +} + +static test_result_t held_domain_run(const char* base, pid_t* child) { + char t[1100], sym[1100], sdir[1100], src[1100]; + char g1[1200], g2[1200], cur[1200], next[1200], last[1200], resolved[1024]; + snprintf(t, sizeof(t), "%s/t", base); + snprintf(sym, sizeof(sym), "%s/t.sym", base); + snprintf(sdir, sizeof(sdir), "%s/s", base); + snprintf(src, sizeof(src), "%s/src", base); + snprintf(g1, sizeof(g1), "%s/.generations/g-1", t); + snprintf(g2, sizeof(g2), "%s/.generations/g-2", t); + snprintf(cur, sizeof(cur), "%s/.current", t); + snprintf(next, sizeof(next), "%s/.current.next", t); + snprintf(last, sizeof(last), "%s/.current.last", t); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(g1), 0); /* no .d: attempt 1 fails */ + + /* The symfile, written by a table with a SYM column. */ + ray_t* sc = ray_sym_vec_new(RAY_SYM_W64, 1); + TEST_ASSERT_FALSE(RAY_IS_ERR(sc)); + sc->len = 1; + ((int64_t*)ray_data(sc))[0] = ray_sym_intern("held_a", 6); + ray_t* st = ray_table_add_col(ray_table_new(1), ray_sym_intern("s", 1), sc); + ray_release(sc); + ray_err_t err = ray_splay_save(st, sdir, sym); + ray_release(st); + TEST_ASSERT_EQ_I(err, RAY_OK); + + /* g-2 has no SYM column: it reads without the symfile. */ + ray_t* pair = generation_pair(2); + err = ray_splay_save(pair, src, NULL); + ray_release(pair); + TEST_ASSERT_EQ_I(err, RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(src, resolved, sizeof(resolved)), RAY_OK); + TEST_ASSERT_EQ_I(rename(resolved, g2), 0); + + FILE* f = fopen(last, "wb"); + TEST_ASSERT_NOT_NULL(f); + fputs(".generations/g-2\n", f); + TEST_ASSERT_EQ_I(fclose(f), 0); + if (mkfifo(cur, 0644) != 0 || mkfifo(next, 0644) != 0) + SKIP("mkfifo unavailable"); + + fflush(NULL); + *child = fork(); + if (*child < 0) SKIP("fork unavailable"); + if (*child == 0) held_domain_child(cur, next, last, sym); + + ray_t* m = ray_read_splayed(t, sym); + bool loaded = m && !RAY_IS_ERR(m) && ray_table_nrows(m) == 2; + if (m && RAY_IS_ERR(m)) ray_error_free(m); else if (m) ray_release(m); + /* The plain file is in place only if the read came back for g-2. */ + struct stat cs; + TEST_ASSERT_TRUE(stat(cur, &cs) == 0 && S_ISREG(cs.st_mode)); + int status = 0; + TEST_ASSERT_TRUE(waitpid(*child, &status, 0) == *child); + *child = -1; + TEST_ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0); + TEST_ASSERT_TRUE(loaded); + + /* No table holds the symfile's domain now. One the read kept would stay + * cached for the path and not open over the removed file. */ + ray_sym_domain_t* d = ray_sym_domain_open_or_create(sym); + bool released = d != NULL; + ray_sym_domain_release(d); + TEST_ASSERT_TRUE(released); + PASS(); +} + +/* A read retried after its generation was replaced lets go of the symfile + * domain an earlier attempt opened, also when the retry finds the symfile + * gone. */ +static test_result_t test_generation_retry_releases_domain(void) { + char base[256]; + snprintf(base, sizeof(base), "/tmp/rayforce_test_splay_held_%ld", (long)getpid()); + rm_rf(base); + pid_t child = -1; + test_result_t r = held_domain_run(base, &child); + if (child > 0) { + kill(child, SIGKILL); + waitpid(child, NULL, 0); + } + rm_rf(base); + return r; +} + +/* A reader of a table whose every generation is broken (y shorter than x) + * while another process keeps publishing them retries for as long as the + * table changes; an interrupt stops it at once, and the read returns an + * error, not a table. Columns of a million rows make each copying attempt + * slower than one publish, so the table has always moved on by the time an + * attempt fails. */ +static test_result_t test_generation_reader_interrupted(void) { + const char* dir = TMP_SPLAY_BASE "/generation_cancel"; + const char* tmpl = TMP_SPLAY_BASE "/generation_cancel_tmpl"; + rm_rf(dir); + rm_rf(tmpl); + const int64_t n = 1000000; + ray_t* xc = ray_vec_new(RAY_I64, n); + xc->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(xc))[i] = i; + 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), xc); + ray_release(xc); + TEST_ASSERT_EQ_I(ray_splay_save(t, dir, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(t, dir, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(t, tmpl, NULL), RAY_OK); + char resolved[1024], g0[1100], g0y[1200]; + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(dir, resolved, sizeof(resolved)), RAY_OK); + snprintf(g0, sizeof(g0), "%s/.generations/g-0", dir); + TEST_ASSERT_EQ_I(rename(resolved, g0), 0); + snprintf(g0y, sizeof(g0y), "%s/y", g0); + ray_t* short_y = ray_vec_new(RAY_I64, n - 1); + short_y->len = n - 1; + memset(ray_data(short_y), 0, (size_t)(n - 1) * sizeof(int64_t)); + TEST_ASSERT_EQ_I(ray_col_save(short_y, TMP_SPLAY_BASE "/generation_cancel_tmpl/y"), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save(short_y, g0y), RAY_OK); + ray_release(short_y); + FILE* f = fopen(TMP_SPLAY_BASE "/generation_cancel/.current", "wb"); + TEST_ASSERT_NOT_NULL(f); + fputs(".generations/g-0\n", f); + fclose(f); + + fflush(NULL); + pid_t child = fork(); + TEST_ASSERT_TRUE(child >= 0); + if (child == 0) generation_flip_child(dir, tmpl, 1 << 30); /* killed below */ + /* Wait until the writer is publishing. */ + for (int i = 0; i < 5000; i++) { + char now[1024]; + if (ray_splay_resolve_dir(dir, now, sizeof(now)) == RAY_OK && strcmp(now, g0) != 0) break; + struct timespec ms = {0, 1000 * 1000}; + nanosleep(&ms, NULL); + } + + ray_request_interrupt(); + struct timespec a, b; + clock_gettime(CLOCK_MONOTONIC, &a); + ray_t* m = ray_splay_load(dir, NULL); + clock_gettime(CLOCK_MONOTONIC, &b); + ray_clear_interrupt(); + kill(child, SIGKILL); + int status = 0; + waitpid(child, &status, 0); + double secs = (double)(b.tv_sec - a.tv_sec) + (double)(b.tv_nsec - a.tv_nsec) / 1e9; + bool err = m && RAY_IS_ERR(m); + if (m && RAY_IS_ERR(m)) ray_error_free(m); else if (m) ray_release(m); + TEST_ASSERT_TRUE(err); + TEST_ASSERT_TRUE(secs < 2.0); + ray_release(t); + rm_rf(dir); + rm_rf(tmpl); + PASS(); +} +#endif + static test_result_t test_generation_invalid_manifest(void) { const char* dir = TMP_SPLAY_BASE "/generation_manifest"; rm_rf(dir); @@ -2765,12 +3115,136 @@ static test_result_t test_generation_writer_exit(void) { PASS(); } +/* File `path` read whole into a raw buffer (*len its size); NULL when + * unreadable. */ +static uint8_t* splay_read_file(const char* path, size_t* len) { + FILE* f = fopen(path, "rb"); + if (!f) return NULL; + uint8_t* buf = NULL; + if (fseek(f, 0, SEEK_END) == 0) { + long sz = ftell(f); + if (sz > 0 && fseek(f, 0, SEEK_SET) == 0 && (buf = (uint8_t*)ray_alloc_raw((size_t)sz)) && + fread(buf, 1, (size_t)sz, f) != (size_t)sz) { ray_free_raw(buf); buf = NULL; } + *len = sz > 0 ? (size_t)sz : 0; + } + fclose(f); + return buf; +} + +/* Column file `name` of the generation `dir` resolves to, read whole. */ +static uint8_t* splay_read_col_file(const char* dir, const char* name, size_t* len) { + char gen[1024], path[1200]; + if (ray_splay_resolve_dir(dir, gen, sizeof(gen)) != RAY_OK) return NULL; + snprintf(path, sizeof(path), "%s/%s", gen, name); + return splay_read_file(path, len); +} + +/* `col` written to `path` with its hash index appended the way the + * in-memory build always did it: attached to the mapped column under a + * budget of many batches (the arrays at the key count, cut to the groups + * after), then copied in by ray_col_append_index. */ +static bool splay_legacy_hash_file(ray_t* col, const char* path) { + if (ray_col_save_bulk(col, path) != RAY_OK) return false; + ray_t* m = ray_col_mmap(path); + if (!m || RAY_IS_ERR(m)) { if (m) ray_error_free(m); return false; } + int64_t wm = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(INT64_C(4) << 20); + ray_t* r = ray_index_attach_hash(&m); + ray_heap_set_anon_watermark(wm); + bool ok = !RAY_IS_ERR(r) && + ray_col_append_index(path, ray_index_payload(m->index), m->len, m->type) == RAY_OK; + if (RAY_IS_ERR(r)) ray_error_free(r); + ray_release(m); + return ok; +} + +/* A save builds its hash indexes in the column files. An unclustered + * numeric column the save hashes on its own holds exactly the bytes the + * in-memory build appended before (as a single batch here, which sizes its + * arrays up front: the reference is built the old way, many batches); a + * SYM column's explicit hash, rebuilt over the file's positions, answers + * lookups. With the pool's per-column tasks and serially. */ +static test_result_t test_save_hash_in_place(void) { + ray_pool_t* pool = ray_pool_get(); + const char* d_auto = TMP_SPLAY_BASE "/hash_auto"; + const char* y_auto = TMP_SPLAY_BASE "/hash_auto_sym"; + const char* refs[2] = { TMP_SPLAY_BASE "/hash_ref_a", TMP_SPLAY_BASE "/hash_ref_t" }; + mkdir(TMP_SPLAY_BASE, 0755); + const int64_t n = 300000; + int64_t ids[997]; + char name[16]; + for (int k = 0; k < 997; k++) { + int l = snprintf(name, sizeof(name), "hk%d", k); + ids[k] = ray_sym_intern(name, (size_t)l); + } + int64_t bad = 0; + for (int plan = 0; plan < 2; plan++) { + if (plan == 1) { if (!pool) continue; atomic_store(&ray_parallel_flag, 1); } + ray_t* a = ray_vec_new(RAY_I64, n); + ray_t* t = ray_vec_new(RAY_TIMESTAMP, n); + ray_t* s = ray_sym_vec_new(RAY_SYM_W64, n); + TEST_ASSERT_FALSE(RAY_IS_ERR(a)); TEST_ASSERT_FALSE(RAY_IS_ERR(t)); TEST_ASSERT_FALSE(RAY_IS_ERR(s)); + a->len = t->len = s->len = n; + for (int64_t i = 0; i < n; i++) { + ((int64_t*)ray_data(a))[i] = (int64_t)(((uint64_t)i * 2654435761ull) % 1000000007ull); + ((int64_t*)ray_data(t))[i] = (int64_t)(((uint64_t)i * 17) % 70001) * 1000000007; + ((int64_t*)ray_data(s))[i] = ids[(i * 31) % 997]; + } + ray_t* sh = s; ray_retain(sh); + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&sh))); + int64_t na = ray_sym_intern("a", 1), nt = ray_sym_intern("t", 1), ns = ray_sym_intern("s", 1); + ray_t* t1 = ray_table_new(3); + t1 = ray_table_add_col(t1, na, a); + t1 = ray_table_add_col(t1, nt, t); + t1 = ray_table_add_col(t1, ns, sh); + rm_rf(d_auto); unlink(y_auto); + TEST_ASSERT_EQ_I(ray_splay_save(t1, d_auto, y_auto), RAY_OK); + if (plan == 1) atomic_store(&ray_parallel_flag, 0); + static const char* cols[2] = { "a", "t" }; + ray_t* vecs[2] = { a, t }; + for (int c = 0; c < 2; c++) { + size_t la = 0, lm = 0; + uint8_t* fa = splay_read_col_file(d_auto, cols[c], &la); + uint8_t* fm = splay_legacy_hash_file(vecs[c], refs[c]) ? splay_read_file(refs[c], &lm) : NULL; + if (!fa || !fm || la != lm || la <= 32 + (size_t)n * 8 || memcmp(fa, fm, la) != 0) bad++; + ray_free_raw(fa); ray_free_raw(fm); + unlink(refs[c]); + } + ray_t* back = ray_read_splayed(d_auto, y_auto); /* mapped: the indexes ride along */ + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + ray_t* bs = ray_table_get_col(back, ns); + ray_t* ba = ray_table_get_col(back, na); + if (!bs || ray_index_kind(bs) != RAY_IDX_HASH || !ba || ray_index_kind(ba) != RAY_IDX_HASH) bad++; + for (int k = 0; k < 997 && bs; k += 37) { + ray_t* atom = ray_sym(ids[k]); + int64_t first = -1; + for (int64_t i = 0; i < n && first < 0; i++) if ((i * 31) % 997 == k) first = i; + if (ray_index_find_atom(bs, atom) != first) bad++; + ray_release(atom); + } + ray_release(back); + ray_release(t1); + ray_release(a); ray_release(t); ray_release(s); + ray_release(sh); + } + rm_rf(d_auto); unlink(y_auto); + TEST_ASSERT_EQ_I(bad, 0); + 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_keeps_only_current", test_generation_keeps_only_current, splay_setup, splay_teardown }, + { "splay/generation_first_write_removed", test_generation_first_write_removed, splay_setup, splay_teardown }, + { "splay/generation_first_write_keeps_others", test_generation_first_write_keeps_others, splay_setup, splay_teardown }, +#ifndef _WIN32 + { "splay/generation_reader_races", test_generation_reader_races, splay_setup, splay_teardown }, + { "splay/generation_retry_releases_domain", test_generation_retry_releases_domain, splay_setup, splay_teardown }, + { "splay/generation_reader_interrupted", test_generation_reader_interrupted, splay_setup, splay_teardown }, +#endif { "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 }, @@ -2818,5 +3292,6 @@ const test_entry_t splay_entries[] = { { "splay/resolution_explicit_wins", test_resolution_explicit_wins, splay_setup, splay_teardown }, { "splay/csv_symfile_order", test_csv_splayed_symfile_order, splay_setup, splay_teardown }, { "splay/csv_quote_mode_per_file", test_csv_splayed_quote_mode_per_file, splay_setup, splay_teardown }, + { "splay/save_hash_in_place", test_save_hash_in_place, splay_setup, splay_teardown }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_store.c b/test/test_store.c index f19448fb1..164b0b109 100644 --- a/test/test_store.c +++ b/test/test_store.c @@ -44,10 +44,14 @@ #include "core/sock.h" #include "core/platform.h" #include "core/runtime.h" +#include "core/pool.h" #include "lang/eval.h" #include "lang/internal.h" #include "mem/sys.h" #include "table/sym.h" +#include "table/domain.h" +#include +#include "ops/hash.h" /* ray_hash_bytes: the import dictionary's full hashes */ #include "vec/str.h" #ifndef RAY_OS_WINDOWS @@ -79,6 +83,7 @@ static void store_setup(void) { } static void store_teardown(void) { + ray_parted_cache_clear(); ray_sym_destroy(); ray_heap_destroy(); } @@ -1964,6 +1969,271 @@ static test_result_t test_stream_sentinel_publishes_has_nulls(void) { PASS(); } +/* SYM writer chunks. A chunk already encoded over the writer's domain (a + * converter's own decode) is written as it is, W32 straight and narrower + * widths widened, and never makes the runtime id cache; a runtime-domain + * chunk makes it and gets its positions through it. HAS_NULLS follows the + * positions written, not a chunk's flag: a flagged chunk without position 0 + * publishes none, an unflagged one holding it, even in its last cell, + * publishes it. */ +static bool stream_sym_read(const char* path, ray_t* hdr, uint32_t* pos, int64_t n) { + FILE* f = fopen(path, "rb"); + if (!f) return false; + bool ok = fread(hdr, 1, 32, f) == 32 && (int64_t)fread(pos, 4, (size_t)n, f) == n; + fclose(f); + return ok; +} +static ray_t* stream_sym_chunk(ray_sym_domain_t* dom, int64_t n, uint8_t width) { + ray_t* v = ray_sym_vec_new(width, n); + if (!v || RAY_IS_ERR(v)) return NULL; + v->sym_domain = dom; ray_sym_domain_retain(dom); + v->len = n; v->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + return v; +} +static test_result_t test_stream_sym_chunks(void) { + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-sym-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + char sp[200], path[200]; snprintf(sp, sizeof(sp), "%s/.sym", dir); + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(sp); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "", 0), 0); + enum { K = 5 }; + const char* words[K] = {"", "alpha", "beta", "a string past the inline bytes", "gamma"}; + int64_t at[K], id[K]; + for (int k = 0; k < K; k++) { + at[k] = ray_sym_domain_intern(dom, words[k], strlen(words[k])); + id[k] = ray_sym_intern(words[k], strlen(words[k])); + TEST_ASSERT_TRUE(at[k] >= 0 && id[k] >= 0); + } + int64_t n = 20000; /* past the writer's 8192-cell buffer */ + uint32_t* back = (uint32_t*)ray_sys_alloc((size_t)(3 * n) * sizeof(uint32_t)); + TEST_ASSERT_NOT_NULL(back); + ray_t hdr; + + /* "d": three chunks over the domain, none holding 0: W32 flagged, W32, + * then W16 (re-encoded to the file's W32) */ + ray_t* c1 = stream_sym_chunk(dom, n, RAY_SYM_W32); + ray_t* c2 = stream_sym_chunk(dom, n, RAY_SYM_W32); + ray_t* c4 = stream_sym_chunk(dom, n, RAY_SYM_W16); + TEST_ASSERT_TRUE(c1 && c2 && c4); + for (int64_t i = 0; i < n; i++) { + ((uint32_t*)ray_data(c1))[i] = (uint32_t)at[1 + i % (K - 1)]; + ((uint32_t*)ray_data(c2))[i] = (uint32_t)at[1 + (i * 3) % (K - 1)]; + ((uint16_t*)ray_data(c4))[i] = (uint16_t)at[1 + (i * 5) % (K - 1)]; + } + c1->attrs |= RAY_ATTR_HAS_NULLS; + ray_col_stream_t w; + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("d", 1), RAY_SYM, dom), RAY_OK); + TEST_ASSERT_NULL(w.lut_id); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, c1), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, c2), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, c4), RAY_OK); + TEST_ASSERT_NULL(w.lut_id); + TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); + snprintf(path, sizeof(path), "%s/d", dir); + TEST_ASSERT_TRUE(stream_sym_read(path, &hdr, back, 3 * n)); + TEST_ASSERT_EQ_I(hdr.type, RAY_SYM); + TEST_ASSERT_EQ_I(hdr.len, 3 * n); + TEST_ASSERT_FALSE(hdr.attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_EQ_I(memcmp(back, ray_data(c1), (size_t)n * 4), 0); + TEST_ASSERT_EQ_I(memcmp(back + n, ray_data(c2), (size_t)n * 4), 0); + int64_t bad = 0; + for (int64_t i = 0; i < n; i++) + if (back[2 * n + i] != ((uint16_t*)ray_data(c4))[i]) bad++; + TEST_ASSERT_EQ_I(bad, 0); + + /* "r": an unflagged chunk over the domain whose only 0 is its last + * cell, then two runtime-domain chunks without "" (the cache made, + * then hit) */ + ray_t* c3 = stream_sym_chunk(dom, n, RAY_SYM_W32); + ray_t* rt = ray_sym_vec_new(RAY_SYM_W64, n); + TEST_ASSERT_TRUE(c3 && rt && !RAY_IS_ERR(rt)); + rt->len = n; + for (int64_t i = 0; i < n; i++) { + ((uint32_t*)ray_data(c3))[i] = (uint32_t)at[1 + i % (K - 1)]; + ((int64_t*)ray_data(rt))[i] = id[1 + (i * 7) % (K - 1)]; + } + ((uint32_t*)ray_data(c3))[n - 1] = 0; + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("r", 1), RAY_SYM, dom), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, c3), RAY_OK); + TEST_ASSERT_NULL(w.lut_id); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, rt), RAY_OK); + TEST_ASSERT_NOT_NULL(w.lut_id); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, rt), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); + TEST_ASSERT_NULL(w.lut_id); + snprintf(path, sizeof(path), "%s/r", dir); + TEST_ASSERT_TRUE(stream_sym_read(path, &hdr, back, 3 * n)); + TEST_ASSERT_EQ_I(hdr.len, 3 * n); + TEST_ASSERT_TRUE(hdr.attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_EQ_I(memcmp(back, ray_data(c3), (size_t)n * 4), 0); + for (int64_t i = 0; i < 2 * n; i++) + if (back[n + i] != (uint32_t)at[1 + ((i % n) * 7) % (K - 1)]) bad++; + TEST_ASSERT_EQ_I(bad, 0); + + ray_release(c1); ray_release(c2); ray_release(c3); ray_release(c4); ray_release(rt); + ray_sys_free(back); + ray_sym_domain_release(dom); + (void)ray_test_rm_rf(dir); + PASS(); +} + +/* STR chunks into a SYM writer: interned into the writer's domain, a batch + * of 8192 at a time. The same 20000 strings (a few hundred distinct, "", + * repeats across batches) into a file domain and into an import dictionary + * domain (the direct import's, which keys on all 64 bits of the hash) give + * the same positions, first occurrence first; and the import dictionary + * then finds every string under its full hash (none added again). */ +static test_result_t test_stream_sym_from_str(void) { + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-str-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + const int64_t n = 20000; + ray_t* col = ray_vec_new(RAY_STR, n); + TEST_ASSERT_FALSE(!col || RAY_IS_ERR(col)); + char buf[64]; + for (int64_t i = 0; i < n; i++) { + int len = i % 97 == 0 ? 0 : snprintf(buf, sizeof(buf), "%s-%lld", i % 3 ? "a string past the inline bytes" : "s", + (long long)((i * 7919) % 300)); + col = ray_str_vec_append(col, buf, (size_t)len); + TEST_ASSERT_FALSE(!col || RAY_IS_ERR(col)); + } + uint32_t* back[2] = {NULL, NULL}; + char sp[200], path[200]; + ray_sym_domain_t* dom[2] = {NULL, NULL}; + for (int k = 0; k < 2; k++) { + snprintf(sp, sizeof(sp), "%s/.sym%d", dir, k); + dom[k] = k ? ray_sym_domain_create_import(sp) : ray_sym_domain_open_or_create(sp); + if (!dom[k]) { TEST_ASSERT_EQ_I(k, 1); break; } /* no import dictionary here */ + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom[k], "", 0), 0); + ray_col_stream_t w; + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern(k ? "i" : "f", 1), RAY_SYM, dom[k]), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, col), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); + back[k] = (uint32_t*)ray_sys_alloc((size_t)n * sizeof(uint32_t)); + TEST_ASSERT_NOT_NULL(back[k]); + ray_t hdr; + snprintf(path, sizeof(path), "%s/%s", dir, k ? "i" : "f"); + TEST_ASSERT_TRUE(stream_sym_read(path, &hdr, back[k], n)); + TEST_ASSERT_EQ_I(hdr.len, n); + TEST_ASSERT_TRUE(hdr.attrs & RAY_ATTR_HAS_NULLS); + } + int64_t bad = 0; + if (dom[1]) { + for (int64_t i = 0; i < n; i++) if (back[0][i] != back[1][i]) { bad++; break; } + /* every string found again under its full hash, at its position */ + int64_t before = ray_sym_domain_count(dom[1]); + for (int64_t i = 0; i < n && !bad; i++) { + size_t len; const char* s = ray_str_vec_get(col, i, &len); + uint64_t h = ray_hash_bytes(s, len); + int64_t pos = -1; + if (!ray_sym_domain_intern_batch64(dom[1], 1, &s, &len, &h, &pos) || pos != (int64_t)back[1][i]) bad++; + } + if (ray_sym_domain_count(dom[1]) != before) bad++; + } + for (int k = 0; k < 2; k++) { if (dom[k]) ray_sym_domain_release(dom[k]); ray_sys_free(back[k]); } + ray_release(col); + (void)ray_test_rm_rf(dir); + TEST_ASSERT_EQ_I(bad, 0); + if (!dom[1]) SKIP("import dictionary unsupported here: the file domain only"); + PASS(); +} +/* A W32 chunk over another symbol file's domain is re-encoded string by + * string, at the writer's own width as at any other: its positions mean + * nothing in the writer's domain (the other file holds the same words in + * another order, and one more). */ +static test_result_t test_stream_sym_foreign(void) { + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-symf-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + char sp[200], sp2[200], path[200]; + snprintf(sp, sizeof(sp), "%s/.sym", dir); snprintf(sp2, sizeof(sp2), "%s/.sym2", dir); + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(sp); + ray_sym_domain_t* other = ray_sym_domain_open_or_create(sp2); + TEST_ASSERT_TRUE(dom && other); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "", 0), 0); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(other, "", 0), 0); + enum { K = 5 }; + const char* words[K] = {"alpha", "beta", "gamma", "a string past the inline bytes", "only in the other"}; + int64_t at2[K]; + for (int k = 0; k < K - 1; k++) TEST_ASSERT_TRUE(ray_sym_domain_intern(dom, words[k], strlen(words[k])) > 0); + for (int k = K - 1; k >= 0; k--) { + at2[k] = ray_sym_domain_intern(other, words[k], strlen(words[k])); + TEST_ASSERT_TRUE(at2[k] > 0); + } + int64_t n = 20000; + ray_t* c = stream_sym_chunk(other, n, RAY_SYM_W32); + TEST_ASSERT_NOT_NULL(c); + for (int64_t i = 0; i < n; i++) ((uint32_t*)ray_data(c))[i] = (uint32_t)at2[(i * 3) % K]; + ray_col_stream_t w; + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("f", 1), RAY_SYM, dom), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, c), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); + int64_t at[K]; + for (int k = 0; k < K; k++) { + at[k] = ray_sym_domain_find(dom, words[k], strlen(words[k])); + TEST_ASSERT_TRUE(at[k] > 0); /* the fifth added by the append */ + } + uint32_t* back = (uint32_t*)ray_sys_alloc((size_t)n * sizeof(uint32_t)); + TEST_ASSERT_NOT_NULL(back); + ray_t hdr; + snprintf(path, sizeof(path), "%s/f", dir); + TEST_ASSERT_TRUE(stream_sym_read(path, &hdr, back, n)); + TEST_ASSERT_FALSE(hdr.attrs & RAY_ATTR_HAS_NULLS); + int64_t bad = 0; + for (int64_t i = 0; i < n; i++) if (back[i] != (uint32_t)at[(i * 3) % K]) bad++; + TEST_ASSERT_EQ_I(bad, 0); + ray_release(c); ray_sys_free(back); + ray_sym_domain_release(dom); ray_sym_domain_release(other); + (void)ray_test_rm_rf(dir); + PASS(); +} + +/* The runtime id cache starts empty whatever its memory held: the blocks it + * is carved from were freed full of one runtime id, which must then be + * interned on first sight rather than read from a stale slot. */ +static test_result_t test_stream_sym_lut_stale(void) { + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-syml-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + char sp[200], path[200]; snprintf(sp, sizeof(sp), "%s/.sym", dir); + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(sp); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "", 0), 0); + TEST_ASSERT_TRUE(ray_sym_domain_intern(dom, "filler", 6) > 0); + int64_t x = ray_sym_intern("a stale runtime id", 18); + TEST_ASSERT_TRUE(x > 0); + /* blocks of the cache's two sizes (2^19 ids, 2^19 positions), freed full of x */ + void* blk[8]; + for (int i = 0; i < 8; i++) { + size_t sz = (size_t)1 << (i < 4 ? 22 : 21); + blk[i] = ray_alloc_raw(sz); + TEST_ASSERT_NOT_NULL(blk[i]); + for (size_t j = 0; j < sz / 8; j++) ((int64_t*)blk[i])[j] = x; + } + for (int i = 7; i >= 0; i--) ray_free_raw(blk[i]); + int64_t n = 1000; + ray_t* rt = ray_sym_vec_new(RAY_SYM_W64, n); + TEST_ASSERT_TRUE(rt && !RAY_IS_ERR(rt)); + rt->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(rt))[i] = x; + ray_col_stream_t w; + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("l", 1), RAY_SYM, dom), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, rt), RAY_OK); + TEST_ASSERT_NOT_NULL(w.lut_id); + TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); + int64_t want = ray_sym_domain_find(dom, "a stale runtime id", 18); + TEST_ASSERT_EQ_I(want, 2); + uint32_t back[1000]; + ray_t hdr; + snprintf(path, sizeof(path), "%s/l", dir); + TEST_ASSERT_TRUE(stream_sym_read(path, &hdr, back, n)); + int64_t bad = 0; + for (int64_t i = 0; i < n; i++) if (back[i] != (uint32_t)want) bad++; + TEST_ASSERT_EQ_I(bad, 0); + ray_release(rt); + ray_sym_domain_release(dom); + (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 @@ -2032,6 +2302,9 @@ static test_result_t test_stream_inline_zone_one_chunk(void) { PASS(); } +static bool store_files_same(const char* a, const char* b); +static ray_err_t store_hash_append_legacy(const char* path); + /* Unclustered I64 over four chunks: no inline index, the zone is kept and * wants_hash set; ray_splay_hash_column then appends a hash. */ static test_result_t test_stream_hash_candidate(void) { @@ -2057,7 +2330,531 @@ static test_result_t test_stream_hash_candidate(void) { 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); + ray_release(back); + /* the file is the one the in-memory build appended before */ + char ref[200]; snprintf(ref, sizeof(ref), "%s/ref", dir); + TEST_ASSERT_EQ_I(ray_col_save_bulk(v, ref), RAY_OK); + TEST_ASSERT_EQ_I(store_hash_append_legacy(ref), RAY_OK); + TEST_ASSERT_TRUE(store_files_same(path, ref)); + ray_release(v); + (void)ray_test_rm_rf(dir); + PASS(); +} + +/* ---- hash index built in place in the column file ---------------------- */ + +/* n rows of `type` keyed as idx_reg_col in test_index.c: keys spread over + * `keys` values, every null_every-th row null. SYM ids stay below the + * interned count (the bare mmap validates them). */ +static ray_t* store_hash_col(int8_t type, int64_t n, int64_t keys, int64_t null_every) { + ray_t* v = type == RAY_SYM ? ray_sym_vec_new(RAY_SYM_W32, n > 0 ? n : 1) + : ray_vec_new(type, n > 0 ? n : 1); + if (!v || RAY_IS_ERR(v)) return v; + v->len = n; + void* d = ray_data(v); + for (int64_t i = 0; i < n; i++) { + int64_t k = (int64_t)(((uint64_t)i * 2654435761ull) % (uint64_t)keys) - keys / 3; + switch (type) { + case RAY_I32: case RAY_DATE: ((int32_t*)d)[i] = (int32_t)k; break; + case RAY_I64: case RAY_TIMESTAMP: ((int64_t*)d)[i] = k * 1000003; break; + case RAY_F64: ((double*)d)[i] = (double)k * 0.25; break; + case RAY_SYM: ((uint32_t*)d)[i] = (uint32_t)(k + keys / 3 + 1); break; + default: break; + } + } + for (int64_t i = 0; null_every && i < n; i += null_every) + if (ray_vec_set_null_checked(v, i, true) != RAY_OK) { ray_release(v); return NULL; } + return v; +} + +/* Files `a` and `b` hold the same bytes. */ +static bool store_files_same(const char* a, const char* b) { + struct stat sa, sb; + if (stat(a, &sa) != 0 || stat(b, &sb) != 0 || sa.st_size != sb.st_size) return false; + size_t sz = (size_t)sa.st_size; + uint8_t* ba = (uint8_t*)ray_alloc_raw(sz ? sz : 1); + uint8_t* bb = (uint8_t*)ray_alloc_raw(sz ? sz : 1); + FILE* fa = fopen(a, "rb"); + FILE* fb = fopen(b, "rb"); + bool ok = ba && bb && fa && fb && fread(ba, 1, sz, fa) == sz && + fread(bb, 1, sz, fb) == sz && memcmp(ba, bb, sz) == 0; + if (fa) fclose(fa); + if (fb) fclose(fb); + ray_free_raw(ba); ray_free_raw(bb); + return ok; +} + +/* The hash index appended to index-less column file `path` as before the + * in-place build: attached to the mapped column, then copied into the file. + * Built under a small budget, so a column of more than one batch takes the + * route the in-memory build always took — arrays at the key count, cut to + * the groups after — and not the sizes the in-place build computes. */ +static ray_err_t store_hash_append_legacy(const char* path) { + ray_t* col = ray_col_mmap(path); + if (!col || RAY_IS_ERR(col)) { if (col) ray_error_free(col); return RAY_ERR_IO; } + int64_t wm = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(INT64_C(4) << 20); + ray_t* r = ray_index_attach_hash(&col); + ray_heap_set_anon_watermark(wm); + ray_err_t err = RAY_ERR_OOM; + if (!RAY_IS_ERR(r)) + err = ray_col_append_index(path, ray_index_payload(col->index), col->len, col->type); + else + ray_error_free(r); + ray_release(col); + return err; +} + +/* The same, built in place over the mapped column. */ +static ray_err_t store_hash_build(const char* path) { + ray_t* col = ray_col_mmap(path); + if (!col || RAY_IS_ERR(col)) { if (col) ray_error_free(col); return RAY_ERR_IO; } + ray_err_t err = ray_col_build_hash_index(path, col, NULL); + ray_release(col); + return err; +} + +static int64_t store_file_size(const char* path) { + struct stat st; + return stat(path, &st) == 0 ? (int64_t)st.st_size : -1; +} + +/* Does `dir` take the in-place build (Linux, a filesystem whose fallocate + * holds the blocks)? Probed with a small column. */ +static bool store_in_place(const char* dir) { + char p[240]; + snprintf(p, sizeof(p), "%s/.probe", dir); + ray_t* v = store_hash_col(RAY_I64, 1000, 10, 0); + bool ok = v && !RAY_IS_ERR(v) && ray_col_save_bulk(v, p) == RAY_OK && + store_hash_build(p) == RAY_OK; + if (v && !RAY_IS_ERR(v)) ray_release(v); + unlink(p); + return ok; +} + +/* Built in place, the column file holds exactly the bytes the in-memory + * build appended — numeric, temporal, float with nulls, SYM ids, every key + * distinct or few — with one batch and with many (the counting pass), and + * the index loads and answers. Where the in-place build does not apply, + * the same through ray_splay_hash_column's in-memory route. */ +static test_result_t test_col_build_hash_index_bytes(void) { + (void)ray_pool_get(); + char name[16]; + for (int i = 0; i < 2000; i++) { /* SYM ids below the interned count */ + int l = snprintf(name, sizeof(name), "hx%d", i); + TEST_ASSERT_TRUE(ray_sym_intern(name, (size_t)l) >= 0); + } + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-hidx-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + bool in_place = store_in_place(dir); + char a[200], b[200]; + snprintf(a, sizeof(a), "%s/a", dir); + snprintf(b, sizeof(b), "%s/b", dir); + static const struct { int8_t type; int64_t n, keys, null_every; } shapes[] = { + { RAY_I64, 200000, 200000, 0 }, { RAY_I64, 300000, 5003, 977 }, + { RAY_I32, 1000, 10, 0 }, { RAY_TIMESTAMP, 90000, 70001, 0 }, + { RAY_F64, 100000, 2003, 101 }, { RAY_SYM, 120000, 997, 0 }, + { RAY_I64, 1, 1, 0 }, + }; + int64_t bad = 0; + for (int plan = 0; plan < 2; plan++) { + if (plan == 1) ray_heap_set_anon_watermark(INT64_C(4) << 20); + for (size_t s = 0; s < sizeof(shapes) / sizeof(shapes[0]); s++) { + ray_t* v = store_hash_col(shapes[s].type, shapes[s].n, shapes[s].keys, shapes[s].null_every); + if (!v || RAY_IS_ERR(v)) { bad++; continue; } + if (ray_col_save_bulk(v, a) != RAY_OK || ray_col_save_bulk(v, b) != RAY_OK) bad++; + int64_t payload = store_file_size(a); + ray_err_t e = in_place ? store_hash_build(a) : ray_splay_hash_column(a, NULL); + if (e != RAY_OK || store_hash_append_legacy(b) != RAY_OK) bad++; + if (!store_files_same(a, b) || store_file_size(a) <= payload) bad++; + ray_t* m = ray_col_mmap(a); + if (!m || RAY_IS_ERR(m) || ray_index_kind(m) != RAY_IDX_HASH) bad++; + else if ((shapes[s].type == RAY_I64 || shapes[s].type == RAY_TIMESTAMP) && shapes[s].n > 2) { + /* row 2's key finds its group, row 2 among its rows */ + int64_t key = ((int64_t*)ray_data(m))[2]; + ray_idx_rows_t rows = { NULL, false }; int64_t gn = 0, hit = 0; + if (ray_index_hash_group(m, key, &rows, &gn) != 1) bad++; + for (int64_t j = 0; j < gn; j++) hit += ray_idx_rows_at(rows, j) == 2; + if (hit != 1) bad++; + } + if (m && !RAY_IS_ERR(m)) ray_release(m); else if (m) ray_error_free(m); + ray_release(v); + } + if (plan == 1) ray_heap_set_anon_watermark(0); + } + TEST_ASSERT_EQ_I(bad, 0); + (void)ray_test_rm_rf(dir); + PASS(); +} + +/* A file that already carries an index is refused and left as it is; a + * STR column is not built in place (the caller takes the in-memory path) + * and its file is not touched. */ +static test_result_t test_col_build_hash_index_refusals(void) { + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-hidx-ref-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + char p[200]; snprintf(p, sizeof(p), "%s/a", dir); + ray_t* m = NULL; + if (store_in_place(dir)) { + ray_t* v = store_hash_col(RAY_I64, 100000, 5003, 0); + TEST_ASSERT_EQ_I(ray_col_save_bulk(v, p), RAY_OK); + TEST_ASSERT_EQ_I(store_hash_build(p), RAY_OK); + int64_t indexed = store_file_size(p); + TEST_ASSERT_EQ_I(store_hash_build(p), RAY_ERR_CORRUPT); + TEST_ASSERT_EQ_I(store_file_size(p), indexed); + m = ray_col_mmap(p); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_HASH); + ray_release(m); + ray_release(v); + } + + ray_t* s = ray_vec_new(RAY_STR, 4); + s = ray_str_vec_append(s, "alpha", 5); + s = ray_str_vec_append(s, "beta", 4); + char q[200]; snprintf(q, sizeof(q), "%s/s", dir); + TEST_ASSERT_EQ_I(ray_col_save_bulk(s, q), RAY_OK); + int64_t plain = store_file_size(q); + TEST_ASSERT_EQ_I(store_hash_build(q), RAY_ERR_NYI); + TEST_ASSERT_EQ_I(store_file_size(q), plain); + /* ray_splay_hash_column takes the in-memory path for it */ + TEST_ASSERT_EQ_I(ray_splay_hash_column(q, NULL), RAY_OK); + m = ray_col_mmap(q); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_HASH); + ray_release(m); + ray_release(s); + (void)ray_test_rm_rf(dir); + PASS(); +} + +/* On a filesystem the in-place build does not trust (copy-on-write, + * network, user — or any platform but Linux) it leaves the file alone, and + * ray_splay_hash_column builds the index in memory and appends it: the same + * bytes. Debug builds pretend the filesystem is untrusted. */ +static test_result_t test_col_build_hash_index_untrusted_fs(void) { +#if defined(RAY_OS_LINUX) && !defined(DEBUG) + SKIP("RAY_HASH_INJECT is read by debug builds only"); +#endif + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-hidx-fs-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + char a[200], b[200]; + snprintf(a, sizeof(a), "%s/a", dir); + snprintf(b, sizeof(b), "%s/b", dir); +#if defined(DEBUG) + TEST_ASSERT_EQ_I(setenv("RAY_HASH_INJECT", "fs", 1), 0); +#endif + ray_t* v = store_hash_col(RAY_I64, 300000, 5003, 977); + TEST_ASSERT_EQ_I(ray_col_save_bulk(v, a), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save_bulk(v, b), RAY_OK); + int64_t payload = store_file_size(a); + ray_err_t direct = store_hash_build(a); + int64_t after = store_file_size(a); + ray_err_t routed = ray_splay_hash_column(a, NULL); +#if defined(DEBUG) + unsetenv("RAY_HASH_INJECT"); +#endif + TEST_ASSERT_EQ_I(direct, RAY_ERR_NYI); + TEST_ASSERT_EQ_I(after, payload); + TEST_ASSERT_EQ_I(routed, RAY_OK); + TEST_ASSERT_EQ_I(store_hash_append_legacy(b), RAY_OK); + TEST_ASSERT_TRUE(store_files_same(a, b)); + ray_t* m = ray_col_mmap(a); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_HASH); + ray_release(m); + ray_release(v); + (void)ray_test_rm_rf(dir); + PASS(); +} + +/* Which filesystems the in-place build trusts, by the type fstatfs reports + * (debug builds stand an injected type in for the real one, so the ones no + * test can mount are classified too): ext4, xfs and tmpfs, whose fallocate + * holds the blocks; not overlayfs, whose upper layer cannot be told, nor + * the copy-on-write, network and user filesystems. An untrusted one leaves + * the file at its payload. */ +static test_result_t test_col_build_hash_index_fs_types(void) { +#if defined(DEBUG) && defined(RAY_OS_LINUX) + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-hidx-fst-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + if (!store_in_place(dir)) { (void)ray_test_rm_rf(dir); SKIP("no in-place build on this filesystem"); } + char p[200]; snprintf(p, sizeof(p), "%s/a", dir); + static const struct { const char* inject; bool trusted; } types[] = { + { "fs:ef53", true }, /* ext2/3/4 */ + { "fs:58465342", true }, /* xfs */ + { "fs:1021994", true }, /* tmpfs */ + { "fs:794c7630", false }, /* overlayfs */ + { "fs:9123683e", false }, /* btrfs */ + { "fs:2fc12fc1", false }, /* zfs */ + { "fs:ca451a4e", false }, /* bcachefs */ + { "fs:6969", false }, /* nfs */ + { "fs:ff534d42", false }, /* cifs */ + { "fs:fe534d42", false }, /* smb2 */ + { "fs:65735546", false }, /* fuse */ + { "fs:c36400", false }, /* ceph */ + }; + ray_t* v = store_hash_col(RAY_I64, 1000, 10, 0); + int64_t bad = 0; + for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); i++) { + if (ray_col_save_bulk(v, p) != RAY_OK) { bad++; continue; } + int64_t payload = store_file_size(p); + TEST_ASSERT_EQ_I(setenv("RAY_HASH_INJECT", types[i].inject, 1), 0); + ray_err_t e = store_hash_build(p); + unsetenv("RAY_HASH_INJECT"); + if (types[i].trusted ? (e != RAY_OK || store_file_size(p) <= payload) + : (e != RAY_ERR_NYI || store_file_size(p) != payload)) bad++; + } + ray_release(v); + TEST_ASSERT_EQ_I(bad, 0); + (void)ray_test_rm_rf(dir); + PASS(); +#else + SKIP("needs a debug build on Linux"); +#endif +} + +/* A region that cannot be allocated or mapped this time (debug builds + * inject either) does not cost the column its hash index: the in-place + * build gives way (NYI, the file at its payload) and ray_splay_hash_column + * and a splayed save build it in memory and append it — the same bytes. */ +static test_result_t test_col_build_hash_index_refused(void) { +#if defined(DEBUG) + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-hidx-ref2-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + if (!store_in_place(dir)) { (void)ray_test_rm_rf(dir); SKIP("no in-place build on this filesystem"); } + char a[200], b[200]; + snprintf(a, sizeof(a), "%s/a", dir); + snprintf(b, sizeof(b), "%s/b", dir); + ray_t* v = store_hash_col(RAY_I64, 300000, 5003, 977); + static const char* steps[2] = { "grow", "map" }; + int64_t bad = 0; + for (int plan = 0; plan < 2; plan++) { /* one batch; the counting pass first */ + if (plan == 1) ray_heap_set_anon_watermark(INT64_C(4) << 20); + for (int s = 0; s < 2; s++) { + if (ray_col_save_bulk(v, a) != RAY_OK || ray_col_save_bulk(v, b) != RAY_OK) bad++; + int64_t payload = store_file_size(a); + TEST_ASSERT_EQ_I(setenv("RAY_HASH_INJECT", steps[s], 1), 0); + ray_err_t direct = store_hash_build(a); + int64_t after = store_file_size(a); + ray_err_t routed = ray_splay_hash_column(a, NULL); + unsetenv("RAY_HASH_INJECT"); + if (direct != RAY_ERR_NYI || after != payload || routed != RAY_OK) bad++; + if (store_hash_append_legacy(b) != RAY_OK || !store_files_same(a, b)) bad++; + ray_t* m = ray_col_mmap(a); + if (!m || RAY_IS_ERR(m) || ray_index_kind(m) != RAY_IDX_HASH) bad++; + if (m && !RAY_IS_ERR(m)) ray_release(m); else if (m) ray_error_free(m); + } + if (plan == 1) ray_heap_set_anon_watermark(0); + } + /* a splayed save under the same refusal still hashes the column */ + int64_t name = ray_sym_intern("k", 1); + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, name, v); + char sd[200]; snprintf(sd, sizeof(sd), "%s/t", dir); + TEST_ASSERT_EQ_I(setenv("RAY_HASH_INJECT", "map", 1), 0); + ray_err_t se = ray_splay_save(t, sd, NULL); + unsetenv("RAY_HASH_INJECT"); + TEST_ASSERT_EQ_I(se, RAY_OK); + ray_t* back = ray_read_splayed(sd, NULL); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + if (ray_index_kind(ray_table_get_col(back, name)) != RAY_IDX_HASH) bad++; + ray_release(back); + ray_release(t); + ray_release(v); + TEST_ASSERT_EQ_I(bad, 0); + (void)ray_test_rm_rf(dir); + PASS(); +#else + SKIP("RAY_HASH_INJECT is read by debug builds only"); +#endif +} + +/* A build that fails once the region is allocated and mapped (debug + * builds raise an interrupt right there) cuts the file back to its payload: + * it loads unindexed and builds again after. One batch and many. */ +static test_result_t test_col_build_hash_index_truncate(void) { +#if defined(DEBUG) + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-hidx-tr-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + if (!store_in_place(dir)) { (void)ray_test_rm_rf(dir); SKIP("no in-place build on this filesystem"); } + char p[200]; snprintf(p, sizeof(p), "%s/a", dir); + ray_t* v = store_hash_col(RAY_I64, 300000, 5003, 977); + int64_t bad = 0; + for (int plan = 0; plan < 2; plan++) { + if (plan == 1) ray_heap_set_anon_watermark(INT64_C(4) << 20); + if (ray_col_save_bulk(v, p) != RAY_OK) bad++; + int64_t payload = store_file_size(p); + TEST_ASSERT_EQ_I(setenv("RAY_HASH_INJECT", "build", 1), 0); + ray_err_t e = store_hash_build(p); + unsetenv("RAY_HASH_INJECT"); + ray_clear_interrupt(); + if (e != RAY_ERR_CANCEL || store_file_size(p) != payload) bad++; + ray_t* back = ray_col_mmap(p); + if (!back || RAY_IS_ERR(back) || (back->attrs & RAY_ATTR_HAS_INDEX) || back->len != 300000) bad++; + if (back && !RAY_IS_ERR(back)) ray_release(back); else if (back) ray_error_free(back); + if (store_hash_build(p) != RAY_OK) bad++; + back = ray_col_mmap(p); + if (!back || RAY_IS_ERR(back) || ray_index_kind(back) != RAY_IDX_HASH) bad++; + if (back && !RAY_IS_ERR(back)) ray_release(back); else if (back) ray_error_free(back); + if (plan == 1) ray_heap_set_anon_watermark(0); + } + ray_release(v); + TEST_ASSERT_EQ_I(bad, 0); + (void)ray_test_rm_rf(dir); + PASS(); +#else + SKIP("RAY_HASH_INJECT is read by debug builds only"); +#endif +} + +/* The marker goes on last: a process that ends with the whole region + * written but before the marker (debug builds end it right there, in a + * child) leaves a file that does not claim an index. The column is under + * the parallel threshold: the child has no pool workers. */ +static test_result_t test_col_build_hash_index_marker_last(void) { +#if defined(DEBUG) && defined(RAY_OS_LINUX) + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-hidx-mk-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + if (!store_in_place(dir)) { (void)ray_test_rm_rf(dir); SKIP("no in-place build on this filesystem"); } + char p[200], r[200]; + snprintf(p, sizeof(p), "%s/a", dir); + snprintf(r, sizeof(r), "%s/ref", dir); + ray_t* v = store_hash_col(RAY_I64, 50000, 997, 0); + TEST_ASSERT_EQ_I(ray_col_save_bulk(v, p), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save_bulk(v, r), RAY_OK); + int64_t payload = store_file_size(p); + TEST_ASSERT_EQ_I(store_hash_build(r), RAY_OK); + pid_t pid = fork(); TEST_ASSERT_TRUE(pid >= 0); + if (!pid) { + if (setenv("RAY_HASH_INJECT", "premarker", 1)) _exit(2); + (void)store_hash_build(p); + _exit(3); /* not reached: it ends inside */ + } + int status; + TEST_ASSERT_EQ_I(waitpid(pid, &status, 0), pid); + TEST_ASSERT_TRUE(WIFEXITED(status)); TEST_ASSERT_EQ_I(WEXITSTATUS(status), 86); + /* the whole region is there, the header claims nothing */ + TEST_ASSERT_EQ_I(store_file_size(p), store_file_size(r)); + TEST_ASSERT_TRUE(store_file_size(p) > payload); + uint32_t mp = 0, mr = 0; + FILE* f = fopen(p, "rb"); TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_EQ_I((int64_t)fread(&mp, 1, 4, f), 4); fclose(f); + f = fopen(r, "rb"); TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_EQ_I((int64_t)fread(&mr, 1, 4, f), 4); fclose(f); + TEST_ASSERT_TRUE(mr != 0); /* the finished file's marker */ + TEST_ASSERT_TRUE(mp != mr); + ray_t* back = ray_col_mmap(p); /* longer than its payload, unclaimed: refused */ + TEST_ASSERT_TRUE(back && RAY_IS_ERR(back)); + ray_error_free(back); + ray_release(v); + (void)ray_test_rm_rf(dir); + PASS(); +#else + SKIP("needs a debug build on Linux"); +#endif +} + +/* The region's blocks cannot be allocated past RLIMIT_FSIZE (a full disk + * alike): the in-place build says so (NYI: the caller builds in memory), + * the file is left at its payload, loads unindexed, and builds once there + * is room. The column is under the parallel threshold: the child has no + * pool workers. */ +static test_result_t test_col_build_hash_index_rollback(void) { +#ifdef RAY_OS_LINUX + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-hidx-rb-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + if (!store_in_place(dir)) { (void)ray_test_rm_rf(dir); SKIP("no in-place build on this filesystem"); } + char p[200]; snprintf(p, sizeof(p), "%s/a", dir); + int64_t n = 50000; + ray_t* v = store_hash_col(RAY_I64, n, 997, 0); + TEST_ASSERT_EQ_I(ray_col_save_bulk(v, p), RAY_OK); + int64_t payload = store_file_size(p); + 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; /* the pad fits, the region doesn't */ + if (signal(SIGXFSZ, SIG_IGN) == SIG_ERR || setrlimit(RLIMIT_FSIZE, &limit)) _exit(2); + _exit(store_hash_build(p) == RAY_ERR_NYI ? 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(store_file_size(p), payload); + ray_t* back = ray_col_mmap(p); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + TEST_ASSERT_FALSE(back->attrs & RAY_ATTR_HAS_INDEX); + TEST_ASSERT_EQ_I(back->len, n); + ray_release(back); + TEST_ASSERT_EQ_I(store_hash_build(p), RAY_OK); + back = ray_col_mmap(p); + 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(); +#else + SKIP("requires Linux RLIMIT_FSIZE fault injection"); +#endif +} + +/* Interrupted at points spread over a build under a budget of many + * batches — before the region is laid out, while it is filled — the build + * reports the cancel and the file is back at its payload, or it completes + * with the uninterrupted bytes. */ +static void store_interrupt_after(void* arg) { + int64_t ns = *(const int64_t*)arg; + struct timespec ts = { (time_t)(ns / 1000000000), (long)(ns % 1000000000) }; + nanosleep(&ts, NULL); + ray_request_interrupt(); +} +static int64_t store_now_ns(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; +} +static test_result_t test_col_build_hash_index_interrupt(void) { + ray_pool_t* pool = ray_pool_get(); + if (!pool || ray_pool_total_workers(pool) < 2) SKIP("needs workers"); + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-hidx-int-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + if (!store_in_place(dir)) { (void)ray_test_rm_rf(dir); SKIP("no in-place build on this filesystem"); } + char p[200], r[200]; + snprintf(p, sizeof(p), "%s/a", dir); + snprintf(r, sizeof(r), "%s/ref", dir); + ray_t* v = store_hash_col(RAY_I64, 500000, 70001, 1013); + ray_heap_set_anon_watermark(INT64_C(64) << 20); /* batches of 128K rows */ + TEST_ASSERT_EQ_I(ray_col_save_bulk(v, r), RAY_OK); + int64_t payload = store_file_size(r); + atomic_store(&pool->cancelled, 1); + TEST_ASSERT_EQ_I(store_hash_build(r), RAY_ERR_CANCEL); + atomic_store(&pool->cancelled, 0); + TEST_ASSERT_EQ_I(store_file_size(r), payload); + int64_t t0 = store_now_ns(); + TEST_ASSERT_EQ_I(store_hash_build(r), RAY_OK); + int64_t took = store_now_ns() - t0; + int64_t cancelled = 0, bad = 0; + for (int k = 0; k < 8; k++) { + if (ray_col_save_bulk(v, p) != RAY_OK) { bad++; continue; } + int64_t delay = took * k / 8; + ray_thread_t th; + TEST_ASSERT_EQ_I(ray_thread_create(&th, store_interrupt_after, &delay), RAY_OK); + ray_err_t e = store_hash_build(p); + ray_thread_join(th); + ray_clear_interrupt(); + if (e == RAY_OK) { if (!store_files_same(p, r)) bad++; continue; } + cancelled++; + if (e != RAY_ERR_CANCEL || store_file_size(p) != payload) bad++; + ray_t* back = ray_col_mmap(p); + if (!back || RAY_IS_ERR(back) || (back->attrs & RAY_ATTR_HAS_INDEX)) bad++; + if (back && !RAY_IS_ERR(back)) ray_release(back); else if (back) ray_error_free(back); + } + ray_heap_set_anon_watermark(0); + TEST_ASSERT_EQ_I(bad, 0); + TEST_ASSERT_TRUE(cancelled > 0); + ray_release(v); (void)ray_test_rm_rf(dir); PASS(); } @@ -3769,13 +4566,13 @@ static test_result_t test_serde_lambda_roundtrip(void) { ray_t* body = ray_i64(42); TEST_ASSERT_NOT_NULL(body); - /* Allocate lambda with 7 pointer slots (same layout as eval.c) */ - ray_t* lambda = ray_alloc(7 * sizeof(ray_t*)); + /* Allocate the lambda with its full slot layout (same as eval.c) */ + ray_t* lambda = ray_alloc(LAMBDA_SLOTS * sizeof(ray_t*)); TEST_ASSERT_NOT_NULL(lambda); TEST_ASSERT_FALSE(RAY_IS_ERR(lambda)); lambda->type = RAY_LAMBDA; lambda->attrs = RAY_FN_COMPILED; lambda->len = 0; - memset(ray_data(lambda), 0, 7 * sizeof(ray_t*)); + memset(ray_data(lambda), 0, LAMBDA_SLOTS * sizeof(ray_t*)); ((ray_t**)ray_data(lambda))[0] = params; ((ray_t**)ray_data(lambda))[1] = body; @@ -3817,6 +4614,88 @@ static test_result_t test_serde_lambda_roundtrip(void) { PASS(); } +/* ---- serde coverage: a lambda's closure must be SYM keys -> LIST values --- */ + +/* The compiled capture binding (OP_BINDCAPS) reads a closure's values as a LIST + * of ray_t*. A wire frame whose closure carries a typed value vector instead + * must be rejected at deserialization, not dereferenced later. */ +static ray_t* make_test_lambda(ray_t* closure) { + int64_t x_id = ray_sym_intern("x", 1); + ray_t* params = ray_vec_new(RAY_SYM, 1); + if (!params || RAY_IS_ERR(params)) return params; + params->len = 1; + ((int64_t*)ray_data(params))[0] = x_id; + ray_t* lambda = ray_alloc(LAMBDA_SLOTS * sizeof(ray_t*)); + if (!lambda || RAY_IS_ERR(lambda)) { ray_release(params); return lambda; } + lambda->type = RAY_LAMBDA; + lambda->attrs = 0; + lambda->len = 0; + memset(ray_data(lambda), 0, LAMBDA_SLOTS * sizeof(ray_t*)); + LAMBDA_PARAMS(lambda) = params; + LAMBDA_BODY(lambda) = ray_i64(42); + LAMBDA_CLOSURE(lambda) = closure; + return lambda; +} + +static test_result_t test_serde_lambda_malformed_closure(void) { + int64_t k_id = ray_sym_intern("k", 1); + + /* Control: a closure of SYM keys -> LIST values round-trips. */ + ray_t* keys = ray_vec_new(RAY_SYM, 1); + TEST_ASSERT_NOT_NULL(keys); TEST_ASSERT_FALSE(RAY_IS_ERR(keys)); + keys->len = 1; + ((int64_t*)ray_data(keys))[0] = k_id; + ray_t* vals = ray_list_new(1); + TEST_ASSERT_NOT_NULL(vals); TEST_ASSERT_FALSE(RAY_IS_ERR(vals)); + ((ray_t**)ray_data(vals))[0] = ray_i64(7); + vals->len = 1; + ray_t* good = make_test_lambda(ray_dict_new(keys, vals)); + TEST_ASSERT_NOT_NULL(good); TEST_ASSERT_FALSE(RAY_IS_ERR(good)); + ray_t* w = ray_ser(good); + TEST_ASSERT_NOT_NULL(w); TEST_ASSERT_FALSE(RAY_IS_ERR(w)); + ray_t* back = ray_de(w); + TEST_ASSERT_NOT_NULL(back); TEST_ASSERT_FALSE(RAY_IS_ERR(back)); + TEST_ASSERT_EQ_I(back->type, RAY_LAMBDA); + TEST_ASSERT_NOT_NULL(LAMBDA_CLOSURE(back)); + TEST_ASSERT_EQ_I(ray_dict_vals(LAMBDA_CLOSURE(back))->type, RAY_LIST); + ray_release(back); ray_release(w); ray_release(good); + + /* A closure whose values are a typed vector is refused. */ + keys = ray_vec_new(RAY_SYM, 1); + TEST_ASSERT_NOT_NULL(keys); TEST_ASSERT_FALSE(RAY_IS_ERR(keys)); + keys->len = 1; + ((int64_t*)ray_data(keys))[0] = k_id; + ray_t* ivals = ray_vec_new(RAY_I64, 1); + TEST_ASSERT_NOT_NULL(ivals); TEST_ASSERT_FALSE(RAY_IS_ERR(ivals)); + ((int64_t*)ray_data(ivals))[0] = 0x4141414141414141LL; + ivals->len = 1; + ray_t* bad = make_test_lambda(ray_dict_new(keys, ivals)); + TEST_ASSERT_NOT_NULL(bad); TEST_ASSERT_FALSE(RAY_IS_ERR(bad)); + w = ray_ser(bad); + TEST_ASSERT_NOT_NULL(w); TEST_ASSERT_FALSE(RAY_IS_ERR(w)); + back = ray_de(w); + TEST_ASSERT_NOT_NULL(back); + TEST_ASSERT(RAY_IS_ERR(back), "typed closure values must be rejected by the deserializer"); + ray_error_free(back); + ray_release(w); ray_release(bad); + + /* A closure that is not a dict at all is refused too. */ + ray_t* notdict = ray_vec_new(RAY_I64, 1); + TEST_ASSERT_NOT_NULL(notdict); TEST_ASSERT_FALSE(RAY_IS_ERR(notdict)); + ((int64_t*)ray_data(notdict))[0] = 1; + notdict->len = 1; + bad = make_test_lambda(notdict); + TEST_ASSERT_NOT_NULL(bad); TEST_ASSERT_FALSE(RAY_IS_ERR(bad)); + w = ray_ser(bad); + TEST_ASSERT_NOT_NULL(w); TEST_ASSERT_FALSE(RAY_IS_ERR(w)); + back = ray_de(w); + TEST_ASSERT_NOT_NULL(back); + TEST_ASSERT(RAY_IS_ERR(back), "a non-dict closure must be rejected by the deserializer"); + ray_error_free(back); + ray_release(w); ray_release(bad); + PASS(); +} + /* ---- serde coverage: ray_obj_save serialization failure path ------------- */ /* ray_obj_save calls ray_ser(obj) first; if that returns error (e.g. object @@ -5333,6 +6212,10 @@ static test_result_t test_col_str_legacy_hash_repair(void) { TEST_ASSERT_EQ_U(fwrite(&garbage[i], 1, sizeof(garbage[i]), f), sizeof(garbage[i])); } + /* A legacy writer also left the header's rc at 0: no hash mark. */ + uint32_t legacy_rc = 0; + TEST_ASSERT_EQ_I(fseek(f, (long)offsetof(ray_t, rc), SEEK_SET), 0); + TEST_ASSERT_EQ_U(fwrite(&legacy_rc, 1, sizeof(legacy_rc), f), sizeof(legacy_rc)); TEST_ASSERT_EQ_I(fclose(f), 0); ray_t* loaded = ray_col_load(TMP_COL_PATH); @@ -5384,6 +6267,576 @@ static test_result_t test_col_str_legacy_hash_repair(void) { PASS(); } +/* ---- test_col_str_hash_persisted --------------------------------------- */ +/* A current writer stores every pooled descriptor's content hash and marks + * the header, so the loaders take the descriptors as written: no pass over + * the pool, no write into the private mapping. Hashes the column has not + * cached yet are computed on save. */ +static test_result_t test_col_str_hash_persisted(void) { + const char* same = "persisted-pooled-string-value"; + const char* other = "another-pooled-string-value"; + ray_t* vec = ray_vec_new(RAY_STR, 3); + TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); + vec = ray_str_vec_append(vec, same, strlen(same)); + TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); + vec = ray_str_vec_append(vec, same, strlen(same)); + TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); + vec = ray_str_vec_append(vec, other, strlen(other)); + TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); + ray_str_t* vd = (ray_str_t*)ray_data(vec); + const char* vpool = (const char*)ray_data(vec->str_pool); + uint32_t expect[3]; + for (int i = 0; i < 3; i++) { + expect[i] = ray_str_t_hash32(&vd[i], vpool); + vd[i].hash32 = 0; /* lazy state: the writer must fill it */ + } + TEST_ASSERT_EQ_I(ray_col_save(vec, TMP_COL_PATH), RAY_OK); + + /* On disk: the mark in rc, the hash in every pooled descriptor. */ + FILE* f = fopen(TMP_COL_PATH, "r+b"); + TEST_ASSERT_NOT_NULL(f); + uint32_t disk_rc = 0; + TEST_ASSERT_EQ_I(fseek(f, (long)offsetof(ray_t, rc), SEEK_SET), 0); + TEST_ASSERT_EQ_U(fread(&disk_rc, 1, sizeof(disk_rc), f), sizeof(disk_rc)); + TEST_ASSERT_EQ_U(disk_rc, RAY_COL_STR_HASHED); + for (int i = 0; i < 3; i++) { + uint32_t stored = 0; + TEST_ASSERT_EQ_I(fseek(f, 32L + (long)i * 16L + 12L, SEEK_SET), 0); + TEST_ASSERT_EQ_U(fread(&stored, 1, sizeof(stored), f), sizeof(stored)); + TEST_ASSERT_EQ_U(stored, expect[i]); + } + /* Forge one stored hash. A marked file is taken as written, which is + * only observable this way: the loaders must not recompute it. */ + const uint32_t forged = 0x5A5A5A5Au; + TEST_ASSERT_EQ_I(fseek(f, 32L + 2L * 16L + 12L, SEEK_SET), 0); + TEST_ASSERT_EQ_U(fwrite(&forged, 1, sizeof(forged), f), sizeof(forged)); + TEST_ASSERT_EQ_I(fclose(f), 0); + + ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + TEST_ASSERT_NOT_NULL(mapped); + TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); + ray_str_t* md = (ray_str_t*)ray_data(mapped); + TEST_ASSERT_EQ_U(md[0].hash32, expect[0]); + TEST_ASSERT_EQ_U(md[1].hash32, expect[1]); + TEST_ASSERT_EQ_U(md[2].hash32, forged); + ray_release(mapped); + + ray_t* loaded = ray_col_load(TMP_COL_PATH); + TEST_ASSERT_NOT_NULL(loaded); + TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); + ray_str_t* ld = (ray_str_t*)ray_data(loaded); + TEST_ASSERT_EQ_U(ld[0].hash32, expect[0]); + TEST_ASSERT_EQ_U(ld[2].hash32, forged); + ray_release(loaded); + + ray_release(vec); + unlink(TMP_COL_PATH); + PASS(); +} + +/* ---- test_stream_str_hash_persisted ------------------------------------- */ +/* The streaming writer (CSV and parquet imports) stores the same hashes and + * the same mark as ray_col_save, including for a column whose in-memory + * hashes were never computed. */ +static test_result_t test_stream_str_hash_persisted(void) { + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-strhash-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + const char* s0 = "streamed-pooled-string-value"; + const char* s1 = "short"; + const char* s2 = "second-streamed-pooled-value"; + ray_t* v = ray_vec_new(RAY_STR, 3); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + v = ray_str_vec_append(v, s0, strlen(s0)); + v = ray_str_vec_append(v, s1, strlen(s1)); + v = ray_str_vec_append(v, s2, strlen(s2)); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + ray_str_t* vd = (ray_str_t*)ray_data(v); + const char* vpool = (const char*)ray_data(v->str_pool); + uint32_t expect[3]; + for (int i = 0; i < 3; i++) { + expect[i] = ray_str_t_hash32(&vd[i], vpool); + if (!ray_str_is_inline(&vd[i])) vd[i].hash32 = 0; + } + ray_col_stream_t w; + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("s", 1), RAY_STR, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_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); + FILE* f = fopen(path, "rb"); + TEST_ASSERT_NOT_NULL(f); + uint32_t disk_rc = 0; + TEST_ASSERT_EQ_I(fseek(f, (long)offsetof(ray_t, rc), SEEK_SET), 0); + TEST_ASSERT_EQ_U(fread(&disk_rc, 1, sizeof(disk_rc), f), sizeof(disk_rc)); + TEST_ASSERT_EQ_U(disk_rc, RAY_COL_STR_HASHED); + TEST_ASSERT_EQ_I(fclose(f), 0); + + ray_t* back = ray_col_mmap(path); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + ray_str_t* bd = (ray_str_t*)ray_data(back); + const char* bpool = (const char*)ray_data(back->str_pool); + TEST_ASSERT_EQ_U(bd[0].hash32, expect[0]); + TEST_ASSERT_EQ_U(bd[2].hash32, expect[2]); + TEST_ASSERT_TRUE(ray_str_is_inline(&bd[1])); + TEST_ASSERT_EQ_U(ray_str_t_hash32(&bd[1], bpool), expect[1]); + /* And the stored value is the content hash of the bytes on disk. */ + TEST_ASSERT_EQ_U(bd[0].hash32, (uint32_t)ray_str_t_hash(&bd[0], bpool)); + ray_release(back); ray_release(v); + (void)ray_test_rm_rf(dir); + PASS(); +} + +/* ---- test_parted_remount_reuse ------------------------------------------ */ +/* A second ray_read_parted of the same root returns the very same segment + * vectors for partitions whose files did not change, loads a replaced + * partition afresh, and ray_parted_cache_clear forgets everything. */ +#define TMP_PARTED_ROOT "/tmp/rayforce_test_parted_remount" +static ray_t* parted_remount_part(int64_t base) { + int64_t raw[3] = { base, base + 1, base + 2 }; + ray_t* v = ray_vec_from_raw(RAY_I64, raw, 3); + ray_t* tbl = ray_table_new(1); + tbl = ray_table_add_col(tbl, ray_sym_intern("v", 1), v); + ray_release(v); + return tbl; +} +static test_result_t test_parted_remount_reuse(void) { + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(TMP_PARTED_ROOT "/2024.01.01"), 0); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(TMP_PARTED_ROOT "/2024.01.02"), 0); + ray_t* a = parted_remount_part(10); + ray_t* b = parted_remount_part(20); + TEST_ASSERT_EQ_I(ray_splay_save(a, TMP_PARTED_ROOT "/2024.01.01/t", NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(b, TMP_PARTED_ROOT "/2024.01.02/t", NULL), RAY_OK); + + ray_t* m1 = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(m1 && !RAY_IS_ERR(m1)); + ray_t** s1 = (ray_t**)ray_data(ray_table_get_col_idx(m1, 1)); + ray_t* m2 = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(m2 && !RAY_IS_ERR(m2)); + ray_t** s2 = (ray_t**)ray_data(ray_table_get_col_idx(m2, 1)); + /* Unchanged root: both partitions are the same mapped vectors. */ + TEST_ASSERT_EQ_PTR(s1[0], s2[0]); + TEST_ASSERT_EQ_PTR(s1[1], s2[1]); + TEST_ASSERT_TRUE(ray_atomic_load(&s1[0]->rc) >= 3); /* two results + the cache */ + + /* Replace the second partition: a fresh vector there, the first kept. */ + ray_t* c = parted_remount_part(30); + TEST_ASSERT_EQ_I(ray_splay_save(c, TMP_PARTED_ROOT "/2024.01.02/t", NULL), RAY_OK); + ray_t* m3 = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(m3 && !RAY_IS_ERR(m3)); + ray_t** s3 = (ray_t**)ray_data(ray_table_get_col_idx(m3, 1)); + TEST_ASSERT_EQ_PTR(s3[0], s1[0]); + TEST_ASSERT_TRUE(s3[1] != s1[1]); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(s3[1]))[0], 30); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(s1[1]))[0], 20); /* the old view keeps its rows */ + + /* Forgotten: the next mount maps everything again. */ + ray_parted_cache_clear(); + ray_t* m4 = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(m4 && !RAY_IS_ERR(m4)); + ray_t** s4 = (ray_t**)ray_data(ray_table_get_col_idx(m4, 1)); + TEST_ASSERT_TRUE(s4[0] != s1[0]); + TEST_ASSERT_EQ_I(ray_table_nrows(m4), 6); + + ray_release(m1); ray_release(m2); ray_release(m3); ray_release(m4); + ray_release(a); ray_release(b); ray_release(c); + ray_parted_cache_clear(); + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + PASS(); +} + +#ifdef RAY_OS_LINUX +/* Check the mappings themselves: the legacy numeric-column unmap path + * rounds its accounting subtraction up to a page, unlike the map charge. */ +static int parted_mapping_count(void) { + FILE* f = fopen("/proc/self/maps", "r"); + if (!f) return -1; + int count = 0; + char line[4096]; + while (fgets(line, sizeof(line), f)) + if (strstr(line, TMP_PARTED_ROOT)) count++; + fclose(f); + return count; +} +#endif + +/* A dropped LIST view must release its copied payload and mapped columns + * on GC, including when the directory has already disappeared. */ +static test_result_t test_parted_cache_gc(void) { + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + ray_t* items = ray_list_new(16384); + for (int i = 0; i < 16384; i++) { + ray_t* item = ray_i64(i); + items = ray_list_append(items, item); + ray_release(item); + } + ray_t* src = ray_table_new(2); + src = ray_table_add_col(src, ray_sym_intern("v", 1), items); + ray_release(items); + ray_t* nums = ray_vec_new(RAY_I64, 16384); + nums->len = 16384; + memset(ray_data(nums), 0, 16384 * sizeof(int64_t)); + src = ray_table_add_col(src, ray_sym_intern("n", 1), nums); + ray_release(nums); + TEST_ASSERT_EQ_I(ray_splay_save(src, TMP_PARTED_ROOT "/1/t", NULL), RAY_OK); + ray_mem_stats_t before, mounted, after; + ray_mem_stats(&before); + ray_t* view = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(view && !RAY_IS_ERR(view)); + ray_t* seg = ((ray_t**)ray_data(ray_table_get_col_idx(view, 1)))[0]; + ray_heap_gc(); + TEST_ASSERT_EQ_U(ray_atomic_load(&seg->rc), 2); /* live views keep reuse */ + ray_mem_stats(&mounted); +#ifdef RAY_OS_LINUX + TEST_ASSERT_TRUE(parted_mapping_count() > 0); +#endif + TEST_ASSERT_TRUE(mounted.bytes_allocated > before.bytes_allocated + 500000); + ray_release(view); + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + ray_heap_gc(); + ray_mem_stats(&after); + TEST_ASSERT_TRUE(after.bytes_allocated <= before.bytes_allocated + 4096); +#ifdef RAY_OS_LINUX + TEST_ASSERT_EQ_I(parted_mapping_count(), 0); +#endif + ray_release(src); + PASS(); +} + +static ray_t* parted_symbol_part(const char* value) { + int64_t id = ray_sym_intern(value, strlen(value)); + ray_t* col = ray_vec_from_raw(RAY_SYM, &id, 1); + ray_t* tbl = ray_table_new(1); + tbl = ray_table_add_col(tbl, ray_sym_intern("s", 1), col); + ray_release(col); + return tbl; +} + +/* Recreating a root after dropping its view must not find a dictionary + * pinned only by the cache, with or without explicit GC before the write. + * Cover both equal-size and differently sized symbols. */ +static test_result_t parted_rebuilt_symbols(bool collect) { + const char* values[] = { "aa", "xx", "longer" }; + for (int i = 0; i < 3; i++) { + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + ray_t* src = parted_symbol_part(values[i]); + TEST_ASSERT_EQ_I(ray_splay_save(src, TMP_PARTED_ROOT "/1/t", + TMP_PARTED_ROOT "/.sym"), RAY_OK); + ray_release(src); + ray_t* view = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(view && !RAY_IS_ERR(view)); + ray_t* seg = ((ray_t**)ray_data(ray_table_get_col_idx(view, 1)))[0]; + int64_t pos = ray_read_sym(ray_data(seg), 0, seg->type, seg->attrs); + ray_t* value = ray_sym_domain_str(ray_sym_vec_domain(seg), pos); + TEST_ASSERT_EQ_U(ray_str_len(value), strlen(values[i])); + TEST_ASSERT_TRUE(memcmp(ray_str_ptr(value), values[i], strlen(values[i])) == 0); + ray_release(view); + if (collect) ray_heap_gc(); + } + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + PASS(); +} + +static test_result_t test_parted_rebuilt_symbols(void) { + return parted_rebuilt_symbols(true); +} + +static test_result_t test_parted_rebuilt_write_without_gc(void) { + return parted_rebuilt_symbols(false); +} + +/* A filesystem publisher can replace the root without a GC call in the + * reader. Both parted and splayed reads must discard unused cached domains. */ +static test_result_t parted_rebuilt_read_without_gc(bool parted) { + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + (void)ray_test_rm_rf(TMP_PARTED_ROOT "_next"); + ray_t* a = parted_symbol_part("aa"); + ray_t* b = parted_symbol_part("xx"); + TEST_ASSERT_EQ_I(ray_splay_save(a, TMP_PARTED_ROOT "/1/t", + TMP_PARTED_ROOT "/.sym"), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(b, TMP_PARTED_ROOT "_next/1/t", + TMP_PARTED_ROOT "_next/.sym"), RAY_OK); + ray_t* old = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(old && !RAY_IS_ERR(old)); + ray_release(old); + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + TEST_ASSERT_EQ_I(rename(TMP_PARTED_ROOT "_next", TMP_PARTED_ROOT), 0); + ray_t* fresh = parted ? ray_read_parted(TMP_PARTED_ROOT, "t") + : ray_read_splayed(TMP_PARTED_ROOT "/1/t", TMP_PARTED_ROOT "/.sym"); + TEST_ASSERT_TRUE(fresh && !RAY_IS_ERR(fresh)); + ray_t* seg = ray_table_get_col_idx(fresh, parted ? 1 : 0); + if (parted) seg = ((ray_t**)ray_data(seg))[0]; + int64_t pos = ray_read_sym(ray_data(seg), 0, seg->type, seg->attrs); + ray_t* value = ray_sym_domain_str(ray_sym_vec_domain(seg), pos); + TEST_ASSERT_EQ_U(ray_str_len(value), 2); + TEST_ASSERT_TRUE(memcmp(ray_str_ptr(value), "xx", 2) == 0); + ray_release(fresh); ray_release(a); ray_release(b); + ray_heap_gc(); + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + PASS(); +} + +static test_result_t test_parted_rebuilt_without_gc(void) { + return parted_rebuilt_read_without_gc(true); +} + +static test_result_t test_parted_rebuilt_splayed_without_gc(void) { + return parted_rebuilt_read_without_gc(false); +} + +/* Opening an unrelated domain must preserve partitions held by a live view. */ +static test_result_t test_parted_live_domain_open(void) { + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + (void)ray_test_rm_rf(TMP_PARTED_ROOT "_next"); + ray_t* a = parted_symbol_part("aa"); + ray_t* b = parted_symbol_part("xx"); + TEST_ASSERT_EQ_I(ray_splay_save(a, TMP_PARTED_ROOT "/1/t", + TMP_PARTED_ROOT "/.sym"), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(b, TMP_PARTED_ROOT "_next/1/t", + TMP_PARTED_ROOT "_next/.sym"), RAY_OK); + ray_t* view = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(view && !RAY_IS_ERR(view)); + ray_t* seg = ((ray_t**)ray_data(ray_table_get_col_idx(view, 1)))[0]; + TEST_ASSERT_EQ_I(ray_atomic_load(&seg->rc), 2); + + ray_t* other = ray_read_splayed(TMP_PARTED_ROOT "_next/1/t", + TMP_PARTED_ROOT "_next/.sym"); + TEST_ASSERT_TRUE(other && !RAY_IS_ERR(other)); + TEST_ASSERT_EQ_I(ray_atomic_load(&seg->rc), 2); + ray_t* remount = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(remount && !RAY_IS_ERR(remount)); + TEST_ASSERT_EQ_PTR(((ray_t**)ray_data(ray_table_get_col_idx(remount, 1)))[0], seg); + int64_t pos = ray_read_sym(ray_data(seg), 0, seg->type, seg->attrs); + ray_t* value = ray_sym_domain_str(ray_sym_vec_domain(seg), pos); + TEST_ASSERT_EQ_U(ray_str_len(value), 2); + TEST_ASSERT_TRUE(memcmp(ray_str_ptr(value), "aa", 2) == 0); + + ray_release(remount); ray_release(other); ray_release(view); + ray_release(a); ray_release(b); + ray_parted_cache_clear(); + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + (void)ray_test_rm_rf(TMP_PARTED_ROOT "_next"); + PASS(); +} + +static test_result_t test_parted_missing_symfile(void) { + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + ray_t* src = parted_symbol_part("aa"); + TEST_ASSERT_EQ_I(ray_splay_save(src, TMP_PARTED_ROOT "/1/t", + TMP_PARTED_ROOT "/.sym"), RAY_OK); + ray_release(src); + ray_t* view = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(view && !RAY_IS_ERR(view)); + TEST_ASSERT_EQ_I(unlink(TMP_PARTED_ROOT "/.sym"), 0); + ray_t* missing = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_ERR_CODE_MSG(missing, "sym", "no symfile resolved"); + ray_error_free(missing); + ray_release(view); + ray_parted_cache_clear(); + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + PASS(); +} + +/* Same inode, size and mtime: a copied LIST payload must still reload. + * Numeric mmap payloads alone cannot detect a bad cache hit here because + * an in-place write is already visible through the old mapping. */ +static test_result_t test_parted_restored_mtime(void) { +#ifdef RAY_OS_WINDOWS + SKIP("nanosecond timestamp restoration requires POSIX"); +#else + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + ray_t* items = ray_list_new(1); + ray_t* value = ray_i64(10); + items = ray_list_append(items, value); + ray_release(value); + ray_t* src = ray_table_new(1); + src = ray_table_add_col(src, ray_sym_intern("v", 1), items); + ray_release(items); + TEST_ASSERT_EQ_I(ray_splay_save(src, TMP_PARTED_ROOT "/1/t", NULL), RAY_OK); + ray_t* m1 = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(m1 && !RAY_IS_ERR(m1)); + ray_t* s1 = ((ray_t**)ray_data(ray_table_get_col_idx(m1, 1)))[0]; + const char* path = TMP_PARTED_ROOT "/1/t/v"; + struct stat st; + TEST_ASSERT_EQ_I(stat(path, &st), 0); + struct timespec times[2]; +#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) + /* Darwin's POSIX namespace exposes seconds/nanoseconds separately. */ + times[0] = (struct timespec){ st.st_atime, st.st_atimensec }; + times[1] = (struct timespec){ st.st_mtime, st.st_mtimensec }; +#elif defined(__APPLE__) + times[0] = st.st_atimespec; times[1] = st.st_mtimespec; +#else + times[0] = st.st_atim; times[1] = st.st_mtim; +#endif + /* Let ctime advance even on filesystems with coarse clocks. */ + struct timespec pause = {1, 0}; + nanosleep(&pause, NULL); + FILE* f = fopen(path, "r+b"); + TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_EQ_I(fseek(f, -8, SEEK_END), 0); + int64_t changed = 99; + TEST_ASSERT_EQ_U(fwrite(&changed, 1, 8, f), 8); + TEST_ASSERT_EQ_I(fclose(f), 0); + TEST_ASSERT_EQ_I(utimensat(AT_FDCWD, path, times, 0), 0); + ray_t* m2 = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(m2 && !RAY_IS_ERR(m2)); + ray_t* s2 = ((ray_t**)ray_data(ray_table_get_col_idx(m2, 1)))[0]; + TEST_ASSERT_TRUE(s1 != s2); + TEST_ASSERT_EQ_I(((ray_t**)ray_data(s1))[0]->i64, 10); + TEST_ASSERT_EQ_I(((ray_t**)ray_data(s2))[0]->i64, 99); + ray_release(m1); ray_release(m2); ray_release(src); + ray_parted_cache_clear(); + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + PASS(); +#endif +} + +/* Both generations remain intact: their file signatures cannot substitute + * for comparing the resolved directory. Also prove the sweep drops refs. */ +static test_result_t test_parted_generation_and_sweep(void) { + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + ray_t* a = parted_remount_part(10); + ray_t* b = parted_remount_part(20); + TEST_ASSERT_EQ_I(ray_splay_save(a, TMP_PARTED_ROOT "/1/t", NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(b, TMP_PARTED_ROOT "/2/t", NULL), RAY_OK); + ray_t* m1 = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(m1 && !RAY_IS_ERR(m1)); + ray_t** s1 = (ray_t**)ray_data(ray_table_get_col_idx(m1, 1)); + TEST_ASSERT_EQ_I(ray_splay_save(b, TMP_PARTED_ROOT "/1/t/.generations/g-1", NULL), RAY_OK); + FILE* f = fopen(TMP_PARTED_ROOT "/1/t/.current", "wb"); + TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_TRUE(fputs(".generations/g-1\n", f) >= 0); + TEST_ASSERT_EQ_I(fclose(f), 0); + (void)ray_test_rm_rf(TMP_PARTED_ROOT "/2"); + ray_t* m2 = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(m2 && !RAY_IS_ERR(m2)); + ray_t* s2 = ((ray_t**)ray_data(ray_table_get_col_idx(m2, 1)))[0]; + TEST_ASSERT_TRUE(s1[0] != s2); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(s2))[0], 20); + TEST_ASSERT_EQ_U(ray_atomic_load(&s1[1]->rc), 1); /* deleted partition swept */ + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + ray_t* missing = ray_read_parted(TMP_PARTED_ROOT, "t"); + TEST_ASSERT_TRUE(RAY_IS_ERR(missing)); + ray_error_free(missing); + TEST_ASSERT_EQ_U(ray_atomic_load(&s2->rc), 1); /* failed mount sweeps too */ + ray_release(m1); ray_release(m2); ray_release(a); ray_release(b); + PASS(); +} + +/* The limit applies across roots/tables even when every view remains live. + * Eviction only drops the cache's reference, so the oldest view still reads. */ +static test_result_t test_parted_cache_limit(void) { + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + ray_t* src = parted_remount_part(10); + ray_t* views[1025]; + for (int i = 0; i < 1025; i++) { + char path[128], name[24]; + snprintf(name, sizeof(name), "t%d", i); + snprintf(path, sizeof(path), "%s/1/%s", TMP_PARTED_ROOT, name); + TEST_ASSERT_EQ_I(ray_splay_save_bulk(src, path, NULL), RAY_OK); + views[i] = ray_read_parted(TMP_PARTED_ROOT, name); + TEST_ASSERT_TRUE(views[i] && !RAY_IS_ERR(views[i])); + } + ray_t* first = ((ray_t**)ray_data(ray_table_get_col_idx(views[0], 1)))[0]; + ray_t* last = ((ray_t**)ray_data(ray_table_get_col_idx(views[1024], 1)))[0]; + TEST_ASSERT_EQ_U(ray_atomic_load(&first->rc), 1); + TEST_ASSERT_EQ_U(ray_atomic_load(&last->rc), 2); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(first))[0], 10); + for (int i = 0; i < 1025; i++) ray_release(views[i]); + ray_heap_gc(); + ray_release(src); + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + PASS(); +} + +typedef struct { atomic_int* ready; atomic_bool* go; bool ok; } parted_thread_t; +static void parted_mount_thread(void* arg) { + parted_thread_t* ctx = arg; + ray_heap_init(); + atomic_fetch_add(ctx->ready, 1); + while (!atomic_load(ctx->go)) ray_sleep_ms(1); + ctx->ok = true; + for (int i = 0; i < 100 && ctx->ok; i++) { + ray_t* a = ray_read_parted(TMP_PARTED_ROOT, "t"); + ray_t* b = ray_read_parted(TMP_PARTED_ROOT, "t"); + ctx->ok = a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b); + if (ctx->ok) { + ray_t* sa = ((ray_t**)ray_data(ray_table_get_col_idx(a, 1)))[0]; + ray_t* sb = ((ray_t**)ray_data(ray_table_get_col_idx(b, 1)))[0]; + ctx->ok = sa == sb && ((int64_t*)ray_data(sa))[0] == 10; + } + if (i % 3 == 1) ray_parted_cache_clear(); + ray_release(a); ray_release(b); + } + /* Must release this thread's cache even if its heap is adopted later. */ + ray_heap_abandon(); +} + +static test_result_t test_parted_concurrent_mounts(void) { + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + ray_t* src = parted_remount_part(10); + TEST_ASSERT_EQ_I(ray_splay_save(src, TMP_PARTED_ROOT "/1/t", NULL), RAY_OK); + atomic_int ready = 0; + atomic_bool go = false; + parted_thread_t ctx[4]; + ray_thread_t threads[4]; + for (int i = 0; i < 4; i++) { + ctx[i] = (parted_thread_t){ &ready, &go, false }; + TEST_ASSERT_EQ_I(ray_thread_create(&threads[i], parted_mount_thread, &ctx[i]), RAY_OK); + } + while (atomic_load(&ready) < 4) ray_sleep_ms(1); + atomic_store(&go, true); + for (int i = 0; i < 4; i++) TEST_ASSERT_EQ_I(ray_thread_join(threads[i]), RAY_OK); + for (int i = 0; i < 4; i++) TEST_ASSERT_TRUE(ctx[i].ok); +#ifdef RAY_OS_LINUX + TEST_ASSERT_EQ_I(parted_mapping_count(), 0); +#endif + ray_release(src); + (void)ray_test_rm_rf(TMP_PARTED_ROOT); + PASS(); +} + +/* Nested files have no persisted-hash marker. Garbage hash bytes must be + * reset by their loader, while inline strings keep their payload bytes. */ +static test_result_t test_col_nested_str_hash_reset(void) { + ray_t* v = ray_vec_new(RAY_STR, 2); + v = ray_str_vec_append(v, "nested-pooled-string-value", 25); + v = ray_str_vec_append(v, "inline", 6); + ((ray_str_t*)ray_data(v))[0].hash32 = 0x12345678; + ray_t* list = ray_list_new(1); + list = ray_list_append(list, v); + TEST_ASSERT_EQ_I(ray_col_save(list, TMP_COL_PATH), RAY_OK); + ray_t* back = ray_col_load(TMP_COL_PATH); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + ray_t* nested = ((ray_t**)ray_data(back))[0]; + ray_str_t* desc = (ray_str_t*)ray_data(nested); + TEST_ASSERT_EQ_U(desc[0].hash32, 0); + size_t len = 0; + const char* str = ray_str_vec_get(nested, 1, &len); + TEST_ASSERT_EQ_U(len, 6); + TEST_ASSERT_TRUE(memcmp(str, "inline", 6) == 0); + ray_release(back); ray_release(list); ray_release(v); + unlink(TMP_COL_PATH); + PASS(); +} + +static test_result_t test_col_save_str_bounds(void) { + ray_t* v = ray_vec_new(RAY_STR, 1); + v = ray_str_vec_append(v, "pooled-string-out-of-bounds", 26); + ray_str_t* desc = (ray_str_t*)ray_data(v); + uint32_t old_off = desc[0].pool_off; + desc[0].pool_off = UINT32_MAX; + TEST_ASSERT_EQ_I(ray_col_save(v, TMP_COL_PATH), RAY_ERR_CORRUPT); + desc[0].pool_off = old_off; + desc[0].len = UINT32_MAX; + TEST_ASSERT_EQ_I(ray_col_save(v, TMP_COL_PATH), RAY_ERR_CORRUPT); + desc[0].len = 26; + ray_release(v); + unlink(TMP_COL_PATH); + PASS(); +} + /* ---- test_col_format_version_roundtrip ---------------------------------- */ /* A saved column carries the format generation in the 32-byte header's * `order` byte (offset 17), with aux (bytes 0-15) ZERO on disk (no magic — @@ -6230,6 +7683,22 @@ const test_entry_t store_entries[] = { { "store/col_sym_w64_neg_index", test_col_sym_w64_negative_index, store_setup, store_teardown }, { "store/col_str_pool_roundtrip", test_col_str_pool_roundtrip, store_setup, store_teardown }, { "store/col_str_legacy_hash_repair", test_col_str_legacy_hash_repair, store_setup, store_teardown }, + { "store/col_str_hash_persisted", test_col_str_hash_persisted, store_setup, store_teardown }, + { "store/stream_str_hash_persisted", test_stream_str_hash_persisted, store_setup, store_teardown }, + { "store/parted_cache_limit", test_parted_cache_limit, store_setup, store_teardown }, + { "store/parted_cache_gc", test_parted_cache_gc, store_setup, store_teardown }, + { "store/parted_live_domain_open", test_parted_live_domain_open, store_setup, store_teardown }, + { "store/parted_rebuilt_write_without_gc", test_parted_rebuilt_write_without_gc, store_setup, store_teardown }, + { "store/parted_rebuilt_splayed_without_gc", test_parted_rebuilt_splayed_without_gc, store_setup, store_teardown }, + { "store/parted_rebuilt_without_gc", test_parted_rebuilt_without_gc, store_setup, store_teardown }, + { "store/parted_rebuilt_symbols", test_parted_rebuilt_symbols, store_setup, store_teardown }, + { "store/parted_missing_symfile", test_parted_missing_symfile, store_setup, store_teardown }, + { "store/parted_restored_mtime", test_parted_restored_mtime, store_setup, store_teardown }, + { "store/parted_generation_and_sweep", test_parted_generation_and_sweep, store_setup, store_teardown }, + { "store/parted_concurrent_mounts", test_parted_concurrent_mounts, store_setup, store_teardown }, + { "store/col_nested_str_hash_reset", test_col_nested_str_hash_reset, store_setup, store_teardown }, + { "store/col_save_str_bounds", test_col_save_str_bounds, store_setup, store_teardown }, + { "store/parted_remount_reuse", test_parted_remount_reuse, store_setup, store_teardown }, { "store/col_format_version_roundtrip", test_col_format_version_roundtrip, store_setup, store_teardown }, { "store/col_format_bad_version", test_col_format_bad_version, store_setup, store_teardown }, { "store/col_str_empty_roundtrip", test_col_str_empty_roundtrip, store_setup, store_teardown }, @@ -6262,9 +7731,22 @@ const test_entry_t store_entries[] = { { "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_sym_chunks", test_stream_sym_chunks, store_setup, store_teardown }, + { "store/stream_sym_from_str", test_stream_sym_from_str, store_setup, store_teardown }, + { "store/stream_sym_foreign", test_stream_sym_foreign, store_setup, store_teardown }, + { "store/stream_sym_lut_stale", test_stream_sym_lut_stale, store_setup, store_teardown }, { "store/stream_index_write_failure", test_stream_index_write_failure_drops_index, store_setup, store_teardown }, { "store/stream_inline_zone_one_chunk", test_stream_inline_zone_one_chunk, store_setup, store_teardown }, { "store/stream_hash_candidate", test_stream_hash_candidate, store_setup, store_teardown }, + { "store/col_build_hash_index_bytes", test_col_build_hash_index_bytes, store_setup, store_teardown }, + { "store/col_build_hash_index_refusals", test_col_build_hash_index_refusals, store_setup, store_teardown }, + { "store/col_build_hash_index_untrusted_fs", test_col_build_hash_index_untrusted_fs, store_setup, store_teardown }, + { "store/col_build_hash_index_fs_types", test_col_build_hash_index_fs_types, store_setup, store_teardown }, + { "store/col_build_hash_index_refused", test_col_build_hash_index_refused, store_setup, store_teardown }, + { "store/col_build_hash_index_truncate", test_col_build_hash_index_truncate, store_setup, store_teardown }, + { "store/col_build_hash_index_marker_last", test_col_build_hash_index_marker_last, store_setup, store_teardown }, + { "store/col_build_hash_index_rollback", test_col_build_hash_index_rollback, store_setup, store_teardown }, + { "store/col_build_hash_index_interrupt", test_col_build_hash_index_interrupt, store_setup, store_teardown }, { "store/stream_inline_dict", test_stream_inline_dict, store_setup, store_teardown }, { "store/stream_hash_wave", test_stream_hash_wave, store_setup, store_teardown }, { "store/stream_region_bytes", test_stream_region_bytes_match, store_setup, store_teardown }, @@ -6299,6 +7781,7 @@ const test_entry_t store_entries[] = { { "store/serde_large_null_vec", test_serde_large_null_vec, store_setup, store_teardown }, { "store/serde_f32_atom", test_serde_f32_atom_and_edge_cases, store_setup, store_teardown }, { "store/serde_lambda_roundtrip", test_serde_lambda_roundtrip, store_setup, store_teardown }, + { "store/serde_lambda_malformed_closure", test_serde_lambda_malformed_closure, store_setup, store_teardown }, { "store/serde_save_serde_error", test_serde_save_serde_error, store_setup, store_teardown }, { "store/serde_de_raw_default", test_serde_de_raw_default_and_errors, store_setup, store_teardown }, { "store/serde_table_dict_de_errors", test_serde_table_dict_de_errors, store_setup, store_teardown }, diff --git a/test/test_text_null.c b/test/test_text_null.c index 9285bebda..2d2bf42e8 100644 --- a/test/test_text_null.c +++ b/test/test_text_null.c @@ -70,6 +70,53 @@ static test_result_t text_null_operations(int8_t type) { static test_result_t test_sym_payload_nulls(void) { return text_null_operations(RAY_SYM); } static test_result_t test_str_payload_nulls(void) { return text_null_operations(RAY_STR); } +/* #739: negating SYM membership must keep null rows false at every width, + * with or without HAS_NULLS, in both serial and pool-dispatched kernels. */ +static test_result_t test_sym_membership_nulls(void) { + const uint8_t widths[] = { RAY_SYM_W8, RAY_SYM_W16, RAY_SYM_W32, RAY_SYM_W64 }; + const int64_t lengths[] = { 6, 70002 }; + /* Use existing runtime-domain IDs so they fit even the 8-bit column. */ + const int64_t ids[] = { 1, 0, 2, 1, 0, 3 }; + const uint8_t expected[2][6] = { + { 1, 0, 0, 1, 0, 0 }, + { 0, 0, 1, 0, 0, 1 }, + }; + TEST_ASSERT(ray_sym_count() > 3, "runtime symbols exist"); + ray_t* set = ray_sym_vec_new(RAY_SYM_W64, 2); + TEST_ASSERT(set && !RAY_IS_ERR(set), "membership set"); + set->len = 2; + ray_write_sym(ray_data(set), 0, 1, RAY_SYM, set->attrs); + ray_write_sym(ray_data(set), 1, 0, RAY_SYM, set->attrs); + for (size_t w = 0; w < sizeof(widths); w++) { + for (size_t l = 0; l < sizeof(lengths) / sizeof(lengths[0]); l++) { + ray_t* col = ray_sym_vec_new(widths[w], lengths[l]); + TEST_ASSERT(col && !RAY_IS_ERR(col), "membership column"); + col->len = lengths[l]; + for (int64_t i = 0; i < col->len; i++) + ray_write_sym(ray_data(col), i, ids[i % 6], RAY_SYM, col->attrs); + for (int flagged = 0; flagged < 2; flagged++) { + if (flagged) col->attrs |= RAY_ATTR_HAS_NULLS; + else col->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + for (int negate = 0; negate < 2; negate++) { + ray_t* r = ray_in_vec_exec(col, set, negate != 0); + TEST_ASSERT(r && !RAY_IS_ERR(r), "membership result"); + TEST_ASSERT_EQ_I(r->type, RAY_BOOL); + TEST_ASSERT_EQ_I(r->len, col->len); + const uint8_t* out = (const uint8_t*)ray_data(r); + for (int64_t i = 0; i < r->len; i++) + TEST_ASSERT_FMT(out[i] == expected[negate][i % 6], + "membership width=%u len=%lld flagged=%d negate=%d row=%lld", + widths[w], (long long)col->len, flagged, negate, (long long)i); + ray_release(r); + } + } + ray_release(col); + } + } + ray_release(set); + PASS(); +} + static test_result_t test_dense_sym_zero(void) { /* All widths, both metadata states: zero must remain a real group key. */ const uint8_t widths[] = { RAY_SYM_W8, RAY_SYM_W16, RAY_SYM_W32, RAY_SYM_W64 }; @@ -213,6 +260,7 @@ static test_result_t test_sym_expr_admission(void) { } const test_entry_t text_null_entries[] = { + { "text_null/sym_membership_nulls", test_sym_membership_nulls, text_null_setup, text_null_teardown }, { "text_null/sym_hash_routes", test_sym_hash_routes, text_null_setup, text_null_teardown }, { "text_null/sym_expr_admission", test_sym_expr_admission, text_null_setup, text_null_teardown }, { "text_null/sym_without_flag", test_sym_payload_nulls, text_null_setup, text_null_teardown },