diff --git a/docs/assets/extra.css b/docs/assets/extra.css index 73c59ada1..3caf64653 100644 --- a/docs/assets/extra.css +++ b/docs/assets/extra.css @@ -173,35 +173,38 @@ --md-typeset-a-color: #c4821a; } +/* Material also applies .md-typeset to search-result articles. Keep the + site's display typography out of those compact result snippets. */ + /* ── Headings: Oswald, marketing-style ────────────────────────── */ -.md-typeset h1, -.md-typeset h2, -.md-typeset h3, -.md-typeset h4, -.md-typeset h5, -.md-typeset h6, +.md-typeset:not(.md-search-result__article) h1, +.md-typeset:not(.md-search-result__article) h2, +.md-typeset:not(.md-search-result__article) h3, +.md-typeset:not(.md-search-result__article) h4, +.md-typeset:not(.md-search-result__article) h5, +.md-typeset:not(.md-search-result__article) h6, .md-header__title { font-family: 'Oswald', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-weight: 700; letter-spacing: 0.01em; } -.md-typeset h1 { +.md-typeset:not(.md-search-result__article) h1 { font-weight: 700; font-size: 2.4rem; line-height: 1.1; color: #f1f5f9; } -.md-typeset h2 { +.md-typeset:not(.md-search-result__article) h2 { font-size: 1.7rem; border-bottom: 1px solid rgba(233, 160, 51, 0.15); padding-bottom: 0.3rem; margin-top: 2.5rem; } -.md-typeset h3 { +.md-typeset:not(.md-search-result__article) h3 { font-size: 1.3rem; color: #f0b954; } @@ -269,7 +272,7 @@ /* ── Inline code & code blocks ───────────────────────────────── */ -.md-typeset code { +.md-typeset:not(.md-search-result__article) code { background: rgba(233, 160, 51, 0.1); color: #f5d080; padding: 0.12em 0.35em; @@ -277,7 +280,7 @@ font-size: 0.88em; } -.md-typeset pre > code { +.md-typeset:not(.md-search-result__article) pre > code { background: #0d1219; color: #f1f5f9; border: 1px solid rgba(233, 160, 51, 0.08); @@ -285,12 +288,12 @@ /* ── Tables ──────────────────────────────────────────────────── */ -.md-typeset table:not([class]) { +.md-typeset:not(.md-search-result__article) table:not([class]) { border: 1px solid rgba(233, 160, 51, 0.1); background: rgba(17, 24, 32, 0.4); } -.md-typeset table:not([class]) th { +.md-typeset:not(.md-search-result__article) table:not([class]) th { background: rgba(233, 160, 51, 0.08); color: #f0b954; font-family: 'Oswald', sans-serif; @@ -302,15 +305,15 @@ /* ── Admonitions: match info-box look ────────────────────────── */ -.md-typeset .admonition, -.md-typeset details { +.md-typeset:not(.md-search-result__article) .admonition, +.md-typeset:not(.md-search-result__article) details { border-left: 3px solid #e9a033; background: rgba(17, 24, 32, 0.5); font-size: 0.85rem; } -.md-typeset .admonition-title, -.md-typeset summary { +.md-typeset:not(.md-search-result__article) .admonition-title, +.md-typeset:not(.md-search-result__article) summary { background: rgba(233, 160, 51, 0.08); font-family: 'Oswald', sans-serif; font-weight: 600; @@ -325,7 +328,7 @@ .md-button → outlined "ghost" pill .md-button--primary → filled gradient pill with glow lift. */ -.md-typeset .md-button { +.md-typeset:not(.md-search-result__article) .md-button { display: inline-flex; align-items: center; gap: 8px; padding: 13px 30px; border-radius: 100px; font-weight: 600; font-size: .9rem; @@ -336,20 +339,20 @@ transition: color .2s, border-color .2s, background .2s, box-shadow .2s, transform .2s; } -.md-typeset .md-button:hover { +.md-typeset:not(.md-search-result__article) .md-button:hover { color: var(--text, #f1f5f9); border-color: var(--border-hover, rgba(233, 160, 51, 0.4)); background: rgba(233, 160, 51, 0.05); } -.md-typeset .md-button--primary { +.md-typeset:not(.md-search-result__article) .md-button--primary { color: var(--text, #f1f5f9); border: 0; background: linear-gradient(135deg, var(--primary, #e9a033), var(--primary-light, #f0b954)); box-shadow: 0 4px 20px rgba(233, 160, 51, 0.35); } -.md-typeset .md-button--primary:hover { +.md-typeset:not(.md-search-result__article) .md-button--primary:hover { color: var(--text, #f1f5f9); background: linear-gradient(135deg, var(--primary, #e9a033), var(--primary-light, #f0b954)); box-shadow: 0 8px 32px rgba(233, 160, 51, 0.5); @@ -369,12 +372,12 @@ /* ── Links inside body ──────────────────────────────────────── */ -.md-typeset a { +.md-typeset:not(.md-search-result__article) a { color: #f0b954; transition: color .15s; } -.md-typeset a:hover { +.md-typeset:not(.md-search-result__article) a:hover { color: #5eead4; } @@ -586,49 +589,49 @@ html.landing-page body .footer.landing-footer { display: block; } border-left: 2px solid #e9a033; } -.md-typeset h1 { +.md-typeset:not(.md-search-result__article) h1 { margin-bottom: 2.2rem; color: #f8fafc; font-size: clamp(2.8rem, 5vw, 4.6rem); line-height: .96; letter-spacing: -.025em; } -.md-typeset h2 { +.md-typeset:not(.md-search-result__article) h2 { margin-top: 3.4rem; padding-bottom: .55rem; border-bottom-color: rgba(233,160,51,.22); font-size: 2rem; } -.md-typeset h3 { color: #f3c46b; } -.md-typeset p, -.md-typeset li { line-height: 1.7; } +.md-typeset:not(.md-search-result__article) h3 { color: #f3c46b; } +.md-typeset:not(.md-search-result__article) p, +.md-typeset:not(.md-search-result__article) li { line-height: 1.7; } -.md-typeset .md-button { +.md-typeset:not(.md-search-result__article) .md-button { min-height: 48px; padding: 12px 22px; border-radius: 0; font-family: 'JetBrains Mono', monospace; font-size: .72rem; } -.md-typeset .md-button--primary { +.md-typeset:not(.md-search-result__article) .md-button--primary { color: #171109; border: 1px solid #e9a033; background: #e9a033; box-shadow: 0 12px 36px rgba(233,160,51,.16); } -.md-typeset .md-button--primary:hover { +.md-typeset:not(.md-search-result__article) .md-button--primary:hover { color: #171109; background: #f3c46b; box-shadow: 0 16px 44px rgba(233,160,51,.22); } -.md-typeset code { border-radius: 0; } -.md-typeset pre > code, -.md-typeset .highlight, -.md-typeset table:not([class]), -.md-typeset .admonition, -.md-typeset details { border-radius: 0; } -.md-typeset pre > code { border-color: rgba(255,255,255,.1); } -.md-typeset table:not([class]) { border-color: rgba(255,255,255,.1); } +.md-typeset:not(.md-search-result__article) code { border-radius: 0; } +.md-typeset:not(.md-search-result__article) pre > code, +.md-typeset:not(.md-search-result__article) .highlight, +.md-typeset:not(.md-search-result__article) table:not([class]), +.md-typeset:not(.md-search-result__article) .admonition, +.md-typeset:not(.md-search-result__article) details { border-radius: 0; } +.md-typeset:not(.md-search-result__article) pre > code { border-color: rgba(255,255,255,.1); } +.md-typeset:not(.md-search-result__article) table:not([class]) { border-color: rgba(255,255,255,.1); } .md-footer { border-top-color: rgba(255,255,255,.1); } [data-md-color-scheme="slate"] .md-search__output { border-radius: 0; } @@ -706,15 +709,15 @@ html.landing-page body .footer.landing-footer { display: block; } .docs-nav-github svg { width: 17px; height: 17px; fill: currentColor; } /* Docs typography follows the same editorial hierarchy as the home sections. */ -.md-typeset h1, -.md-typeset h2, -.md-typeset h3, -.md-typeset h4 { +.md-typeset:not(.md-search-result__article) h1, +.md-typeset:not(.md-search-result__article) h2, +.md-typeset:not(.md-search-result__article) h3, +.md-typeset:not(.md-search-result__article) h4 { font-family: 'Oswald', 'Oswald Fallback', sans-serif; text-transform: uppercase; } -.md-typeset h1 { letter-spacing: -.035em; } -.md-typeset h2 { letter-spacing: -.02em; } +.md-typeset:not(.md-search-result__article) h1 { letter-spacing: -.035em; } +.md-typeset:not(.md-search-result__article) h2 { letter-spacing: -.02em; } .md-nav__title { font-family: 'JetBrains Mono', monospace; font-size: .62rem; @@ -778,14 +781,14 @@ html:not(.landing-page) .md-content__inner { padding-bottom: 5rem; } html:not(.landing-page) .md-content__inner::before { display: none; } -html:not(.landing-page) .md-typeset h1 { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1 { margin: 0 0 36px; color: #f8fafc; font-size: clamp(3.6rem, 5vw, 5.8rem); line-height: .9; letter-spacing: -.045em; } -html:not(.landing-page) .md-typeset h1::before { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1::before { content: 'RAYFORCE / DOCUMENTATION'; display: block; margin-bottom: 26px; @@ -795,26 +798,26 @@ html:not(.landing-page) .md-typeset h1::before { font: 600 10px/1.2 'JetBrains Mono', monospace; letter-spacing: .13em; } -html:not(.landing-page) .md-typeset h1 + p { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1 + p { color: #c1cad3; font-size: 1.02rem; line-height: 1.75; } -html:not(.landing-page) .md-typeset h2 { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h2 { margin-top: 4.2rem; padding-bottom: .7rem; border-bottom: 1px solid rgba(233,160,51,.24); font-size: clamp(2.25rem, 3.2vw, 3.5rem); line-height: 1; } -html:not(.landing-page) .md-typeset h3 { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h3 { margin-top: 2.5rem; font-size: 1.6rem; letter-spacing: -.01em; } -html:not(.landing-page) .md-typeset p, -html:not(.landing-page) .md-typeset li { color: #aab5bf; } -html:not(.landing-page) .md-typeset strong { color: #edf2f6; } +html:not(.landing-page) .md-typeset:not(.md-search-result__article) p, +html:not(.landing-page) .md-typeset:not(.md-search-result__article) li { color: #aab5bf; } +html:not(.landing-page) .md-typeset:not(.md-search-result__article) strong { color: #edf2f6; } html:not(.landing-page) .md-sidebar { color: #8f9daa; } @@ -843,10 +846,10 @@ html:not(.landing-page) .md-nav__link--active { border-left: 2px solid #e9a033; color: #f3c46b; } -html:not(.landing-page) .md-typeset pre > code, -html:not(.landing-page) .md-typeset table:not([class]), -html:not(.landing-page) .md-typeset .admonition, -html:not(.landing-page) .md-typeset details { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) pre > code, +html:not(.landing-page) .md-typeset:not(.md-search-result__article) table:not([class]), +html:not(.landing-page) .md-typeset:not(.md-search-result__article) .admonition, +html:not(.landing-page) .md-typeset:not(.md-search-result__article) details { border-color: rgba(255,255,255,.12); background-color: rgba(11,16,23,.88); } @@ -864,11 +867,11 @@ html:not(.landing-page) .md-footer { padding-inline: clamp(18px, 5vw, 48px); border-inline: 0; } - html:not(.landing-page) .md-typeset h1 { font-size: clamp(3rem, 12vw, 4.6rem); } + html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1 { font-size: clamp(3rem, 12vw, 4.6rem); } } @media screen and (max-width: 30em) { - html:not(.landing-page) .md-typeset .md-button { + html:not(.landing-page) .md-typeset:not(.md-search-result__article) .md-button { display: table; width: fit-content; max-width: 100%; @@ -1021,7 +1024,20 @@ html:not(.landing-page) .docs-site-nav .md-search__inner { width: 0; overflow: hidden; } +/* Results are absolutely positioned below the form on desktop. Keep the + closed search collapsed, but allow its results panel to extend when open. */ +html:not(.landing-page) [data-md-toggle="search"]:checked ~ .docs-site-nav .md-search__inner { + overflow: visible; +} html:not(.landing-page) .docs-site-nav .md-search__form { width: 100%; } +@media screen and (max-width: 59.984375em) { + /* A filtered ancestor makes the fixed mobile search panel relative to + the 70px header instead of the viewport, clipping nearly all results. */ + html:not(.landing-page) [data-md-toggle="search"]:checked ~ .docs-site-nav { + backdrop-filter: none; + -webkit-backdrop-filter: none; + } +} /* Full-bleed technical canvas: navigation + article, with the third Material column removed. Empty space is intentional and carries the engine artwork. */ @@ -1114,28 +1130,28 @@ html:not(.landing-page) .md-nav__link--active { /* Same editorial scale as the main site's copy—not Material's wide-screen root scaling and not a second marketing hero inside the docs. */ -html:not(.landing-page) .md-typeset { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) { color: #a9b4bf; font-size: 1rem; line-height: 1.72; } -html:not(.landing-page) .md-typeset h1, -html:not(.landing-page) .md-typeset h2, -html:not(.landing-page) .md-typeset h3, -html:not(.landing-page) .md-typeset h4 { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1, +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h2, +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h3, +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h4 { color: #f8fafc; font-family: Oswald, 'Oswald Fallback', sans-serif; font-weight: 700; text-transform: uppercase; } -html:not(.landing-page) .md-typeset h1 { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1 { max-width: 800px; margin: 0 0 30px; font-size: clamp(3.25rem, 4.2vw, 4.5rem); line-height: .94; letter-spacing: -.04em; } -html:not(.landing-page) .md-typeset h1::before { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1::before { content: 'RAYFORCE / DOCUMENTATION'; display: block; margin-bottom: 24px; @@ -1145,13 +1161,13 @@ html:not(.landing-page) .md-typeset h1::before { font: 600 .62rem/1.2 'JetBrains Mono', monospace; letter-spacing: .13em; } -html:not(.landing-page) .md-typeset h1 + p { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1 + p { max-width: 760px; color: #c1cad3; font-size: 1.12rem; line-height: 1.7; } -html:not(.landing-page) .md-typeset h2 { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h2 { margin-top: 4rem; padding-bottom: .65rem; border-bottom: 1px solid rgba(233,160,51,.24); @@ -1159,20 +1175,20 @@ html:not(.landing-page) .md-typeset h2 { line-height: 1; letter-spacing: -.025em; } -html:not(.landing-page) .md-typeset h3 { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) h3 { margin-top: 2.6rem; color: #f3c46b; font-size: 1.55rem; line-height: 1.2; } -html:not(.landing-page) .md-typeset p, -html:not(.landing-page) .md-typeset li { color: #a9b4bf; } -html:not(.landing-page) .md-typeset strong { color: #edf2f6; } -html:not(.landing-page) .md-typeset hr { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) p, +html:not(.landing-page) .md-typeset:not(.md-search-result__article) li { color: #a9b4bf; } +html:not(.landing-page) .md-typeset:not(.md-search-result__article) strong { color: #edf2f6; } +html:not(.landing-page) .md-typeset:not(.md-search-result__article) hr { margin: 30px 0; border-color: rgba(255,255,255,.12); } -html:not(.landing-page) .md-typeset .md-button { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) .md-button { min-height: 50px; margin-right: 8px; padding: 13px 22px; @@ -1180,16 +1196,16 @@ html:not(.landing-page) .md-typeset .md-button { font: 600 .76rem/1 'JetBrains Mono', monospace; letter-spacing: .03em; } -html:not(.landing-page) .md-typeset .md-button--primary { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) .md-button--primary { color: #15100a; border: 1px solid #e9a033; background: #e9a033; box-shadow: 0 10px 40px rgba(233,160,51,.16); } -html:not(.landing-page) .md-typeset pre > code, -html:not(.landing-page) .md-typeset table:not([class]), -html:not(.landing-page) .md-typeset .admonition, -html:not(.landing-page) .md-typeset details { +html:not(.landing-page) .md-typeset:not(.md-search-result__article) pre > code, +html:not(.landing-page) .md-typeset:not(.md-search-result__article) table:not([class]), +html:not(.landing-page) .md-typeset:not(.md-search-result__article) .admonition, +html:not(.landing-page) .md-typeset:not(.md-search-result__article) details { border-radius: 0; border-color: rgba(255,255,255,.12); background-color: rgba(11,16,23,.88); @@ -1321,17 +1337,17 @@ html:not(.landing-page) .md-footer { width: calc(100% - 32px); padding: 44px 0 80px; } - html:not(.landing-page) .md-typeset h1 { + html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1 { font-size: clamp(2.8rem, 14vw, 4rem); } - html:not(.landing-page) .md-typeset h1::before { + html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1::before { margin-bottom: 20px; padding-left: 34px; background-size: 22px 1px; font-size: .56rem; } - html:not(.landing-page) .md-typeset h1 + p { font-size: 1rem; } - html:not(.landing-page) .md-typeset .md-button { + html:not(.landing-page) .md-typeset:not(.md-search-result__article) h1 + p { font-size: 1rem; } + html:not(.landing-page) .md-typeset:not(.md-search-result__article) .md-button { display: table; width: fit-content; max-width: 100%; diff --git a/docs/docs/c-api/core.md b/docs/docs/c-api/core.md index 846b1faf5..603f9c4ba 100644 --- a/docs/docs/c-api/core.md +++ b/docs/docs/c-api/core.md @@ -91,6 +91,32 @@ Decrements the reference count. When `rc` reaches zero, the object and any owned void ray_release(ray_t* v); ``` +### ray_shallow_bytes / ray_retained_bytes + +How many bytes of native memory a value stands for, so an embedding runtime (an OCaml or Python binding that wraps a `ray_t*` in a finalized object) can charge its garbage collector for the wrapper. Neither call allocates on the Rayforce heap. + +```c +size_t ray_shallow_bytes(const ray_t* v); +size_t ray_retained_bytes(const ray_t* v); +``` + +`ray_shallow_bytes` is what this value's own release gives back: the block the allocator committed for it (header plus capacity; a buddy block is a power of two, a large direct block its exact page-rounded mapping) plus the private storage that no public API hands out on its own and that only this value releases: + +- a long string atom's payload and a GUID atom's payload; +- a string vector's pool; +- an attached accelerator index with its tables; +- a file-mapped column's mapping (a splayed string column's region is charged to the column; the pool block inside it reports 0). + +Values that are reachable but are values in their own right are **not** included: list elements, table and dict slots, lambda parts, a slice's parent. A table and its separately wrapped columns are therefore never charged twice; a slice reports only its header block. Non-owning values report 0: the null and OOM singletons, arena-allocated values, borrowed blocks, an index that is a passenger in a column's mapping. A string pool shared by copy-on-write copies of one vector is charged to each copy. Symbol domains, lazy DAGs and opaque native handles (HNSW, graph) are outside the accounting. + +`ray_retained_bytes` is the shallow figure of the value plus that of everything reachable through ownership edges (list elements, table and dict slots, lambda parts, slice parents, parted segments), each distinct block counted once. Sharing inside the walked graph is not double counted, but two calls on two values that share children both report the shared part. Use it for diagnostics; drive GC pressure with the shallow figure. + +```c +ray_t* col = ray_vec_new(RAY_I64, 1000000); +/* ... */ +caml_alloc_custom_mem(&ops, sizeof(ray_t*), ray_shallow_bytes(col)); /* OCaml: charge the GC */ +``` + ### ray_cow Copy-on-write: if `v` is the sole owner (`rc == 1`), returns `v` unchanged. Otherwise, creates a deep copy and returns it with `rc = 1`. The original is not modified. After `ray_cow()`, if the returned pointer differs from the original, the caller must release it on error paths. diff --git a/docs/docs/guides/datalog-reference.md b/docs/docs/guides/datalog-reference.md index e6eca8b59..27f1aad35 100644 --- a/docs/docs/guides/datalog-reference.md +++ b/docs/docs/guides/datalog-reference.md @@ -226,12 +226,15 @@ Use `_` to match any value without binding it to a variable: ### How queries compile to the DAG -Under the hood, each query compiles to Rayforce's DAG execution pipeline: - -- Each triple pattern `(?e :attr ?v)` becomes a `ray_scan` + `ray_filter` on the datoms table -- Shared variables across patterns become `ray_join` operations -- The `find` clause becomes a final projection selecting the requested columns -- The optimizer applies predicate pushdown, filter reorder, and fusion — the same passes used for `select` +Under the hood each rule is evaluated by materialisation: every positive body +atom is filtered on its constants and repeated variables, joined with the +accumulated result on shared variables (hash join, morsel-parallel), then +negations, comparisons, assignments and aggregates are applied in declared +order, and the head projection is de-duplicated and merged into the derived +relation. Recursive rules run to fixpoint with semi-naive evaluation. Joins +execute on the same operators as `select`, but a whole rule is not planned as +one DAG: body atoms are joined in the order written, and comparisons are +applied after the joins that bind their variables. ## Negation @@ -459,7 +462,52 @@ Every Datalog concept compiles down to existing Rayforce DAG operations. The Dat !!! note "Performance" - Because Datalog compiles to the same DAG as `select`/`update`, queries benefit from all optimizer passes: predicate pushdown, filter reorder, fusion, and morsel-parallel execution with SIMD. + Joins and distinct inside a rule use the parallel `select` operators. Rule-level + join ordering, predicate pushdown across atoms and plan reuse between queries are + not performed; write the most selective atom first. + +## Constants in patterns + +In a `where` clause or rule body, a quoted symbol (`'Alice`) or keyword +(`:name`) is a literal; a bare unquoted symbol (`sid`) is evaluated as a +variable reference to a bound value (integer, float, symbol or string). Head +arguments still treat a bare symbol as a literal constant. + +## Arithmetic + +Integer expressions in `(= ?y (+ ?x 1))` and comparisons are 64-bit and checked: +overflow, division by zero, `INT64_MIN / -1` and any null operand produce the +null integer `0Nl`. Float expressions follow IEEE 754 (division by zero gives +`0Nf`). The error code surfaced for a failed query evaluation is `domain`. + +## Limits + +| Limit | Value | On overflow | +|---|---|---| +| Variables in `find` | 16 | error `find supports at most 16 variables` | +| Arity of a relation | 16 | error at rule or EDB registration | +| Body literals per rule | 16 | error `too many body literals` | +| Rules per program | 128 | error `too many rules` | +| Relations per program | 64 | error | +| Strata | 16 | error | +| Group keys in an aggregate | 8 | error | + +An unknown relation name in a body is an error (`unknown relation 'name'`), +not an empty result. + +## Symbol storage + +`assert-fact` stores symbol values in the `v` column with a type tag, so the +symbol `'Alice` and the integer equal to its intern id are different values. +Query results, `pull` and `scan-eav` return the plain intern id; use `sym-name` +to read it back. Inspecting the raw datoms table shows the tagged encoding. + +A datoms table whose `v` column is a real symbol vector (hand-built or +loaded) is also recognised as holding symbols. A legacy table whose `v` +column holds bare integer intern ids is not — those integers stay integers +and are not matched against a symbol or keyword literal. Positive integer +values of 2^61 and above cannot be stored in the `v` column or returned +from a query without being masked; this is a limit of the tag encoding. ## Complete Example diff --git a/docs/docs/language/functions.md b/docs/docs/language/functions.md index 9ed26fca3..02f76647c 100644 --- a/docs/docs/language/functions.md +++ b/docs/docs/language/functions.md @@ -442,7 +442,7 @@ Cross-temporal comparisons are supported: dates, times, and timestamps are all c | `read-bytes` | unary | Read file contents as a `U8` byte vector | `(read-bytes "file.bin")` | | `write` | binary | Write a string to a file | `(write "file.txt" "content")` | | `write-bytes` | binary | Write a `U8` byte vector to a file | `(write-bytes "file.bin" bytes)` | -| `load` | unary | Load and evaluate a Rayfall script | `(load "lib.rfl")` | +| `load` | unary | Load and evaluate a Rayfall script; a relative path is tried against the working directory, then below `RAYFORCE_HOME` | `(load "lib.rfl")` | ## Control Flow diff --git a/docs/docs/namespaces/sys.md b/docs/docs/namespaces/sys.md index 2e50c6ef5..3e687f307 100644 --- a/docs/docs/namespaces/sys.md +++ b/docs/docs/namespaces/sys.md @@ -36,10 +36,17 @@ Signature: `(.sys.args)`. Returns the process's command-line arguments as a dict | `querylog` | bool | `-Q` | Query-statistics logging enabled at startup. | | `interactive` | bool | `-i` | Force the REPL after a script. | | `log` | str | `-l` / `-L` | Journal base path; empty if none. | +| `source` | str | — | The file currently being evaluated: the innermost `load`, or the command-line script, by the path that was actually opened. Empty at the REPL, under a pipe, or in a hook or timer that runs outside any file. `file` is the script named on the command line (`$0`); `source` follows nested loads (`$BASH_SOURCE`). | | `user` | dict | after `--` | The application's own arguments. | The top-level schema is **stable** — every launcher key is always present with its effective value (the default when the flag wasn't passed), so `(get (.sys.args) 'port)` never misses. Auth passwords (`-u` / `-U`) are deliberately **not** exposed. +```lisp +;; load a sibling of the running file, whichever directory it was started from +(set here (str-join (drop -1 (split (at (.sys.args) 'source) "/")) "/")) +(load (concat here "/lib.rfl")) +``` + **`user` parsing.** Tokens after `--` are paired `-key value` / `--key value`: a token starting with `-` is a key (leading dashes stripped to a symbol), and the next token is its value — unless that token also starts with `-`, in which case the value is the empty string (a bare flag). Duplicate keys keep the last value. ```lisp diff --git a/docs/docs/queries/attributes.md b/docs/docs/queries/attributes.md index fa6f0290b..46635bd84 100644 --- a/docs/docs/queries/attributes.md +++ b/docs/docs/queries/attributes.md @@ -3,13 +3,13 @@ Semantic properties stamped onto columns — `sorted`, `unique`, `grouped`, `parted`. Where an [accelerator index](indexes.md) is a *physical* structure (a hash table, a permutation), a column attribute is an *assertion about meaning*: this column is non-descending, these values are distinct. The `.attr.*` family layers over the same storage as `.idx.*`, but its contract is semantic, not structural. !!! note "v1 status" - The four attributes, their strict verify-on-set kernels, and the `(.attr.*)` Rayfall surface are shipped. `sorted` and `unique` are numeric; the backing-index attributes `grouped` and `parted` also support symbol columns. + The four attributes, their strict verify-on-set kernels, and the `(.attr.*)` Rayfall surface are shipped. `sorted` and `parted` are numeric (`parted` also takes symbols); `unique` and `grouped` take numeric, symbol and string columns. ## Why Attributes Are Separate from Indexes An [accelerator index](indexes.md) answers *"what structure is attached?"* — a zonemap, a hash table, a sort permutation. A column attribute answers a different question: *"what is semantically true of these values?"* The two markers (`sorted`, `unique`) carry no allocation at all — they are cheap flags. The two backing-index attributes (`grouped`, `parted`) do reuse the index layer underneath (so a `grouped` or `parted` column also shows up via `.idx.has?` and `.idx.info`), but `.attr.*` exists to assert a *property* the engine can trust, not merely to build a structure. -The payoff is that consumers can trust a stamped attribute unconditionally. Besides the [as-of join executor](joins.md#pre-sorted-fast-path), filters and grouped aggregation use the physical layout directly. +The payoff is that consumers can trust a stamped attribute unconditionally. Besides the [as-of join executor](joins.md#pre-sorted-fast-path), filters and grouped aggregation use the physical layout directly, and a keyed lookup against a `grouped` vector — `find` or `in` with a vector of needles, `at` on a dict keyed by it — probes the hash once per needle instead of building one over the whole vector per call. ## The Four Attributes @@ -108,7 +108,9 @@ But a column holds at most one backing index — setting `grouped` or `parted` r ## Conservative Propagation -Attributes propagate **conservatively**. Only operations that trivially preserve the values — a refcount / copy-on-write copy, a plain rebind — keep the attributes. *Any* transform that could change ordering, length, or values (arithmetic, `filter` / `where`, `reverse`, `concat`, reordering `take`) **drops** them. This keeps the invariant honest: a held attribute always reflects the current bytes. +Attributes propagate **conservatively**. Only operations that trivially preserve the values — a refcount / copy-on-write copy, a plain rebind — keep the attributes. *Any* transform that could change ordering, length, or values (arithmetic, `filter` / `where`, `reverse`, reordering `take`) **drops** them. This keeps the invariant honest: a held attribute always reflects the current bytes. + +One append shape is the exception. `(concat v rows)` and `(concat v atom)` on a `grouped` vector keep the hash (and a `unique` marker) when **every appended key is new** — the existing groups are copied and each appended row becomes a group of its own, so an append-only keyed vector never pays a rebuild. An appended row that repeats a key, a null, or a symbol from another domain leaves the result a plain vector, exactly as before; `sorted` is always dropped by `concat`. ```lisp ; Arithmetic drops the marker (and a backing index). @@ -119,6 +121,10 @@ Attributes propagate **conservatively**. Only operations that trivially preserv (.attr.get (reverse (.attr.set 'sorted [1 2 3]))) ; ⇒ no attributes (.attr.get (concat (.attr.set 'sorted [1 2 3]) [0 1])) ; ⇒ no attributes +; An append of NEW keys carries a hash index (and `unique`); a repeat drops it. +(.attr.get (concat (.attr.set 'unique (.attr.set 'grouped [1 2 3])) [4 5])) ; ⇒ ['unique 'grouped] +(.attr.get (concat (.attr.set 'grouped [1 2 3]) [3])) ; ⇒ no attributes + ; Plain rebind preserves. (set _s (.attr.set 'sorted [1 2 3])) (.attr.get _s) ; ⇒ ['sorted] @@ -162,9 +168,9 @@ For a partitioned join `(asof-join [Key Time] L R)`, if the single numeric equal ## Caveats and Limits -- **Type support.** `sorted` and `unique` accept numeric types. `grouped` and `parted` also accept `SYM`; `STR` remains unsupported. +- **Type support.** `sorted` accepts numeric types; `parted` numeric and `SYM`. `unique` and `grouped` accept numeric, `SYM` and `STR` — a `STR` hash is keyed on a 64-bit hash of the bytes with the payload compared on every hit, so a content-keyed column (a digest) carries an index like any other. A `STR` `grouped` column persists its hash through a splayed save in place of the automatic string dictionary (one index per column). - **Strict verify, no silent stamping.** `.attr.set` errors on violation rather than recording a property it cannot confirm; this is what lets consumers trust the stamp unconditionally. -- **Conservative propagation.** Only copy / rebind preserve attributes; every transform drops them. Re-assert with `.attr.set` after a transform. +- **Conservative propagation.** Only copy / rebind preserve attributes; every transform drops them, except an append of new keys onto a `grouped` vector (see above). Re-assert with `.attr.set` after any other transform. - **One backing index per column.** `grouped` and `parted` share the [accelerator-index](indexes.md) slot, so a column carries at most one of them at a time; the markers are separate and free. ## Quick Reference diff --git a/docs/docs/queries/indexes.md b/docs/docs/queries/indexes.md index 8a0f97bb1..508bbd300 100644 --- a/docs/docs/queries/indexes.md +++ b/docs/docs/queries/indexes.md @@ -23,7 +23,8 @@ The executor consults indexes at five sites. Each site has a specific consumpti | `.idx.hash` / `part` backing | `where key IN …` + `group by key` | Resolve only the requested key slices and aggregate them directly, skipping filter scan and group discovery. Part slices stream as contiguous ranges. | | `.idx.sort` | ORDER BY — single ascending key | The pre-built permutation is reused directly rather than re-sorting. Descending ORDER BY falls back to recompute (reversing the perm would swap tie-group positions relative to stable DESC sort). | | `.idx.sort` | `distinct` | Walk the sort permutation once to collect first-occurrence row ids per distinct value — O(n) with no hash table. SYM/GUID/STR columns fall back. | -| `.idx.hash` | `find` | Hash-chain probe returns the minimum row id matching the needle, or a provably-absent signal. Integer-family needles only; float and cross-family needles fall through to the scan. | +| `.idx.hash` | `find` | Hash-chain probe returns the minimum row id matching the needle, or a provably-absent signal. Integer-family, `SYM` and `STR` needles against a column of the same family; float and cross-family needles fall through to the scan. A **vector** of needles probes once per needle — nothing is built per call. | +| `.idx.hash` | `in` — `(in needles v)` with `v` indexed, and `(at d keys)` on a dict keyed by an indexed vector | One probe per needle, same type matrix as `find`. Without an index, `find` / `in` hash whichever side is smaller and scan the other once. | ### Eligibility conditions (uniform) @@ -34,7 +35,7 @@ All five sites apply the same prechecks before consulting an index: - **Not parted / not MAPCOMMON:** parted and MAPCOMMON columns skip routing at the filter and IN sites. - **Default table:** filter and IN sites only route columns from the query's default table (non-default table references are skipped). -Mutation auto-drops the attached index — the in-place mutators (`(insert 'v val)`, `(alter 'v set i val)`, `(alter 'v concat vals)`) call `ray_index_drop()` before writing, so a mutated column always has `HAS_INDEX` clear afterward. Reattach explicitly after the write. +Mutation auto-drops the attached index — the in-place mutators (`(insert 'v val)`, `(alter 'v set i val)`) call `ray_index_drop()` before writing, so a mutated column always has `HAS_INDEX` clear afterward. Reattach explicitly after the write. The one append that keeps a hash index is `concat` (and `(alter 'v concat vals)`, which rebinds to a `concat` result) when every appended key is new — see [Common Workflows](#common-workflows). ### Fallback guarantee @@ -93,7 +94,7 @@ Each kind has a one-arg attach builtin. Attaching is idempotent — if a differ `(.idx.zone v) (.idx.hash v) (.idx.sort v) (.idx.bloom v)` -Attach an index of the named kind to a vector `v`. Returns the column with the new index attached (the underlying values are unchanged). All kinds accept the numeric/boolean types `RAY_BOOL`, `RAY_U8`, `RAY_I16`, `RAY_I32`, `RAY_I64`, `RAY_F32`, `RAY_F64`, `RAY_DATE`, `RAY_TIME`, `RAY_TIMESTAMP`; `.idx.hash` **additionally** accepts `RAY_SYM`. `RAY_STR` (and `RAY_SYM` on the non-hash kinds) is deferred to v2. +Attach an index of the named kind to a vector `v`. Returns the column with the new index attached (the underlying values are unchanged). All kinds accept the numeric/boolean types `RAY_BOOL`, `RAY_U8`, `RAY_I16`, `RAY_I32`, `RAY_I64`, `RAY_F32`, `RAY_F64`, `RAY_DATE`, `RAY_TIME`, `RAY_TIMESTAMP`; `.idx.hash` **additionally** accepts `RAY_SYM` (keyed on domain ids) and `RAY_STR` (keyed on a 64-bit hash of the bytes, payload compared on every hit). `RAY_SYM` / `RAY_STR` on the non-hash kinds is deferred to v2. ### Examples @@ -133,7 +134,7 @@ Indexed columns participate in normal operations transparently. `(sum vh)`, `(a ### Mutation Drops the Index -The Rayfall in-place mutators — `(insert 'v val)` for append and `(alter 'v set i val)` / `(alter 'v concat val)` for set / append — invalidate the attached index. The mutator paths drop the index transparently, restore the original nullmap bytes, and proceed with the write. Subsequent `(.idx.has?)` calls return false; reattach the index after the write if you want index routing on the updated column. +The Rayfall in-place mutators — `(insert 'v val)` for append and `(alter 'v set i val)` for set — invalidate the attached index. The mutator paths drop the index transparently, restore the original nullmap bytes, and proceed with the write. Subsequent `(.idx.has?)` calls return false; reattach the index after the write if you want index routing on the updated column. `(alter 'v concat val)` rebinds `v` to `(concat v val)`, so a hash index survives it when every appended key is new (see below). ```lisp (set v [5 1 9 3 7]) @@ -157,9 +158,13 @@ An accelerator index uses bytes 0–7 of the column's [nullmap union](https://gi (in 700 v) ; ⇒ true (700 = 7 × 100) — hash-chain probe (in 701 v) ; ⇒ false (find v 700) ; ⇒ 100 — hash fast path returns minimum row id +(find v [700 701 6993]) ; ⇒ [100 0N 999] — one probe per needle +(in [700 701] v) ; ⇒ [true false] (set v (.idx.drop v)) ; optional early release; mutators auto-drop ``` +An append of new keys keeps the hash: `(concat v [7000 7007])` carries the index over (see [Attributes — Conservative Propagation](attributes.md#conservative-propagation)); an appended repeat drops it as before. + ### Range scans on a stable column ```lisp diff --git a/docs/docs/reference/all-functions.md b/docs/docs/reference/all-functions.md index 1994f63da..a58c4e721 100644 --- a/docs/docs/reference/all-functions.md +++ b/docs/docs/reference/all-functions.md @@ -616,7 +616,7 @@ Printing, file I/O, CSV loading, and script execution. | `read-bytes` | unary | restricted | Read file contents as a `U8` byte vector | `(read-bytes "file.bin")` | | `write` | binary | restricted | Write a string to a file | `(write "file.txt" "content")` | | `write-bytes` | binary | restricted | Write a `U8` byte vector to a file | `(write-bytes "file.bin" bytes)` | -| `load` | unary | restricted | Load and evaluate a Rayfall script file | `(load "lib.rfl")` | +| `load` | unary | restricted | Load and evaluate a Rayfall script file. A relative path is tried against the working directory, then below `RAYFORCE_HOME` when set; absolute paths are used as given; a failure names every path tried | `(load "lib.rfl")` | | `exit` | unary | restricted | Exit the process with status code | `(exit 0)` | | `resolve` | variadic | special | Resolve a symbol in the current scope | `(resolve 'x)` | | `timeit` | variadic | special | Benchmark an expression (prints elapsed time) | `(timeit (sum (til 1000000)))` | @@ -726,10 +726,10 @@ TCP-based IPC for connecting to remote Rayforce instances. Uses binary serializa | `.ipc.open` | variadic | restricted | Open TCP connection to host:port (optional connect timeout in ms), returns handle | `(.ipc.open "localhost:5000" 2000)` | | `.ipc.close` | unary | restricted | Close an IPC connection handle | `(.ipc.close h)` | | `.ipc.send` | binary | restricted | Send a value over an IPC handle (sync request) | `(.ipc.send h "(sum (til 100))")` | -| `.ipc.handle` | variadic | — | Current connection handle inside any `.ipc.on.*` hook, `-1` outside; given a live connection handle, that connection's transmit-queue view (`limit_bytes`, `limit_frames`, `queued_bytes`, `queued_frames`, `hwm_bytes`) | `(.ipc.handle)`, `(.ipc.handle h)` | +| `.ipc.handle` | variadic | — | Current connection handle inside any `.ipc.on.*` hook, `-1` outside; given a live connection handle, that connection's view (`inbound`, `limit_bytes`, `limit_frames`, `queued_bytes`, `queued_frames`, `hwm_bytes`) | `(.ipc.handle)`, `(.ipc.handle h)` | | `.ipc.txlimit` | variadic | restricted | Transmit backlog policy: `()` reads the process default, `(bytes [frames])` sets it, `(h bytes frames)` overrides one connection; a frame that would exceed a connection's limit is refused and a multicast subscriber is dropped and closed | `(.ipc.txlimit 8388608 64)` | | `.ipc.on.open` | hook | user-settable | Fires after inbound connection completes handshake; arg = handle | `(set .ipc.on.open (fn [h] ...))` | -| `.ipc.on.close` | hook | user-settable | Fires before inbound connection teardown; arg = handle | `(set .ipc.on.close (fn [h] ...))` | +| `.ipc.on.close` | hook | user-settable | Fires once before an established connection is torn down, inbound or outbound, on any cause; arg = handle | `(set .ipc.on.close (fn [h] ...))` | | `.ipc.on.sync` | hook | user-settable | Intercepts sync messages; return value becomes the response | `(set .ipc.on.sync (fn [m] (eval (parse m))))` | | `.ipc.on.async` | hook | user-settable | Intercepts async messages; return value ignored | `(set .ipc.on.async (fn [m] ...))` | | `.ipc.on.auth` | hook | user-settable | Narrows `-u`/`-U` auth; truthy = accept, falsy = reject | `(set .ipc.on.auth (fn [u p] (!= u "ban")))` | diff --git a/docs/docs/storage/ipc-hooks.md b/docs/docs/storage/ipc-hooks.md index e027a0389..52e6601d5 100644 --- a/docs/docs/storage/ipc-hooks.md +++ b/docs/docs/storage/ipc-hooks.md @@ -2,7 +2,7 @@ Five user-installable lambdas under `.ipc.on.*` that intercept the server-side connection lifecycle, plus the `.ipc.handle` accessor for the current connection's handle. -The handle a hook receives is a first-class connection handle — the same namespace `.ipc.open` allocates from. Pass it to `.ipc.post` (async push to the connected client), `.ipc.send` (sync round-trip), or `.ipc.close` (kick the client), from inside the hook or any time later. Lifecycle hooks fire for **inbound** connections only; connections the process itself opened via `.ipc.open` never trigger `on.open`/`on.close`. +The handle a hook receives is a first-class connection handle — the same namespace `.ipc.open` allocates from. Pass it to `.ipc.post` (async push to the connected client), `.ipc.send` (sync round-trip), or `.ipc.close` (kick the client), from inside the hook or any time later. `on.open`, `on.sync`, `on.async` and `on.auth` fire for **inbound** connections only. `on.close` fires for **both** directions: a connection the process opened with `.ipc.open` reports its close too, so a receive-only client (a multicast subscriber, say) learns that the peer went away without probing. `(at (.ipc.handle h) 'inbound)` tells the two apart inside the hook. !!! note "See also" The [IPC & Serialization](ipc.md) page documents the client-side `.ipc.open` / `.ipc.send` / `.ipc.close` and the wire format. Hooks live on the server and fire in response to inbound connections. @@ -14,7 +14,7 @@ The server side exposes the inbound connection lifecycle to Rayfall code through | Name | Signature | Fires | Return value | |---|---|---|---| | `.ipc.on.open` | `(fn [h] ...)` | Inbound connection fully handshaked (and authed when `-u`/`-U` is on), just before the first header read. | Ignored. | -| `.ipc.on.close` | `(fn [h] ...)` | Inbound connection about to close, before its socket is closed and per-conn state is freed. Pairs 1-to-1 with `.ipc.on.open` — never fires for connections that died mid-handshake. | Ignored. | +| `.ipc.on.close` | `(fn [h] ...)` | An established connection, inbound or outbound, about to close, before its socket is closed and per-conn state is freed. Fires exactly once per connection on any teardown: the peer's close or reset, a socket error, a local `.ipc.close`, or a multicast eviction seen from the subscriber's side. Never fires for a connection that died mid-handshake. Inbound closes pair 1-to-1 with `.ipc.on.open`; outbound ones have no open event. | Ignored. | | `.ipc.on.sync` | `(fn [m] ...)` | Inbound sync request, after the payload is deserialised into `m`. Replaces the default in-process `eval`. | Serialised and shipped to the client as the response. | | `.ipc.on.async` | `(fn [m] ...)` | Inbound async message. Same dispatch point as `on.sync`, but the wire produces no response. | Ignored (errors are logged to stderr). | | `.ipc.on.auth` | `(fn [u p] ...)` | After the constant-time secret compare in `-u`/`-U` auth passes. Servers started without auth never reach this hook. | Truthy = accept connection, falsy / error = reject and close. | @@ -86,3 +86,13 @@ Inside any hook, `(.ipc.handle)` returns the handle of the connection that trigg The argument `h` passed to `on.open` / `on.close` always equals `(.ipc.handle)` at the moment the hook fires — the builtin is the only way to reach the handle from `on.sync` / `on.async` / `on.auth`, whose signatures don't include it directly. A handle read here stays valid for the connection's lifetime: store it and `.ipc.post` to it later (publish/subscribe), or `.ipc.close` it to drop the client. After the connection closes, the integer may be reused by a future connection — don't cache handles across `on.close`. + +Inside `on.close` the handle still resolves — `(.ipc.handle h)` answers, with `inbound` saying which direction closed — but the peer is gone or going, so sending on it is pointless. The hook runs inside the poller's teardown of that connection; reconnect from a timer (`.time.timer.set`) rather than from inside the hook. + +```lisp +;; a subscriber that notices its publisher dropped it +(set .ipc.on.close (fn [h] + (if (not (at (.ipc.handle h) 'inbound)) + (.time.timer.set 1000 1 (fn [t] (reconnect-and-resubscribe))) + null))) +``` diff --git a/docs/docs/storage/ipc.md b/docs/docs/storage/ipc.md index 336814ed8..0dc8cfdee 100644 --- a/docs/docs/storage/ipc.md +++ b/docs/docs/storage/ipc.md @@ -184,14 +184,14 @@ Every connection queues outbound bytes the socket cannot take immediately (async (.ipc.txlimit 8388608) ; 8 MiB per connection, frames unlimited (.ipc.txlimit 8388608 64) ; at most 8 MiB or 64 queued frames, whichever first (.ipc.txlimit h 67108864 0) ; one connection may hold 64 MiB -(.ipc.handle h) ; {handle limit_bytes limit_frames queued_bytes queued_frames hwm_bytes} +(.ipc.handle h) ; {handle inbound limit_bytes limit_frames queued_bytes queued_frames hwm_bytes} ``` The default is 256 MiB with no frame cap; the minimum is 4 KiB, and `frames` of `0` means unlimited. Changing the default applies to every connection without an override, including ones already open. `.mc.stats` reports the default as `tx_limit_bytes` / `tx_limit_frames` and the largest backlog any connection has held as `tx_hwm_bytes`. `.ipc.txlimit` is restricted: it decides when a peer is dropped. ## Connection Hooks -The server side exposes the inbound connection lifecycle to Rayfall code through five user-installable lambdas under `.ipc.on.*` — `open`, `close`, `sync`, `async`, and `auth` — plus the `(.ipc.handle)` accessor that returns the current connection's handle inside any hook. See [IPC Connection Hooks](ipc-hooks.md) for the full reference: signatures, install / clear semantics, the reserved-namespace carve-out, per-hook error handling, and the restricted-mode interaction. +The server side exposes the inbound connection lifecycle to Rayfall code through five user-installable lambdas under `.ipc.on.*` — `open`, `close`, `sync`, `async`, and `auth` — plus the `(.ipc.handle)` accessor that returns the current connection's handle inside any hook. `close` also fires on the client side for a connection opened with `.ipc.open`, so a subscriber sees its publisher go away. See [IPC Connection Hooks](ipc-hooks.md) for the full reference: signatures, install / clear semantics, the reserved-namespace carve-out, per-hook error handling, and the restricted-mode interaction. ## Serialization with `ser` diff --git a/include/rayforce.h b/include/rayforce.h index c2371849b..2ab292714 100644 --- a/include/rayforce.h +++ b/include/rayforce.h @@ -462,6 +462,43 @@ void ray_progress_span_end(void); void ray_retain(ray_t* v); void ray_release(ray_t* v); +/* ===== Native footprint (foreign-runtime GC accounting) ===== + * + * How many bytes of native memory a value stands for, in two well-defined + * senses, so an embedding runtime can charge its garbage collector for a + * wrapper that keeps a Rayforce value alive. Both are O(size of the value + * graph walked) and never allocate on the Rayforce heap. + * + * ray_shallow_bytes — what this value's own release gives back: the block + * the allocator committed for it (header + capacity — a buddy block is a + * power of two, a large "direct" block its exact page-rounded mapping) PLUS + * the private storage no public API hands out on its own and that only + * this value releases: a long string atom's payload, a GUID atom's payload, + * a string vector's pool, an attached accelerator index with its tables. + * A file-mapped column reports the length of its mapping (a splayed string + * column's region is charged to the column; the pool block inside it + * reports 0). Slices report only their own header block. Children that + * are values in their own right — list elements, table and dict slots, + * lambda parts, a slice's parent — are NOT included, so a table and its + * separately wrapped columns are never charged twice. Non-owning values + * report 0: the null and OOM singletons, arena-allocated values, borrowed + * blocks, an index that is a passenger in a column's mapping. A string + * pool shared by copy-on-write copies of one vector is charged to each + * copy. Symbol domains, lazy DAGs and opaque native handles (HNSW, graph) + * are outside the accounting. + * + * ray_retained_bytes — the shallow bytes of this value and of every value + * reachable from it through ownership edges (list elements, table and dict + * slots, lambda parts, slice parents, parted segments), each distinct block + * counted once. Sharing between the walked values is therefore not double + * counted, but two calls on two values that share children both report the + * shared part. Meant for diagnostics; drive GC pressure with the shallow + * figure. + * + * Errors are ordinary blocks (a RAY_ERROR reports its block). NULL → 0. */ +size_t ray_shallow_bytes(const ray_t* v); +size_t ray_retained_bytes(const ray_t* v); + /* ===== Atom Constructors ===== */ ray_t* ray_bool(bool val); @@ -768,6 +805,7 @@ ray_t* ray_select(ray_t** args, int64_t n); ray_t* ray_update(ray_t** args, int64_t n); ray_t* ray_insert(ray_t** args, int64_t n); ray_t* ray_upsert(ray_t** args, int64_t n); +ray_t* ray_delete(ray_t** args, int64_t n); ray_t* ray_fmt(ray_t* obj, int mode); /* ===== IPC Client API ===== diff --git a/src/app/main.c b/src/app/main.c index f27d2b91c..f6ff95f3a 100644 --- a/src/app/main.c +++ b/src/app/main.c @@ -199,7 +199,10 @@ int main(int argc, char** argv) { " and stderr to a file/journal — anything (println ...)\n" " prints from the server side goes there. Example:\n" " nohup rayforce -p 5000 > rayforce.log 2>&1 &\n" - " systemd: StandardOutput=journal StandardError=journal\n", + " systemd: StandardOutput=journal StandardError=journal\n" + " With -p and a script, a script that fails to parse or\n" + " evaluate is fatal: the listener closes and the process\n" + " exits non-zero (with -i the REPL stays up instead).\n", argv[0]); ray_runtime_destroy(rt); return 0; @@ -282,6 +285,18 @@ int main(int argc, char** argv) { /* Load script if specified */ if (file) { rc = ray_repl_run_file(file); + /* The listener is already up (so the script may use it), which + * means a failed startup script would otherwise leave a port + * that accepts connections in front of an empty workspace: a + * supervisor's port check passes and Restart=on-failure never + * fires. Non-interactively, a script that fails to parse or + * evaluate is fatal; the listener goes down with the process. + * With -i the REPL stays up for the user to look around. */ + if (rc != 0 && !interactive && port > 0) { + fprintf(stderr, "startup script %s failed; closing listener on %s:%u and exiting\n", + file, bind_host[0] ? bind_host : "*", port); + goto done; + } if (!interactive && !(port > 0)) { /* A script that armed timers means to run them: stay until * they are spent (a one-shot fires once, a periodic one until diff --git a/src/app/repl.c b/src/app/repl.c index 35cbf4e7f..9b3862047 100644 --- a/src/app/repl.c +++ b/src/app/repl.c @@ -819,7 +819,7 @@ static void eval_and_print(ray_term_t* term, const char* input, ray_eval_clear_interrupt(); if (term) ray_term_eval_begin(term); - ray_t* nfo = ray_nfo_create("repl", 4, input, strlen(input)); + ray_t* nfo = ray_nfo_create(RAY_NFO_REPL_NAME, strlen(RAY_NFO_REPL_NAME), input, strlen(input)); ray_clear_error_trace(); ray_t* parsed = ray_parse_with_nfo(input, nfo); diff --git a/src/core/ipc.c b/src/core/ipc.c index 412ca2370..741271f32 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -1068,17 +1068,20 @@ static void ipc_on_close(ray_poll_t* poll, ray_selector_t* sel) * before the listener's own close path (which would otherwise also * route through here) runs the hook with a stale fd. Guard on: * - sel->data: the listener itself has no conn data. - * - listener_id ≥ 0: lifecycle hooks pair with inbound on.open - * only — outbound conns (ray_ipc_connect) never fired on.open, - * so they must not fire on.close either. - * - phase ≥ HEADER: the connection actually completed handshake - * (otherwise no matching on.open was fired, so on.close must - * also stay silent to keep the pair balanced for the user). */ + * - phase ≥ HEADER: the connection actually completed handshake. + * An inbound one that died mid-handshake never fired on.open; + * an outbound one is registered after its handshake, so it + * always qualifies. + * The hook fires for both directions (#503): a receive-only client — + * every multicast subscriber — otherwise learns of the peer's close + * only by probing. It fires once per established connection on any + * teardown (peer EOF, socket error, local .ipc.close, eviction); + * on.open stays inbound-only, and (.ipc.handle h) reports `inbound` + * so one handler can tell the direction. */ if (sel->data) { ray_ipc_conn_data_t* cd = (ray_ipc_conn_data_t*)sel->data; - if (cd->listener_id >= 0 && - (cd->phase == RAY_IPC_PHASE_HEADER || - cd->phase == RAY_IPC_PHASE_PAYLOAD)) { + if (cd->phase == RAY_IPC_PHASE_HEADER || + cd->phase == RAY_IPC_PHASE_PAYLOAD) { hook_call_lifecycle(poll, IPC_HOOK_CLOSE, sel->id); } /* A RESP deposited for a sync wait that never consumed it @@ -1780,7 +1783,7 @@ int64_t ray_ipc_connect(const char* host, uint16_t port, if (!cd) { ray_sock_close(fd); return -1; } memset(cd, 0, sizeof(*cd)); cd->phase = RAY_IPC_PHASE_HEADER; - cd->listener_id = -1; /* outbound — no lifecycle hooks */ + cd->listener_id = -1; /* outbound: on.open never fires, on.close does */ cd->restricted = poll->restricted; /* -U narrows pushed evals too */ ray_sock_set_nonblocking(fd); @@ -2089,6 +2092,8 @@ ray_err_t ray_ipc_tx_info(int64_t handle, ray_ipc_tx_info_t* out) conn_tx_limits(sel, &out->limit_bytes, &out->limit_frames); out->queued_bytes = conn_tx_pending(sel, &out->queued_frames); out->hwm_bytes = sel->tx.hwm_bytes; + out->inbound = sel->data && + ((ray_ipc_conn_data_t*)sel->data)->listener_id >= 0; return RAY_OK; } diff --git a/src/core/ipc.h b/src/core/ipc.h index 282ff1828..2a77fc623 100644 --- a/src/core/ipc.h +++ b/src/core/ipc.h @@ -159,6 +159,7 @@ typedef struct { int64_t queued_bytes; /* backlog right now */ int64_t queued_frames; int64_t hwm_bytes; /* largest backlog ever queued here */ + bool inbound; /* accepted by a listener here (true) or opened by .ipc.open (false) */ } ray_ipc_tx_info_t; void ray_ipc_tx_limit_get(int64_t* bytes, int64_t* frames); diff --git a/src/core/morsel.c b/src/core/morsel.c index ccc5d9c62..6fff44f7f 100644 --- a/src/core/morsel.c +++ b/src/core/morsel.c @@ -21,6 +21,7 @@ * SOFTWARE. */ +#include "vec/vec.h" #include "core/morsel.h" #include "core/platform.h" #include "mem/heap.h" @@ -80,7 +81,7 @@ bool ray_morsel_next(ray_morsel_t* m) { * directly would give stale zeros. Cost is one O(morsel_len) * sentinel scan per chunk; cheap given morsel_len <= 1024. */ m->null_bits = NULL; - if (m->vec->attrs & RAY_ATTR_HAS_NULLS) { + if (ray_vec_may_have_nulls(m->vec)) { int64_t bit0 = m->offset & 7; int64_t base_byte = m->offset / 8; int64_t total_bits = bit0 + m->morsel_len; diff --git a/src/io/csv.c b/src/io/csv.c index 800f810c9..269fb3daa 100644 --- a/src/io/csv.c +++ b/src/io/csv.c @@ -52,6 +52,7 @@ #include "table/sym.h" #include "table/domain.h" #include "vec/str.h" +#include "vec/vec.h" #include #include @@ -4123,10 +4124,7 @@ static void csv_col_info_init(csv_col_info_t* ci, ray_t* col) { /* has_nulls must consult the slice_parent, since a slice view * never carries its own null bitmap — ray_vec_is_null handles the * redirect but we still want a fast bypass when neither has nulls. */ - ci->has_nulls = false; - if (col && (col->attrs & RAY_ATTR_HAS_NULLS)) ci->has_nulls = true; - if (ci->data_owner && (ci->data_owner->attrs & RAY_ATTR_HAS_NULLS)) - ci->has_nulls = true; + ci->has_nulls = ray_vec_may_have_nulls(col); } static void csv_write_cell(csv_writer_t* w, const csv_col_info_t* ci, int64_t r) { diff --git a/src/lang/eval.c b/src/lang/eval.c index 81c5ae389..a3f08df94 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -226,7 +226,7 @@ static ray_t* try_sum_affine_expr(ray_t* expr, int* handled) { *handled = 0; return NULL; } - if (vec->attrs & RAY_ATTR_HAS_NULLS) { + if (ray_vec_may_have_nulls(vec)) { ray_release(vec); *handled = 0; return NULL; @@ -1145,9 +1145,9 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, dag_opcode == OP_LT || dag_opcode == OP_LE || dag_opcode == OP_GT || dag_opcode == OP_GE)) { int l_str_vec = left_coll && ray_is_vec(left) && left->type == RAY_STR && - !(left->attrs & RAY_ATTR_HAS_NULLS); + !ray_vec_has_nulls(left); int r_str_vec = right_coll && ray_is_vec(right) && right->type == RAY_STR && - !(right->attrs & RAY_ATTR_HAS_NULLS); + !ray_vec_has_nulls(right); int l_str_atom = !left_coll && left && left->type == -RAY_STR && !RAY_ATOM_IS_NULL(left); int r_str_atom = !right_coll && right && right->type == -RAY_STR && @@ -1503,9 +1503,7 @@ ray_t* gather_by_idx(ray_t* vec, int64_t* idx, int64_t n) { int8_t type = vec->type; /* Check nulls once — resolve through slices */ - bool has_nulls = (vec->attrs & RAY_ATTR_HAS_NULLS) || - ((vec->attrs & RAY_ATTR_SLICE) && vec->slice_parent && - (vec->slice_parent->attrs & RAY_ATTR_HAS_NULLS)); + bool has_nulls = ray_vec_may_have_nulls(vec); if (type == RAY_STR) { ray_t* result = ray_vec_new(type, n); @@ -3249,6 +3247,7 @@ static void ray_register_builtins(void) { register_vary("update", RAY_FN_SPECIAL_FORM | RAY_FN_RESTRICTED, ray_update); register_vary("insert", RAY_FN_SPECIAL_FORM | RAY_FN_RESTRICTED, ray_insert); register_vary("upsert", RAY_FN_SPECIAL_FORM | RAY_FN_RESTRICTED, ray_upsert); + register_vary("delete", RAY_FN_SPECIAL_FORM | RAY_FN_RESTRICTED, ray_delete); /* xbar is registered NON-atomic so the call path lands in * ray_xbar_fn(VEC, scalar) directly. ray_xbar_fn handles the * vector fast path itself (tight per-element loop, no per-atom @@ -4028,7 +4027,7 @@ ray_t* ray_eval(ray_t* obj) { ray_t* ray_eval_str(const char* source) { ray_clear_error_trace(); - ray_t* nfo = ray_nfo_create("repl", 4, source, strlen(source)); + ray_t* nfo = ray_nfo_create(RAY_NFO_REPL_NAME, strlen(RAY_NFO_REPL_NAME), source, strlen(source)); ray_t* parsed = ray_parse_with_nfo(source, nfo); if (RAY_IS_ERR(parsed)) { ray_release(nfo); return parsed; } diff --git a/src/lang/nfo.h b/src/lang/nfo.h index fe42050dc..8dbcf77c9 100644 --- a/src/lang/nfo.h +++ b/src/lang/nfo.h @@ -49,6 +49,10 @@ typedef union ray_span_t { * [3] vals (RAY_I64 vector — span ids) */ +/* Filename an nfo carries for input that came from no file — the REPL, + * ray_eval_str, a pipe. (.sys.args) reports `source` as empty for it. */ +#define RAY_NFO_REPL_NAME "repl" + #define NFO_FILENAME(nfo) ray_list_get((nfo), 0) #define NFO_SOURCE(nfo) ray_list_get((nfo), 1) #define NFO_KEYS(nfo) ray_list_get((nfo), 2) diff --git a/src/mem/heap.c b/src/mem/heap.c index 6260ff7be..1096ef782 100644 --- a/src/mem/heap.c +++ b/src/mem/heap.c @@ -1891,6 +1891,19 @@ ray_t* ray_alloc_copy(ray_t* v) { ray_atomic_store(©->rc, 1); else copy->rc = 1; + /* A table's key map (RAY_IDX_UKEY, ops/idxop.h) describes the rows of the + * table it was built for and upsert mutates it in place, recording the + * row count it now covers. Two tables sharing one would each be writing + * their own count into it, so a copy starts without it and builds its own + * on demand. Nothing else attaches an index to a RAY_TABLE, so clearing + * the bit here cannot discard anything else. Before retain, so the copy + * never takes a reference it does not keep. */ + if (copy->type == RAY_TABLE && (copy->attrs & RAY_ATTR_HAS_INDEX)) { + copy->index = NULL; + copy->_idx_pad = NULL; + copy->attrs &= (uint8_t)~RAY_ATTR_HAS_INDEX; + } + if (!ray_retain_owned_refs(copy)) { /* Deep-clone of an owned resource failed (e.g. HNSW index OOM). * The copy's owned state has already been neutralized, so a plain @@ -2820,3 +2833,175 @@ void ray_parallel_end(void) { atomic_store(&ray_parallel_flag, 0); ray_heap_gc(); } + +/* -------------------------------------------------------------------------- + * Native footprint — ray_shallow_bytes / ray_retained_bytes (rayforce.h) + * + * Read-only mirrors of the ownership rules in ray_release_owned_refs and + * of the mapping arithmetic in ray_free. Keep the three in step: a new + * owned child kind belongs in retained_walk, a new private-storage kind + * (one only its holder releases and no API hands out) in shallow too. + * -------------------------------------------------------------------------- */ + +/* Bytes of a file mapping owned by block v (mmod 1) — the size ray_free + * hands to the unmap. A string column reaches its region descriptor + * through its pool (or the registry once the pool was swapped); anything + * else is the page-rounded payload plus an inline passenger index. */ +static size_t mapped_block_bytes(const ray_t* v) { + if (v->type == RAY_TABLE || v->type == RAY_DICT || v->type == RAY_LIST) return 0; + if (v->type == RAY_STR) { + ray_file_map_t* m = NULL; + if (v->str_pool && !RAY_IS_ERR(v->str_pool) && v->str_pool->mmod == 3) + m = v->str_pool->file_map; + if (!m) m = ray_file_map_lookup(v); + if (m) return m->len; + } + if (v->type <= 0 || v->type >= RAY_TYPE_COUNT) return 0; + uint8_t esz = ray_sym_elem_size(v->type, v->attrs); + size_t data_size = 32 + (size_t)v->len * esz; + if (v->type == RAY_STR) { + size_t pool_len = 0; + if (v->str_pool && !RAY_IS_ERR(v->str_pool) && v->str_pool->len > 0) + pool_len = (size_t)v->str_pool->len; + data_size += 32 + pool_len; + } + if ((v->attrs & RAY_ATTR_HAS_INDEX) && v->index && !RAY_IS_ERR(v->index)) { + ray_index_t* ix = ray_index_payload(v->index); + if (ix->markers & RAY_MARK_MMAP) { + int64_t region_off = ((int64_t)data_size + 31) & ~(int64_t)31; + data_size = (size_t)(region_off + ray_index_inline_size(ix)); + } + } + return (data_size + 4095) & ~(size_t)4095; +} + +/* The allocation behind one block, and nothing it points at. */ +static size_t block_own_bytes(const ray_t* v) { + if (!v) return 0; + if (v->attrs & RAY_ATTR_ARENA) return 0; /* singletons, arena values */ + switch (v->mmod) { + case 1: return mapped_block_bytes(v); /* owns its mapping */ + case 2: return 0; /* borrowed */ + case 3: return 0; /* pool inside a column's region */ + default: break; + } + if (ray_is_direct(v)) return ray_direct_map_size(v); + if (v->order < RAY_ORDER_MIN || v->order > RAY_HEAP_MAX_ORDER) return 0; + return BSIZEOF(v->order); +} + +/* Heap-resident index: its block plus its tables. A mapping passenger is + * charged through the column's mapping. */ +static size_t index_own_bytes(const ray_t* idx) { + if (!idx || RAY_IS_ERR(idx) || idx->mmod == 1) return 0; + ray_index_t* ix = ray_index_payload((ray_t*)idx); + if (ix->markers & RAY_MARK_MMAP) return 0; + size_t n = block_own_bytes(idx); + ray_t* kids[4]; + int k = ray_index_child_blocks(ix, kids, 4); + for (int i = 0; i < k; i++) n += block_own_bytes(kids[i]); + return n; +} + +size_t ray_shallow_bytes(const ray_t* v) { + if (!v) return 0; + size_t n = block_own_bytes(v); + if (RAY_IS_ERR(v)) return n; + if (ray_is_atom(v)) { + if (ray_atom_owns_obj(v) && v->obj && !RAY_IS_ERR(v->obj)) + n += block_own_bytes(v->obj); + return n; + } + if (v->attrs & RAY_ATTR_SLICE) return n; + if (v->type == RAY_INDEX) return index_own_bytes(v); + if (v->attrs & RAY_ATTR_HAS_INDEX) n += index_own_bytes(v->index); + if (v->type == RAY_STR && v->str_pool && !RAY_IS_ERR(v->str_pool)) + n += block_own_bytes(v->str_pool); + return n; +} + +/* Pointer set for the retained walk: open addressing over ray_sys_alloc, + * so the walk never touches the heap it is measuring. On OOM the set stops + * growing and add() answers "new" for everything — the walk then still + * terminates (the value graph is acyclic) and can only over-count. */ +typedef struct { const ray_t** slots; size_t cap; size_t n; } ptrset_t; + +static bool ptrset_add(ptrset_t* s, const ray_t* p) { + if (s->n * 2 >= s->cap) { + size_t ncap = s->cap ? s->cap * 2 : 64; + const ray_t** ns = (const ray_t**)ray_sys_alloc(ncap * sizeof(*ns)); + if (!ns) return true; + memset(ns, 0, ncap * sizeof(*ns)); + for (size_t i = 0; i < s->cap; i++) { + const ray_t* q = s->slots[i]; + if (!q) continue; + size_t h = ((uintptr_t)q >> 5) & (ncap - 1); + while (ns[h]) h = (h + 1) & (ncap - 1); + ns[h] = q; + } + if (s->slots) ray_sys_free((void*)s->slots); + s->slots = ns; s->cap = ncap; + } + size_t h = ((uintptr_t)p >> 5) & (s->cap - 1); + while (s->slots[h]) { + if (s->slots[h] == p) return false; + h = (h + 1) & (s->cap - 1); + } + s->slots[h] = p; s->n++; + return true; +} + +static size_t retained_walk(const ray_t* v, ptrset_t* seen) { + if (!v || RAY_IS_ERR(v)) return 0; + if (!ptrset_add(seen, v)) return 0; + size_t n = block_own_bytes(v); + + if (ray_is_atom(v)) { + if (v->type == RAY_LAMBDA) { + ray_t* lam = (ray_t*)v; + ray_t** slots = (ray_t**)ray_data(lam); + for (int i = 0; i < 4; i++) n += retained_walk(slots[i], seen); + n += retained_walk(LAMBDA_NFO(lam), seen); + n += retained_walk(LAMBDA_DBG(lam), seen); + n += retained_walk(LAMBDA_CLOSURE(lam), seen); + return n; + } + if (ray_atom_owns_obj(v)) n += retained_walk(v->obj, seen); + return n; + } + if (v->attrs & RAY_ATTR_SLICE) return n + retained_walk(v->slice_parent, seen); + if (v->type == RAY_INDEX) { + ray_index_t* ix = ray_index_payload((ray_t*)v); + if (v->mmod == 1 || (ix->markers & RAY_MARK_MMAP)) return 0; + ray_t* kids[4]; + int k = ray_index_child_blocks(ix, kids, 4); + for (int i = 0; i < k; i++) n += retained_walk(kids[i], seen); + return n; + } + if ((v->attrs & RAY_ATTR_HAS_INDEX) && v->index && !RAY_IS_ERR(v->index) && + v->index->mmod != 1) + n += retained_walk(v->index, seen); + if (v->type == RAY_STR) { + if (v->str_pool && !RAY_IS_ERR(v->str_pool)) n += retained_walk(v->str_pool, seen); + return n; + } + if (v->type == RAY_SYM) return n; /* the domain is not a ray_t */ + if (RAY_IS_PARTED(v->type) || v->type == RAY_LIST) { + ray_t** ptrs = (ray_t**)ray_data((ray_t*)v); + for (int64_t i = 0; i < v->len; i++) n += retained_walk(ptrs[i], seen); + return n; + } + if (v->type == RAY_MAPCOMMON || v->type == RAY_TABLE || v->type == RAY_DICT) { + ray_t** slots = (ray_t**)ray_data((ray_t*)v); + n += retained_walk(slots[0], seen); + n += retained_walk(slots[1], seen); + } + return n; +} + +size_t ray_retained_bytes(const ray_t* v) { + ptrset_t seen = { NULL, 0, 0 }; + size_t n = retained_walk(v, &seen); + if (seen.slots) ray_sys_free((void*)seen.slots); + return n; +} diff --git a/src/ops/agg.c b/src/ops/agg.c index ab342bf8d..fcdb99858 100644 --- a/src/ops/agg.c +++ b/src/ops/agg.c @@ -143,7 +143,7 @@ static ray_t* agg_parted_sum(ray_t* x) { for (int64_t s = 0; s < x->len; s++) { ray_t* seg = segs[s]; if (!seg) continue; - int has_nulls = (seg->attrs & RAY_ATTR_HAS_NULLS) != 0; + int has_nulls = ray_vec_may_have_nulls(seg); for (int64_t i = 0; i < seg->len; i++) if (!has_nulls || !ray_vec_is_null(seg, i)) { if (base == RAY_F64) sum += ((double*)ray_data(seg))[i]; @@ -156,7 +156,7 @@ static ray_t* agg_parted_sum(ray_t* x) { for (int64_t s = 0; s < x->len; s++) { ray_t* seg = segs[s]; if (!seg) continue; - int has_nulls = (seg->attrs & RAY_ATTR_HAS_NULLS) != 0; + int has_nulls = ray_vec_may_have_nulls(seg); for (int64_t i = 0; i < seg->len; i++) if (!has_nulls || !ray_vec_is_null(seg, i)) sum = wrap_add_i64(sum, agg_read_i64(seg, i)); } @@ -173,7 +173,7 @@ static ray_t* agg_parted_avg(ray_t* x) { for (int64_t s = 0; s < x->len; s++) { ray_t* seg = segs[s]; if (!seg) continue; - int has_nulls = (seg->attrs & RAY_ATTR_HAS_NULLS) != 0; + int has_nulls = ray_vec_may_have_nulls(seg); if (base == RAY_F64 || base == RAY_F32) { for (int64_t i = 0; i < seg->len; i++) { if (has_nulls && ray_vec_is_null(seg, i)) continue; @@ -204,7 +204,7 @@ static ray_t* agg_parted_prod(ray_t* x) { for (int64_t s = 0; s < x->len; s++) { ray_t* seg = segs[s]; if (!seg) continue; - int has_nulls = (seg->attrs & RAY_ATTR_HAS_NULLS) != 0; + int has_nulls = ray_vec_may_have_nulls(seg); for (int64_t i = 0; i < seg->len; i++) { if (has_nulls && ray_vec_is_null(seg, i)) continue; if (base == RAY_F64) prod *= ((double*)ray_data(seg))[i]; @@ -218,7 +218,7 @@ static ray_t* agg_parted_prod(ray_t* x) { for (int64_t s = 0; s < x->len; s++) { ray_t* seg = segs[s]; if (!seg) continue; - int has_nulls = (seg->attrs & RAY_ATTR_HAS_NULLS) != 0; + int has_nulls = ray_vec_may_have_nulls(seg); for (int64_t i = 0; i < seg->len; i++) { if (has_nulls && ray_vec_is_null(seg, i)) continue; prod = wrap_mul_i64(prod, agg_read_i64(seg, i)); @@ -237,7 +237,7 @@ static ray_t* agg_parted_minmax(ray_t* x, int want_max) { for (int64_t s = 0; s < x->len; s++) { ray_t* seg = segs[s]; if (!seg) continue; - int has_nulls = (seg->attrs & RAY_ATTR_HAS_NULLS) != 0; + int has_nulls = ray_vec_may_have_nulls(seg); if (base == RAY_F64 || base == RAY_F32) { for (int64_t i = 0; i < seg->len; i++) { if (has_nulls && ray_vec_is_null(seg, i)) continue; @@ -294,7 +294,7 @@ static ray_t* agg_parted_truth(ray_t* x, int want_all) { for (int64_t s = 0; s < x->len; s++) { ray_t* seg = segs[s]; if (!seg) continue; - int has_nulls = (seg->attrs & RAY_ATTR_HAS_NULLS) != 0; + int has_nulls = ray_vec_may_have_nulls(seg); for (int64_t i = 0; i < seg->len; i++) { if (((i | s) & 65535) == 0 && ray_interrupted()) return ray_error("cancel", "interrupted"); @@ -317,7 +317,7 @@ static ray_t* agg_truth_vec(ray_t* x, int want_all) { return ray_error("type", want_all ? "all expects a numeric vector, got %s" : "any expects a numeric vector, got %s", ray_type_name(x->type)); - bool has_nulls = (x->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(x); int64_t seen = 0, truthy = 0; for (int64_t i = 0; i < x->len; i++) { if ((i & 65535) == 0 && ray_interrupted()) @@ -363,8 +363,8 @@ static ray_t* agg_pair_vec(ray_t* x, ray_t* y, uint16_t op) { if (!agg_numeric_flat_type(x->type) || !agg_numeric_flat_type(y->type)) return ray_error("type", "%s expects numeric vectors, got %s and %s", name, ray_type_name(x->type), ray_type_name(y->type)); - bool xn = (x->attrs & RAY_ATTR_HAS_NULLS) != 0; - bool yn = (y->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool xn = ray_vec_may_have_nulls(x); + bool yn = ray_vec_may_have_nulls(y); int64_t cnt = 0; double sx = 0.0, sy = 0.0, sxx = 0.0, syy = 0.0, sxy = 0.0; for (int64_t i = 0; i < x->len; i++) { @@ -426,7 +426,7 @@ ray_t* ray_sum_fn(ray_t* x) { if (x->type == RAY_I32 || x->type == RAY_I16 || x->type == RAY_U8 || x->type == RAY_TIME) { int64_t n = x->len; - bool has_nulls = (x->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(x); int64_t sum = 0; if (x->type == RAY_I32) { int32_t* d = (int32_t*)ray_data(x); diff --git a/src/ops/agg_engine.c b/src/ops/agg_engine.c index b4271a43b..08e6040ea 100644 --- a/src/ops/agg_engine.c +++ b/src/ops/agg_engine.c @@ -147,7 +147,7 @@ bool agg_dense_plan(ray_t** key_cols, uint32_t n_keys, case RAY_TIMESTAMP: case RAY_SYM: break; default: return false; } - if (kc->attrs & RAY_ATTR_HAS_NULLS) return false; + if (kc->type != RAY_SYM && ray_vec_may_have_nulls(kc)) return false; if (nrows <= 0) return false; /* empty → no min/max, maxagg_ops[a] != OP_COUNT) ? ray_table_get_col(tbl, ie->sym) : NULL; d->val_data[a] = vc ? ray_data(vc) : NULL; d->val_types[a] = vc ? vc->type : RAY_I64; - d->val_hasnull[a] = vc ? ((vc->attrs & RAY_ATTR_HAS_NULLS) != 0) : false; + d->val_hasnull[a] = vc ? ray_vec_may_have_nulls(vc) : false; d->val_esz[a] = vc ? col_esz(vc) : 0; /* Binary agg (pearson): resolve the y-side column from agg_ins2[a]. */ ray_t* vc2 = (ext->agg_ins2 && ext->agg_ins2[a] != RAY_OP_NONE) ? ray_table_get_col(tbl, find_ext(g, ext->agg_ins2[a])->sym) : NULL; d->val2_data[a] = vc2 ? ray_data(vc2) : NULL; d->val2_types[a] = vc2 ? vc2->type : RAY_I64; - d->val2_hasnull[a] = vc2 ? ((vc2->attrs & RAY_ATTR_HAS_NULLS) != 0) : false; + d->val2_hasnull[a] = vc2 ? ray_vec_may_have_nulls(vc2) : false; d->val2_esz[a] = vc2 ? col_esz(vc2) : 0; } return true; @@ -659,7 +659,7 @@ static bool agg_dense_plan_sel(ray_t** key_cols, uint32_t n_keys, int64_t n_sel, case RAY_TIMESTAMP: case RAY_SYM: break; default: return false; } - if (kc->attrs & RAY_ATTR_HAS_NULLS) return false; + if (kc->type != RAY_SYM && ray_vec_may_have_nulls(kc)) return false; out->mins[k] = INT64_MAX; out->ranges[k] = 0; /* sentinels; filled below */ } @@ -2959,7 +2959,7 @@ static ray_t* exec_group_v2_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, case RAY_TIMESTAMP: case RAY_SYM: break; default: keys_intsym = false; } - if (kc->attrs & RAY_ATTR_HAS_NULLS) keys_intsym = false; + if (kc->type != RAY_SYM && ray_vec_may_have_nulls(kc)) keys_intsym = false; } if (dense_par_ok) { @@ -3181,7 +3181,7 @@ ray_t* agg_run_one(const agg_vtable_t* vt, ray_t* val_col, ray_valid_t valid = { val_col ? ray_data(val_col) : NULL, val_col ? val_col->type : RAY_I64, - val_col ? ((val_col->attrs & RAY_ATTR_HAS_NULLS) != 0) : false }; + val_col ? ray_vec_may_have_nulls(val_col) : false }; const void* vals = val_col ? ray_data(val_col) : NULL; vt->update_batch(states, vt->state_size, gids, vals, &valid, nrows, NULL); @@ -3221,9 +3221,9 @@ ray_t* agg_run_one_bin(const agg_vtable_t* vt, ray_t* x_col, ray_t* y_col, vt->init(states + (size_t)gi * vt->state_size); ray_valid_t vx = { ray_data(x_col), x_col->type, - (x_col->attrs & RAY_ATTR_HAS_NULLS) != 0 }; + ray_vec_may_have_nulls(x_col) }; ray_valid_t vy = { ray_data(y_col), y_col->type, - (y_col->attrs & RAY_ATTR_HAS_NULLS) != 0 }; + ray_vec_may_have_nulls(y_col) }; vt->update_batch2(states, vt->state_size, gids, ray_data(x_col), ray_data(y_col), &vx, &vy, nrows, NULL); diff --git a/src/ops/agg_engine.h b/src/ops/agg_engine.h index 102c87a56..69058b471 100644 --- a/src/ops/agg_engine.h +++ b/src/ops/agg_engine.h @@ -79,7 +79,7 @@ typedef struct { } dense_plan_t; /* Decide if dense grouping applies to (key_cols, aggs). Eligible iff: - * - every key type in {I64,I32,I16,U8,BOOL,DATE,TIME,TIMESTAMP,SYM} and NOT HAS_NULLS + * - every key type in {I64,I32,I16,U8,BOOL,DATE,TIME,TIMESTAMP,SYM} with no nullable non-SYM keys * - product of per-key ranges is no larger than the contributing row count * (so dense state is O(input), never controlled by a machine-size budget) * Does one min/max prescan over the key columns. Sets out->ok accordingly. diff --git a/src/ops/builtins.c b/src/ops/builtins.c index 7e0c4c171..054ecb3f9 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -28,6 +28,7 @@ #include #include "lang/eval.h" #include "lang/internal.h" +#include "ops/idxop.h" /* ray_index_carry_append: keep a hash index across concat */ #include "lang/env.h" #include "core/platform.h" /* ray_vm_map_fd_ro / ray_vm_unmap_file (tracked) */ #include "vec/vec.h" @@ -842,7 +843,7 @@ static ray_t* cast_vec_copy_nulls(ray_t* vec, ray_t* val) { * null contract. Narrowing casts require writing the dest-width * sentinel directly — propagating through the cast macro produces * (int16_t)NULL_I32 = 0 etc., which collides with a legitimate value. */ - if (val->attrs & RAY_ATTR_HAS_NULLS) { + if (ray_vec_may_have_nulls(val)) { switch (vec->type) { case RAY_F64: { double* d = (double*)ray_data(vec); @@ -2080,21 +2081,55 @@ ray_t* ray_read_bytes_fn(ray_t* path_obj) { return read_file_bytes(path_obj, "read-bytes"); } -/* (load path) — read and evaluate a Rayfall script file via mmap */ +static bool load_path_is_absolute(const char* p) { + if (p[0] == '/' || p[0] == '\\') return true; +#if defined(RAY_OS_WINDOWS) + if (((p[0] >= 'A' && p[0] <= 'Z') || (p[0] >= 'a' && p[0] <= 'z')) && p[1] == ':') return true; +#endif + return false; +} + +/* Where a relative load path is looked for after the working directory: + * below $RAYFORCE_HOME, q's QHOME fallback (#506). Fills `alt` with the + * candidate and returns true when a home is set and the path is relative. */ +static bool load_home_candidate(const char* path, char* alt, size_t cap) { + if (load_path_is_absolute(path)) return false; + const char* home = getenv("RAYFORCE_HOME"); + if (!home || !*home) return false; + size_t hl = strlen(home); + while (hl > 1 && (home[hl - 1] == '/' || home[hl - 1] == '\\')) hl--; + int n = snprintf(alt, cap, "%.*s/%s", (int)hl, home, path); + return n > 0 && (size_t)n < cap; +} + +/* (load path) — read and evaluate a Rayfall script file via mmap. + * + * A relative path is resolved against the working directory first and, + * when that does not exist and RAYFORCE_HOME is set, below the home; + * an absolute path is used as given. Nested loads follow the same rule + * (relative to the working directory, not to the loading file, as q + * does). The path that was actually opened is what (.sys.args) + * reports as `source` while the file runs. */ ray_t* ray_load_file_fn(ray_t* path_obj) { if (path_obj->type != -RAY_STR) return ray_error("type", "load: path must be str, got %s", ray_type_name(path_obj->type)); const char* path = ray_str_ptr(path_obj); if (!path) return ray_error("domain", "load: empty path"); size_t path_len = ray_str_len(path_obj); + char alt[4096]; #if defined(RAY_OS_WINDOWS) /* Windows: fall back to fread */ FILE* fp = fopen(path, "r"); - if (!fp) return ray_error("io", NULL); + if (!fp && errno == ENOENT && load_home_candidate(path, alt, sizeof(alt))) { + fp = fopen(alt, "r"); + if (!fp) return ray_error("io", "load \"%s\": %s (also tried \"%s\")", path, strerror(ENOENT), alt); + path = alt; path_len = strlen(alt); + } + if (!fp) return ray_error("io", "load \"%s\": %s", path, strerror(errno)); fseek(fp, 0, SEEK_END); long sz = ftell(fp); fseek(fp, 0, SEEK_SET); - if (sz < 0) { fclose(fp); return ray_error("io", NULL); } + if (sz < 0) { int e = errno; fclose(fp); return ray_error("io", "load \"%s\": cannot determine size: %s", path, strerror(e)); } if (sz == 0) { fclose(fp); return ray_i64(0); } char* buf = (char*)ray_alloc_raw((size_t)sz + 1); if (!buf) { fclose(fp); return ray_error("oom", NULL); } @@ -2116,15 +2151,27 @@ ray_t* ray_load_file_fn(ray_t* path_obj) { ray_free_raw(buf); return result; #else + /* Every failure names the file and the OS cause: a bare `io` from a + * script's load is indistinguishable from an IPC, journal or storage + * failure and sends diagnosis the wrong way (#505). */ int fd = open(path, O_RDONLY); - if (fd < 0) return ray_error("io", NULL); + if (fd < 0 && errno == ENOENT && load_home_candidate(path, alt, sizeof(alt))) { + fd = open(alt, O_RDONLY); + if (fd < 0) return ray_error("io", "load \"%s\": %s (also tried \"%s\")", path, strerror(ENOENT), alt); + path = alt; path_len = strlen(alt); + } + if (fd < 0) return ray_error("io", "load \"%s\": %s", path, strerror(errno)); struct stat st; - if (fstat(fd, &st) < 0 || st.st_size < 0) { close(fd); return ray_error("io", NULL); } + if (fstat(fd, &st) < 0 || st.st_size < 0) { + int e = errno; close(fd); + return ray_error("io", "load \"%s\": cannot stat: %s", path, strerror(e)); + } + if (S_ISDIR(st.st_mode)) { close(fd); return ray_error("io", "load \"%s\": is a directory", path); } size_t sz = (size_t)st.st_size; if (sz == 0) { close(fd); return ray_i64(0); } char* map = (char*)ray_vm_map_fd_ro(fd, sz); - close(fd); - if (!map) return ray_error("io", NULL); + { int e = errno; close(fd); errno = e; } + if (!map) return ray_error("io", "load \"%s\": cannot map %zu bytes: %s", path, sz, strerror(errno)); /* Copy to NUL-terminated buffer -- mmap region may not have a trailing NUL */ char* buf = (char*)ray_alloc_raw(sz + 1); if (!buf) { ray_vm_unmap_file(map, sz); return ray_error("oom", NULL); } @@ -3298,8 +3345,13 @@ ray_t* ray_concat_fn(ray_t* a, ray_t* b) { return str_vec_concat_atom(b, a, true); /* Vector concat: same type — delegate to ray_vec_concat which handles * null bitmap propagation, SYM width promotion, and STR pool merging. */ - if (ray_is_vec(a) && ray_is_vec(b) && a->type == b->type) - return ray_vec_concat(a, b); + if (ray_is_vec(a) && ray_is_vec(b) && a->type == b->type) { + ray_t* r = ray_vec_concat(a, b); + /* An append onto an indexed vector keeps the index when every + * appended key is new (see ray_index_carry_append). */ + if (r && !RAY_IS_ERR(r) && ray_index_has(a)) ray_index_carry_append(a, r); + return r; + } /* Concat typed vec + boxed list or boxed list + typed vec -> boxed list */ if ((ray_is_vec(a) && b->type == RAY_LIST) || (a->type == RAY_LIST && ray_is_vec(b))) { ray_t* la = (a->type == RAY_LIST) ? a : NULL; @@ -3394,7 +3446,7 @@ ray_t* ray_concat_fn(ray_t* a, ray_t* b) { /* Null propagation: propagate null-ness of the leading atom * (a typed-null sentinel written raw at slot 0) and any nulls in the * trailing vector b. */ - if (RAY_ATOM_IS_NULL(a) || (b->attrs & RAY_ATTR_HAS_NULLS)) + if (RAY_ATOM_IS_NULL(a) || ray_vec_may_have_nulls(b)) result->attrs |= RAY_ATTR_HAS_NULLS; if (b->type == RAY_SYM) { /* Mixed sources: the atom id is runtime-domain by design, b's @@ -3445,8 +3497,9 @@ ray_t* ray_concat_fn(ray_t* a, ray_t* b) { result->len = na + 1; /* Null propagation: propagate nulls in the leading vector a * and null-ness of the trailing atom (sentinel written raw at na). */ - if ((a->attrs & RAY_ATTR_HAS_NULLS) || RAY_ATOM_IS_NULL(b)) + if (ray_vec_may_have_nulls(a) || RAY_ATOM_IS_NULL(b)) result->attrs |= RAY_ATTR_HAS_NULLS; + if (ray_index_has(a)) ray_index_carry_append(a, result); return result; } /* Atom + atom of same type -> 2-element vector */ @@ -3643,7 +3696,7 @@ ray_t* ray_raze_fn(ray_t* x) { for (int64_t i = 0; i < n; i++) { ray_t* it = items[i]; if (!ray_is_vec(it) || it->type != t - || (it->attrs & RAY_ATTR_HAS_NULLS)) { + || ray_vec_may_have_nulls(it)) { fast = false; break; } total += it->len; diff --git a/src/ops/cdfuse.c b/src/ops/cdfuse.c index b602e873f..5f7763d54 100644 --- a/src/ops/cdfuse.c +++ b/src/ops/cdfuse.c @@ -511,8 +511,8 @@ ray_t* ray_cd_fused(ray_t* key_col, ray_t* val_col, int64_t nrows) { if (!key_col || !val_col || nrows <= 0) return NULL; if (!ray_is_vec(key_col) || !ray_is_vec(val_col)) return NULL; if (!cdf_type_ok(key_col->type) || !cdf_type_ok(val_col->type)) return NULL; - if ((key_col->attrs & RAY_ATTR_HAS_NULLS) || - (val_col->attrs & RAY_ATTR_HAS_NULLS)) + if (ray_vec_may_have_nulls(key_col) || + ray_vec_may_have_nulls(val_col)) return NULL; if (key_col->len < nrows || val_col->len < nrows) return NULL; if (nrows < CDF_MIN_ROWS) return NULL; /* small: existing path fine */ diff --git a/src/ops/cmp.c b/src/ops/cmp.c index 831ab9968..ef9da147f 100644 --- a/src/ops/cmp.c +++ b/src/ops/cmp.c @@ -70,6 +70,18 @@ int sym_atom_cmp(ray_t* a, ray_t* b) { return r; } +/* Both operands integer-family atoms (I64/I32/I16/U8): order them as + * int64. A double is exact only to 2^53, so every i64 above it — any + * TIMESTAMP, a 64-bit hash, a packed key — would otherwise merge with its + * neighbours under <, >, <=, >= (and the dyadic min/max built on them) while + * == already told them apart (#524). Mixed float/int and BOOL/char pairs + * keep the double compare: their values are exact in a double. */ +static inline int both_int_atoms(const ray_t* a, const ray_t* b) { + int ia = a->type == -RAY_I64 || a->type == -RAY_I32 || a->type == -RAY_I16 || a->type == -RAY_U8; + int ib = b->type == -RAY_I64 || b->type == -RAY_I32 || b->type == -RAY_I16 || b->type == -RAY_U8; + return ia && ib; +} + /* Comparison */ ray_t* ray_gt_fn(ray_t* a, ray_t* b) { { int c; if (char_str_cmp(a, b, &c) == 0) return make_bool(c > 0 ? 1 : 0); } @@ -90,6 +102,7 @@ ray_t* ray_gt_fn(ray_t* a, ray_t* b) { if (na && nb) return make_bool(0); /* null == null → not > */ if (na) return make_bool(0); /* null > X → false */ if (nb) return make_bool(1); /* X > null → true */ + if (both_int_atoms(a, b)) return make_bool(as_i64(a) > as_i64(b) ? 1 : 0); return make_bool(as_f64(a) > as_f64(b) ? 1 : 0); } @@ -111,6 +124,7 @@ ray_t* ray_lt_fn(ray_t* a, ray_t* b) { if (na && nb) return make_bool(0); /* null == null → not < */ if (na) return make_bool(1); /* null < X → true */ if (nb) return make_bool(0); /* X < null → false */ + if (both_int_atoms(a, b)) return make_bool(as_i64(a) < as_i64(b) ? 1 : 0); return make_bool(as_f64(a) < as_f64(b) ? 1 : 0); } @@ -133,6 +147,7 @@ ray_t* ray_gte_fn(ray_t* a, ray_t* b) { if (na && nb) return make_bool(1); /* null == null → >= true */ if (na) return make_bool(0); /* null >= X → false */ if (nb) return make_bool(1); /* X >= null → true */ + if (both_int_atoms(a, b)) return make_bool(as_i64(a) >= as_i64(b) ? 1 : 0); return make_bool(as_f64(a) >= as_f64(b) ? 1 : 0); } @@ -155,6 +170,7 @@ ray_t* ray_lte_fn(ray_t* a, ray_t* b) { if (na && nb) return make_bool(1); /* null == null → <= true */ if (na) return make_bool(1); /* null <= X → true */ if (nb) return make_bool(0); /* X <= null → false */ + if (both_int_atoms(a, b)) return make_bool(as_i64(a) <= as_i64(b) ? 1 : 0); return make_bool(as_f64(a) <= as_f64(b) ? 1 : 0); } diff --git a/src/ops/collection.c b/src/ops/collection.c index c7248a21e..e91a7103f 100644 --- a/src/ops/collection.c +++ b/src/ops/collection.c @@ -189,7 +189,7 @@ static inline int hs_row_is_null(ray_t* src, int64_t i, void* data) { ray_t* e = ((ray_t**)data)[i]; return !e || RAY_ATOM_IS_NULL(e); } - return (src->attrs & RAY_ATTR_HAS_NULLS) && ray_vec_is_null(src, i); + return ray_vec_may_have_nulls(src) && ray_vec_is_null(src, i); } static bool hashset_init(hashset_t* hs, ray_t* src, int64_t hint) { @@ -207,7 +207,7 @@ static bool hashset_init(hashset_t* hs, ray_t* src, int64_t hint) { hs->null_idx = HS_EMPTY; hs->src = src; hs->src_type = src ? src->type : 0; - hs->src_has_nulls = src ? ((src->attrs & RAY_ATTR_HAS_NULLS) != 0) : false; + hs->src_has_nulls = src ? ray_vec_may_have_nulls(src) : false; hs->src_data = src ? ray_data(src) : NULL; return true; } @@ -381,6 +381,55 @@ static bool hashset_insert(hashset_t* hs, int64_t i) { return true; } +/* Vector-needle find with the NEEDLES hashed and the haystack scanned once: + * out[i] = first row of `hay` equal to needle i, NULL_I64 on a miss. The + * alternative (hash the haystack, probe the needles) costs a hash build over + * the big side per call; this costs one over the small side plus a scan that + * stops as soon as every distinct needle has been seen. `first` is indexed + * by the hashset's representative row (the first needle inserted with that + * key), so duplicate needles share one answer and a null needle matches the + * haystack's first null exactly as the haystack-hashed path does. + * Returns false only on OOM (caller falls back). */ +static bool find_hash_needles(ray_t* hay, ray_t* nd, int64_t* out, bool* any_null) { + int64_t m = nd->len, n = hay->len; + hashset_t hs; + if (!hashset_init(&hs, nd, m)) return false; + int64_t* first = (int64_t*)ray_sys_alloc((size_t)(m > 0 ? m : 1) * sizeof(int64_t)); + if (!first) { hashset_destroy(&hs); return false; } + int64_t distinct = 0; + for (int64_t j = 0; j < m; j++) { + first[j] = -1; + if (hashset_insert(&hs, j)) distinct++; + } + int8_t ht = hay->type; void* hd = ray_data(hay); + int64_t found = 0; + for (int64_t r = 0; r < n && found < distinct; r++) { + int64_t rep = hashset_find_xrow(&hs, hay, r, ht, hd); + if (rep != HS_EMPTY && first[rep] < 0) { first[rep] = r; found++; } + } + int8_t nt = nd->type; void* ndd = ray_data(nd); + for (int64_t i = 0; i < m; i++) { + int64_t rep = hashset_find_xrow(&hs, nd, i, nt, ndd); + int64_t pos = (rep == HS_EMPTY) ? -1 : first[rep]; + if (pos < 0) { out[i] = NULL_I64; *any_null = true; } + else out[i] = pos; + } + ray_sys_free(first); + hashset_destroy(&hs); + return true; +} + +/* Hash the smaller side only when the scan side probes cheaply: SYM rows + * from a DIFFERENT domain than the needles would need a per-row string + * translation (hashset_find_xrow's cross-domain arm) — hashing the + * haystack and translating the few needles is the right orientation there. */ +static bool find_needle_side_ok(ray_t* hay, ray_t* nd) { + if (nd->len >= hay->len) return false; + if (hay->type == RAY_SYM && nd->type == RAY_SYM && + ray_sym_vec_domain(hay) != ray_sym_vec_domain(nd)) return false; + return true; +} + /* ══════════════════════════════════════════ * Higher-order functions * ══════════════════════════════════════════ */ @@ -580,7 +629,7 @@ static ray_t* scan_typed_arith(ray_t* fn, ray_t* vec) { static ray_t* prior_typed_cmp(ray_t* fn, ray_t* vec) { if (fn->type != RAY_BINARY || !vec || !ray_is_vec(vec) || vec->len <= 0) return NULL; - if (vec->attrs & RAY_ATTR_HAS_NULLS) return NULL; + if (ray_vec_may_have_nulls(vec)) return NULL; ray_binary_fn bf = (ray_binary_fn)(uintptr_t)fn->i64; int op; /* 0:< 1:> 2:<= 3:>= 4:== 5:!= */ if (bf == ray_lt_fn) op = 0; @@ -1301,6 +1350,26 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { * hashset over `vec` once, probe per element of `val`. Was * O(len(val)×len(vec)); now O(len(val)+len(vec)). */ if (ray_is_vec(val) && ray_is_vec(vec)) { + /* Attached hash index on the set: one probe per needle, nothing + * built per call. Null needles miss (the index is consulted on + * null-free sets only), matching the hashset path below. */ + if (ray_index_has(vec)) { + ray_idx_consults[IDX_SITE_IN]++; + int64_t* pos = (int64_t*)ray_sys_alloc((size_t)vlen * sizeof(int64_t)); + if (!pos) return ray_error("oom", NULL); + bool miss = false; + if (ray_index_find_vec(vec, val, pos, &miss)) { + ray_idx_hits[IDX_SITE_IN]++; + ray_t* result = ray_vec_new(RAY_BOOL, vlen); + if (RAY_IS_ERR(result)) { ray_sys_free(pos); return result; } + result->len = vlen; + bool* out = (bool*)ray_data(result); + for (int64_t i = 0; i < vlen; i++) out[i] = pos[i] != NULL_I64; + ray_sys_free(pos); + return result; + } + ray_sys_free(pos); + } /* Typed kernel first: verdict-LUT for SYM, SIMD small-set for * ints, pool-parallel — the same engine the fused WHERE path * uses. Gated off null-bearing operands: this hashset path @@ -1308,8 +1377,8 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { * the WHERE kernel uses null-matches-nothing semantics — the * two must not be conflated. NULL result = unsupported shape * (STR etc.): fall through to the hashset probe below. */ - if (!(val->attrs & RAY_ATTR_HAS_NULLS) && - !(vec->attrs & RAY_ATTR_HAS_NULLS)) { + if (!ray_vec_may_have_nulls(val) && + !ray_vec_may_have_nulls(vec)) { ray_t* fast = ray_in_vec_exec(val, vec, false); if (fast) return fast; } @@ -1317,6 +1386,18 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { if (RAY_IS_ERR(result)) return result; result->len = vlen; bool* out = (bool*)ray_data(result); + /* Fewer needles than set rows: hash the needles and scan the + * set once instead of hashing the whole set per call. */ + if (find_needle_side_ok(vec, val)) { + int64_t* pos = (int64_t*)ray_sys_alloc((size_t)vlen * sizeof(int64_t)); + bool miss = false; + if (pos && find_hash_needles(vec, val, pos, &miss)) { + for (int64_t i = 0; i < vlen; i++) out[i] = pos[i] != NULL_I64; + ray_sys_free(pos); + return result; + } + if (pos) ray_sys_free(pos); + } hashset_t hs; if (!hashset_init(&hs, vec, vec->len)) { ray_release(result); @@ -1381,7 +1462,7 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { /* Typed vector: search without boxing */ if (ray_is_vec(vec) && ray_is_atom(val)) { int64_t len = vec->len; - bool has_nulls = (vec->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(vec); bool val_null = RAY_ATOM_IS_NULL(val); if (has_nulls) { for (int64_t i = 0; i < len; i++) { @@ -1724,9 +1805,7 @@ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { * (with retain) so the result owns a valid backing store. */ if (vtype == RAY_STR) col_propagate_str_pool(result, vec); /* Propagate null bitmap — check parent's flag for slices */ - bool has_nulls = (vec->attrs & RAY_ATTR_HAS_NULLS) || - ((vec->attrs & RAY_ATTR_SLICE) && vec->slice_parent && - (vec->slice_parent->attrs & RAY_ATTR_HAS_NULLS)); + bool has_nulls = ray_vec_may_have_nulls(vec); if (has_nulls) { for (int64_t i = 0; i < count; i++) if (ray_vec_is_null(vec, start + i)) @@ -1929,10 +2008,7 @@ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { /* SYM ids copied verbatim — resolve over the source domain. */ if (vtype == RAY_SYM) ray_sym_vec_adopt_domain(result, vec); /* Propagate null bitmap — check parent's flag for slices */ - bool has_nulls = len > 0 && - ((vec->attrs & RAY_ATTR_HAS_NULLS) || - ((vec->attrs & RAY_ATTR_SLICE) && vec->slice_parent && - (vec->slice_parent->attrs & RAY_ATTR_HAS_NULLS))); + bool has_nulls = len > 0 && ray_vec_may_have_nulls(vec); if (has_nulls) { if (n >= 0) { for (int64_t i = 0; i < abs_n; i++) @@ -2306,6 +2382,41 @@ ray_t* ray_at_fn(ray_t* vec, ray_t* idx) { int64_t n = ray_len(idx); ray_t* out = ray_list_new(n); if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + /* Typed keys probed by a typed vector of the same type: resolve + * every position in one `find` (attached hash index, else one + * hash build) instead of a scan of the keys per probe. The + * per-key path below stays for mixed shapes; a sliced key vector + * probed with nulls also stays there — the scalar lookup reads a + * slice's nulls through its parent, which the hash does not. */ + ray_t* dkeys = ray_dict_keys(vec); + ray_t* dvals = ray_dict_vals(vec); + if (dkeys && dvals && ray_is_vec(dkeys) && ray_is_vec(idx) && + idx->type == dkeys->type && + !((dkeys->attrs & RAY_ATTR_SLICE) && (idx->attrs & RAY_ATTR_HAS_NULLS))) { + ray_t* pos = ray_find_fn(dkeys, idx); + if (!pos || RAY_IS_ERR(pos)) { ray_release(out); return pos ? pos : ray_error("oom", NULL); } + const int64_t* pd = (const int64_t*)ray_data(pos); + int64_t nvals = ray_len(dvals); + for (int64_t i = 0; i < n; i++) { + ray_t* value; + if (pd[i] == NULL_I64 || pd[i] < 0 || pd[i] >= nvals) { + value = ray_typed_null(-RAY_I64); /* 0Nl for missing key */ + } else { + int alloc = 0; + value = collection_elem(dvals, pd[i], &alloc); + if (value && !RAY_IS_ERR(value) && !alloc) ray_retain(value); + } + if (!value || RAY_IS_ERR(value)) { + ray_release(pos); ray_release(out); + return value ? value : ray_error("oom", NULL); + } + out = ray_list_append(out, value); + ray_release(value); + if (!out || RAY_IS_ERR(out)) { ray_release(pos); return out ? out : ray_error("oom", NULL); } + } + ray_release(pos); + return out; + } for (int64_t i = 0; i < n; i++) { int allocated = 0; ray_t* key = collection_elem(idx, i, &allocated); @@ -2363,7 +2474,7 @@ ray_t* ray_at_fn(ray_t* vec, ray_t* idx) { int64_t idxlen = ray_len(idx); int64_t vlen = ray_len(vec); int64_t* ids = (int64_t*)ray_data(idx); - bool idx_has_nulls = (idx->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool idx_has_nulls = ray_vec_may_have_nulls(idx); bool valid = true; for (int64_t j = 0; j < idxlen; j++) { if ((idx_has_nulls && ray_vec_is_null(idx, j)) || @@ -2461,18 +2572,35 @@ ray_t* ray_find_fn(ray_t* vec, ray_t* val) { int64_t* out = (int64_t*)ray_data(result); bool any_null = false; - /* Hash fast path: both sides typed vecs — O(n+m), mirrors ray_in_fn. */ + /* Both sides typed vecs — O(n+m). In order of preference: + * 1. an attached hash index on the haystack: one probe per needle, + * nothing built per call; + * 2. fewer needles than rows: hash the needles, scan the haystack + * once (find_hash_needles); + * 3. hash the haystack, probe the needles (mirrors ray_in_fn). */ if (ray_is_vec(val) && ray_is_vec(vec)) { - hashset_t hs; - if (!hashset_init(&hs, vec, vec->len)) { ray_release(result); return ray_error("oom", NULL); } - for (int64_t j = 0; j < vec->len; j++) hashset_insert(&hs, j); - int8_t vt = val->type; void* vd = ray_data(val); - for (int64_t i = 0; i < vlen; i++) { - int64_t row = hashset_find_xrow(&hs, val, i, vt, vd); - if (row == HS_EMPTY) { out[i] = NULL_I64; any_null = true; } - else out[i] = row; + bool done = false; + if (ray_index_has(vec)) { + ray_idx_consults[IDX_SITE_FIND]++; + if (ray_index_find_vec(vec, val, out, &any_null)) { + ray_idx_hits[IDX_SITE_FIND]++; + done = true; + } + } + if (!done && find_needle_side_ok(vec, val)) + done = find_hash_needles(vec, val, out, &any_null); + if (!done) { + hashset_t hs; + if (!hashset_init(&hs, vec, vec->len)) { ray_release(result); return ray_error("oom", NULL); } + for (int64_t j = 0; j < vec->len; j++) hashset_insert(&hs, j); + int8_t vt = val->type; void* vd = ray_data(val); + for (int64_t i = 0; i < vlen; i++) { + int64_t row = hashset_find_xrow(&hs, val, i, vt, vd); + if (row == HS_EMPTY) { out[i] = NULL_I64; any_null = true; } + else out[i] = row; + } + hashset_destroy(&hs); } - hashset_destroy(&hs); } else { /* Fallback (LIST/mixed): per-element scalar find into the dense buffer. */ for (int64_t j = 0; j < vlen; j++) { @@ -2492,36 +2620,23 @@ ray_t* ray_find_fn(ray_t* vec, ray_t* val) { /* Typed vector: search without boxing */ if (ray_is_vec(vec)) { int64_t len = vec->len; - bool has_nulls = (vec->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(vec); bool val_null = RAY_ATOM_IS_NULL(val); - /* Hash-index fast path: integer-family needle against an indexed - * integer-family column without nulls. Float and cross-family - * needles fall through to the scan (the scan owns promotion - * semantics; we do not replicate them here). */ - if (!has_nulls && !val_null && ray_is_atom(val) && ray_index_has(vec)) { - int64_t needle = 0; - int eligible = 1; - switch (val->type) { - case -RAY_I64: - case -RAY_TIMESTAMP: needle = val->i64; break; - case -RAY_I32: - case -RAY_DATE: - case -RAY_TIME: needle = (int64_t)val->i32; break; - case -RAY_I16: needle = (int64_t)val->i16; break; - case -RAY_BOOL: - case -RAY_U8: needle = (int64_t)val->b8; break; - default: eligible = 0; break; - } - if (eligible) { - ray_idx_consults[IDX_SITE_FIND]++; - int64_t row = ray_index_find_row(vec, needle); - if (row >= -1) { /* -2 means not eligible — fall through */ - ray_idx_hits[IDX_SITE_FIND]++; - if (row < 0) - return ray_typed_null(-RAY_I64); - return make_i64(row); - } + /* Hash-index fast path: an integer-family, symbol or string needle + * against an indexed column of the same family (ray_index_find_atom + * owns the type matrix). Float and cross-family needles fall + * through to the scan (the scan owns promotion semantics; we do + * not replicate them here). */ + if (!val_null && ray_is_atom(val) && ray_index_has(vec) && + (!has_nulls || vec->type == RAY_SYM)) { + ray_idx_consults[IDX_SITE_FIND]++; + int64_t row = ray_index_find_atom(vec, val); + if (row >= -1) { /* -2 means not eligible — fall through */ + ray_idx_hits[IDX_SITE_FIND]++; + if (row < 0) + return ray_typed_null(-RAY_I64); + return make_i64(row); } } @@ -2594,7 +2709,7 @@ ray_t* reverse_vec_eager(ray_t* x) { if (vtype == RAY_STR) { ray_t* result = ray_vec_new(RAY_STR, len); if (RAY_IS_ERR(result)) return result; - bool has_nulls = (x->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(x); if (has_nulls) { for (int64_t i = 0; i < len; i++) { if (ray_vec_is_null(x, len - 1 - i)) { @@ -2627,7 +2742,7 @@ ray_t* reverse_vec_eager(ray_t* x) { if (vtype == RAY_SYM) esz = ray_sym_elem_size(vtype, x->attrs); char* src = (char*)ray_data(x); char* dst = (char*)ray_data(result); - bool has_nulls = (x->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(x); if (has_nulls) { for (int64_t i = 0; i < len; i++) { memcpy(dst + i * esz, src + (len - 1 - i) * esz, esz); @@ -2838,7 +2953,7 @@ ray_t* deltas_vec_eager(ray_t* x) { .src = x, .dst = out, .pool = pool, - .has_nulls = (x->attrs & RAY_ATTR_HAS_NULLS) != 0 + .has_nulls = ray_vec_may_have_nulls(x) }; ray_pool_dispatch(pool, ts_deltas_fn, &ctx, n - 1); if (pool_cancelled(pool)) { ray_release(out); return ray_error("cancel", "interrupted"); } @@ -2903,7 +3018,7 @@ ray_t* ratios_vec_eager(ray_t* x) { .src = x, .dst = out, .pool = pool, - .has_nulls = (x->attrs & RAY_ATTR_HAS_NULLS) != 0 + .has_nulls = ray_vec_may_have_nulls(x) }; ray_pool_dispatch(pool, ts_ratios_fn, &ctx, n - 1); if (pool_cancelled(pool)) { ray_release(out); return ray_error("cancel", "interrupted"); } @@ -3000,7 +3115,7 @@ ray_t* fills_vec_eager(ray_t* x) { } if (x->type == RAY_SYM || x->type == RAY_STR || x->type == RAY_BOOL || x->type == RAY_U8 || - (!(x->attrs & RAY_ATTR_HAS_NULLS) && !(x->attrs & RAY_ATTR_SLICE))) { + (!ray_vec_may_have_nulls(x) && !(x->attrs & RAY_ATTR_SLICE))) { ray_retain(x); return x; } @@ -3320,7 +3435,7 @@ ray_t* running_vec_eager(ray_t* x, uint16_t opcode) { .summary = summary, .carry = carry, .opcode = opcode, .is_float = (x->type == RAY_F64 || x->type == RAY_F32), - .has_nulls = (x->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE)) != 0, + .has_nulls = ray_vec_may_have_nulls(x), .nblocks = nblocks }; @@ -3674,7 +3789,7 @@ static ray_t* moving_prefix_vec_eager(ray_t* x, uint16_t opcode, int64_t window, .prefix_count = prefix_count, .summary = summary, .carry = carry, .opcode = opcode, - .has_nulls = (x->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE)) != 0, + .has_nulls = ray_vec_may_have_nulls(x), .window = window }; @@ -3826,7 +3941,7 @@ static ray_t* moving_minmax_vec_eager(ray_t* x, uint16_t opcode, int64_t window, .src = x, .dst = out, .pool = pool, .opcode = opcode, .is_float = (x->type == RAY_F64 || x->type == RAY_F32), - .has_nulls = (x->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE)) != 0, + .has_nulls = ray_vec_may_have_nulls(x), .window = window, .ntasks = (int64_t)ntasks }; diff --git a/src/ops/datalog.c b/src/ops/datalog.c index 243e1e973..3f3e5ddbc 100644 --- a/src/ops/datalog.c +++ b/src/ops/datalog.c @@ -73,6 +73,8 @@ void dl_program_free(dl_program_t* prog) { if (prog->rels[i].prov_src_data && !RAY_IS_ERR(prog->rels[i].prov_src_data)) ray_release(prog->rels[i].prov_src_data); } + for (int i = 0; i < prog->n_rules; i++) + dl_rule_free_exprs(&prog->rules[i]); ray_free(dl_prog_block(prog)); } @@ -245,6 +247,7 @@ int dl_add_rule(dl_program_t* prog, const dl_rule_t* rule) { int idx = prog->n_rules++; memcpy(&prog->rules[idx], rule, sizeof(dl_rule_t)); prog->rules[idx].stratum = -1; + if (dl_rule_clone_exprs(&prog->rules[idx]) < 0) { prog->n_rules--; return -1; } /* Ensure IDB relation exists for the head predicate */ dl_ensure_idb(prog, rule->head_pred, rule->head_arity); @@ -435,6 +438,59 @@ dl_expr_t* dl_expr_binop(int op, dl_expr_t* left, dl_expr_t* right) { return e; } +/* dl_expr_alloc allocates a ray_alloc block whose ray_data() is the + * dl_expr_t node; recover the block header to free it. */ +static inline ray_t* dl_expr_block(dl_expr_t* e) { return (ray_t*)((char*)e - 32); } + +void dl_expr_free(dl_expr_t* e) { + if (!e) return; + dl_expr_free(e->left); + dl_expr_free(e->right); + ray_free(dl_expr_block(e)); +} + +dl_expr_t* dl_expr_clone(const dl_expr_t* e) { + if (!e) return NULL; + dl_expr_t* c = dl_expr_alloc(); + if (!c) return NULL; + *c = *e; + c->left = c->right = NULL; + if (e->left) { c->left = dl_expr_clone(e->left); if (!c->left) { dl_expr_free(c); return NULL; } } + if (e->right) { c->right = dl_expr_clone(e->right); if (!c->right) { dl_expr_free(c); return NULL; } } + return c; +} + +void dl_rule_free_exprs(dl_rule_t* rule) { + if (!rule) return; + for (int i = 0; i < rule->n_body; i++) { + dl_body_t* b = &rule->body[i]; + dl_expr_free(b->assign_expr); b->assign_expr = NULL; + dl_expr_free(b->cmp_lhs_expr); b->cmp_lhs_expr = NULL; + dl_expr_free(b->cmp_rhs_expr); b->cmp_rhs_expr = NULL; + } +} + +int dl_rule_clone_exprs(dl_rule_t* rule) { + for (int i = 0; i < rule->n_body; i++) { + dl_body_t* b = &rule->body[i]; + dl_expr_t* a = dl_expr_clone(b->assign_expr); + dl_expr_t* l = dl_expr_clone(b->cmp_lhs_expr); + dl_expr_t* r = dl_expr_clone(b->cmp_rhs_expr); + if ((b->assign_expr && !a) || (b->cmp_lhs_expr && !l) || (b->cmp_rhs_expr && !r)) { + dl_expr_free(a); dl_expr_free(l); dl_expr_free(r); + /* Detach the shared originals so a later free of this copy + * cannot touch the caller's trees, then free what we cloned. */ + for (int j = 0; j < rule->n_body; j++) { + if (j < i) { dl_expr_free(rule->body[j].assign_expr); dl_expr_free(rule->body[j].cmp_lhs_expr); dl_expr_free(rule->body[j].cmp_rhs_expr); } + rule->body[j].assign_expr = rule->body[j].cmp_lhs_expr = rule->body[j].cmp_rhs_expr = NULL; + } + return -1; + } + b->assign_expr = a; b->cmp_lhs_expr = l; b->cmp_rhs_expr = r; + } + return 0; +} + /* ======================================================================== * Assignment and builtin rule builders * ======================================================================== */ @@ -749,7 +805,7 @@ static ray_t* dl_eval_expr(dl_expr_t* expr, ray_t* accum, case OP_ADD: od[r] = ld[r] + rd[r]; break; case OP_SUB: od[r] = ld[r] - rd[r]; break; case OP_MUL: od[r] = ld[r] * rd[r]; break; - case OP_DIV: od[r] = rd[r] != 0.0 ? ld[r] / rd[r] : 0.0; break; + case OP_DIV: od[r] = ld[r] / rd[r]; break; default: od[r] = 0.0; break; } } @@ -767,12 +823,14 @@ static ray_t* dl_eval_expr(dl_expr_t* expr, ray_t* accum, int64_t* rd = (int64_t*)ray_data(rv); int64_t* od = (int64_t*)ray_data(out); for (int64_t r = 0; r < nrows; r++) { + int64_t a = ld[r], b = rd[r], o; + if (a == NULL_I64 || b == NULL_I64) { od[r] = NULL_I64; continue; } switch (expr->binop) { - case OP_ADD: od[r] = ld[r] + rd[r]; break; - case OP_SUB: od[r] = ld[r] - rd[r]; break; - case OP_MUL: od[r] = ld[r] * rd[r]; break; - case OP_DIV: od[r] = rd[r] != 0 ? ld[r] / rd[r] : 0; break; - default: od[r] = 0; break; + case OP_ADD: od[r] = __builtin_add_overflow(a, b, &o) ? NULL_I64 : o; break; + case OP_SUB: od[r] = __builtin_sub_overflow(a, b, &o) ? NULL_I64 : o; break; + case OP_MUL: od[r] = __builtin_mul_overflow(a, b, &o) ? NULL_I64 : o; break; + case OP_DIV: od[r] = (b == 0 || (a == INT64_MIN && b == -1)) ? NULL_I64 : a / b; break; + default: od[r] = NULL_I64; break; } } ray_release(lv); @@ -1022,20 +1080,51 @@ static ray_t* dl_antijoin_tables(ray_t* left, ray_t* right, * back to a payload compare when the cell carries the matching tag — * so a body literal can pin both an untagged RAY_SYM column built * from a rule head and a DATOM-tagged RAY_I64 column built from EAV - * storage without the frontend having to know which is which. */ + * storage without the frontend having to know which is which. + * + * `strict_tag` narrows that leniency for the one column where it would + * otherwise reopen the audit #1.5 ambiguity: the "eav" relation's v + * column, the only column any frontend ever writes a DATOM tag into. + * A plain integer stored there via assert-fact (e.g. a symbol's own + * intern id, round-tripped through pull as a bare I64 and re-asserted) + * can coincide numerically with a symbol/string literal's intern id; + * without strict_tag the direct `cell == value` compare below would + * wrongly call that a match. Callers pass strict_tag only for that + * column — every other column (the "a" column included, and any + * rule-derived relation) is never DATOM-tagged, so the lenient direct + * compare remains correct and necessary there. + * + * Audit #1.5 is about integers vs symbols, not strings vs symbols: + * assert-fact only ever stores an integer or a symbol, so a `"foo"` STR + * literal in a triple pattern can only mean the symbol named "foo" — the + * frontend comment above already interns a STR literal as a sym for + * exactly this reason. So under strict_tag a RAY_STR literal matches a + * DL_DATOM_TAG_SYM-tagged cell by payload (as well as a STR-tagged one, + * should a future frontend ever write that tag); a RAY_SYM literal + * matches only a SYM-tagged cell; a RAY_I64 literal matches only a + * genuinely untagged cell, numerically. */ static bool dl_col_eq_row(ray_t* col, int64_t row, int64_t value, - int8_t const_type) { + int8_t const_type, bool strict_tag) { + if (col->type == RAY_F64) { + double cell = ((double*)ray_data(col))[row]; + if (const_type == RAY_F64) { double v; memcpy(&v, &value, sizeof v); return cell == v; } + if (const_type == RAY_I64) return cell == (double)value; + return false; + } if (col->type == RAY_I64) { int64_t cell = ((int64_t*)ray_data(col))[row]; - if (cell == value) return true; - int64_t cell_tag = cell & (int64_t)0x6000000000000000; + if (const_type == RAY_F64) { double v; memcpy(&v, &value, sizeof v); return (double)cell == v; } + if (!strict_tag || (const_type != RAY_STR && const_type != RAY_SYM)) { + if (cell == value) return true; + } + int64_t cell_tag = cell & DL_DATOM_TAG_MASK; if (cell_tag == 0) return false; /* plain int column */ - int64_t cell_payload = cell & (int64_t)0x1FFFFFFFFFFFFFFF; + int64_t cell_payload = cell & DL_DATOM_PAYLOAD; if (const_type == RAY_STR && - cell_tag == (int64_t)0x4000000000000000) + (cell_tag == DL_DATOM_TAG_STR || cell_tag == DL_DATOM_TAG_SYM)) return cell_payload == value; if (const_type == RAY_SYM && - cell_tag == (int64_t)0x2000000000000000) + cell_tag == DL_DATOM_TAG_SYM) return cell_payload == value; return false; } @@ -1044,8 +1133,73 @@ static bool dl_col_eq_row(ray_t* col, int64_t row, int64_t value, return false; } +/* Copy the rows of tbl where keep[r] != 0 (count = number of such rows) + * into a new table with identical schema (SYM width/domain preserved). + * keep == NULL with count == 0 builds the empty table of the same schema. + * Returns an owned table or RAY_ERROR. */ +static ray_t* dl_table_take_mask(ray_t* tbl, const uint8_t* keep, int64_t count) { + int64_t nrows = ray_table_nrows(tbl); + int64_t ncols = ray_table_ncols(tbl); + ray_t* out = ray_table_new((int)ncols); + if (!out) return ray_error("memory", "dl_table_take_mask: table_new"); + if (RAY_IS_ERR(out)) return out; + for (int64_t c = 0; c < ncols; c++) { + ray_t* src = ray_table_get_col_idx(tbl, c); + if (!src) { ray_release(out); return ray_error("domain", "dl_table_take_mask: missing source column"); } + ray_t* dst = (src->type == RAY_SYM) + ? ray_sym_vec_new(src->attrs & RAY_SYM_W_MASK, count) + : ray_vec_new(src->type, count); + if (!dst) { ray_release(out); return ray_error("memory", "dl_table_take_mask: vec_new"); } + if (RAY_IS_ERR(dst)) { ray_error_free(dst); ray_release(out); return ray_error("memory", "dl_table_take_mask: vec_new"); } + dst->len = count; + if (src->type == RAY_SYM) ray_sym_vec_adopt_domain(dst, src); + uint8_t esz = ray_sym_elem_size(src->type, src->attrs); + const uint8_t* src_b = (const uint8_t*)ray_data(src); + uint8_t* dst_b = (uint8_t*)ray_data(dst); + int64_t j = 0; + for (int64_t r = 0; keep && r < nrows; r++) { + if (!keep[r]) continue; + memcpy(dst_b + (size_t)j * esz, src_b + (size_t)r * esz, (size_t)esz); + j++; + } + if (src->type == RAY_STR) col_propagate_str_pool(dst, src); + ray_t* next = ray_table_add_col(out, ray_table_col_name(tbl, c), dst); + ray_release(dst); + if (!next) { ray_release(out); return ray_error("memory", "dl_table_take_mask: add_col"); } + if (RAY_IS_ERR(next)) { ray_release(out); return next; } + out = next; + } + return out; +} + +/* Strip the DATOM tag from every cell of an I64 result column so + * query projection returns plain intern ids like the rest of the + * user-visible API (pull, scan-eav). Returns a retained reference to + * `col` unchanged when it's not I64 or carries no tagged cell, so the + * common case is a cheap no-op. */ +static ray_t* dl_untag_i64_col(ray_t* col) { + if (col->type != RAY_I64) { ray_retain(col); return col; } + int64_t n = col->len; + const int64_t* d = (const int64_t*)ray_data(col); + int64_t i = 0; + /* Same v >= 0 guard as dl_datom_untag: a negative cell can never be a + * genuine tag (sign extension spuriously sets the tag bits), so the + * pre-scan must not treat it as one -- otherwise a column that is all + * plain, untagged, possibly-negative integers would still take the + * (needlessly allocating, and for negatives previously corrupting) + * per-cell path below instead of the no-op retain. */ + while (i < n && !(d[i] >= 0 && (d[i] & DL_DATOM_TAG_MASK))) i++; + if (i == n) { ray_retain(col); return col; } + ray_t* out = ray_vec_new(RAY_I64, n); + if (!out || RAY_IS_ERR(out)) return out; + out->len = n; + int64_t* o = (int64_t*)ray_data(out); + for (int64_t r = 0; r < n; r++) o[r] = dl_datom_untag(d[r]); + return out; +} + static ray_t* dl_filter_eq(ray_t* tbl, int col_idx, int64_t value, - int8_t const_type) { + int8_t const_type, bool strict_tag) { /* Contract: always return an owned reference (rc bumped) so the * caller can release uniformly. Every pass-through must therefore * retain — else the caller's `ray_release(body_tbl); body_tbl = @@ -1056,12 +1210,11 @@ static ray_t* dl_filter_eq(ray_t* tbl, int col_idx, int64_t value, ray_t* col = ray_table_get_col_idx(tbl, col_idx); if (!col) { ray_retain(tbl); return tbl; } - /* Non-numeric, non-sym keys: not supported by this filter — pass - * through (retained) rather than miscompare via raw memcpy. */ - if (col->type != RAY_I64 && col->type != RAY_SYM) { - ray_retain(tbl); - return tbl; - } + /* Non-numeric, non-sym keys: not supported by this filter — raise a + * type error rather than silently passing every row through. */ + if (col->type != RAY_I64 && col->type != RAY_SYM && col->type != RAY_F64) + return ray_error("type", "datalog: constant filter on unsupported column type %s", + ray_type_name(col->type)); /* sym-domain Phase 2: for a SYM column, `value` is a runtime-domain * literal id (datalog constants intern at parse), while the cells @@ -1080,65 +1233,76 @@ static ray_t* dl_filter_eq(ray_t* tbl, int col_idx, int64_t value, } int64_t nrows = ray_table_nrows(tbl); - int64_t ncols = ray_table_ncols(tbl); - /* Count matching rows — type-aware read for RAY_SYM adaptive width. */ + /* Compute the keep mask — type-aware read for RAY_SYM adaptive width. */ + ray_t* keep_block = ray_alloc((size_t)nrows); + if (!keep_block || RAY_IS_ERR(keep_block)) return ray_error("memory", "dl_filter_eq: mask alloc"); + uint8_t* keep = (uint8_t*)ray_data(keep_block); int64_t count = 0; - for (int64_t r = 0; r < nrows; r++) - if (dl_col_eq_row(col, r, value, const_type)) count++; + for (int64_t r = 0; r < nrows; r++) { + keep[r] = dl_col_eq_row(col, r, value, const_type, strict_tag) ? 1 : 0; + count += keep[r]; + } - if (count == nrows) { ray_retain(tbl); return tbl; } + if (count == nrows) { ray_free(keep_block); ray_retain(tbl); return tbl; } /* Build filtered table. Each surviving column is allocated with * its source's element-size (via ray_sym_elem_size) so narrow-SYM * stays narrow rather than being silently widened to W64. */ - ray_t* out = ray_table_new((int)ncols); - if (!out) return ray_error("memory", "dl_filter_eq: table_new"); - if (RAY_IS_ERR(out)) return out; - for (int64_t c = 0; c < ncols; c++) { - ray_t* src = ray_table_get_col_idx(tbl, c); - if (!src) { - ray_release(out); - return ray_error("domain", "dl_filter_eq: missing source column"); - } - ray_t* dst = (src->type == RAY_SYM) - ? ray_sym_vec_new(src->attrs & RAY_SYM_W_MASK, count) - : ray_vec_new(src->type, count); - if (!dst) { ray_release(out); return ray_error("memory", "dl_filter_eq: vec_new"); } - if (RAY_IS_ERR(dst)) { ray_error_free(dst); ray_release(out); return ray_error("memory", "dl_filter_eq: vec_new"); } - dst->len = count; - /* raw SYM cell-id copies resolve over the source's dictionary */ - if (src->type == RAY_SYM) ray_sym_vec_adopt_domain(dst, src); - uint8_t esz = ray_sym_elem_size(src->type, src->attrs); - const uint8_t* src_b = (const uint8_t*)ray_data(src); - uint8_t* dst_b = (uint8_t*)ray_data(dst); - int64_t j = 0; - for (int64_t r = 0; r < nrows; r++) { - if (dl_col_eq_row(col, r, value, const_type)) { - memcpy(dst_b + (size_t)j * esz, - src_b + (size_t)r * esz, - (size_t)esz); - j++; - } - } - if (src->type == RAY_STR) col_propagate_str_pool(dst, src); - ray_t* next = ray_table_add_col(out, ray_table_col_name(tbl, c), dst); - ray_release(dst); - /* ray_table_add_col does not release `out` on failure, so we - * must release the partially-built table before bailing out. */ - if (!next) { - ray_release(out); - return ray_error("memory", "dl_filter_eq: add_col"); - } - if (RAY_IS_ERR(next)) { - ray_release(out); - return next; - } - out = next; + ray_t* out = dl_table_take_mask(tbl, keep, count); + ray_free(keep_block); + return out; +} + +static int64_t dl_cell_i64(ray_t* col, int64_t row) { + if (col->type == RAY_SYM) + return ray_read_sym(ray_data(col), row, col->type, col->attrs); + return ((int64_t*)ray_data(col))[row]; +} + +/* Rows where column c1 == column c2 (I64/SYM cells read as int64). + * Owned result; retains and returns tbl unchanged when all rows match. */ +static ray_t* dl_filter_col_eq(ray_t* tbl, int c1, int c2) { + if (!tbl || RAY_IS_ERR(tbl)) { if (tbl) ray_retain(tbl); return tbl; } + int64_t nrows = ray_table_nrows(tbl); + if (nrows == 0) { ray_retain(tbl); return tbl; } + ray_t* a = ray_table_get_col_idx(tbl, c1); + ray_t* b = ray_table_get_col_idx(tbl, c2); + if (!a || !b) return ray_error("domain", "datalog: repeated-variable filter on missing column"); + if ((a->type != RAY_I64 && a->type != RAY_SYM) || (b->type != RAY_I64 && b->type != RAY_SYM)) + return ray_error("type", "datalog: repeated variable over unsupported column type %s", + ray_type_name(a->type != RAY_I64 && a->type != RAY_SYM ? a->type : b->type)); + ray_t* keep_block = ray_alloc((size_t)nrows); + if (!keep_block || RAY_IS_ERR(keep_block)) return ray_error("memory", "datalog: mask alloc"); + uint8_t* keep = (uint8_t*)ray_data(keep_block); + int64_t count = 0; + for (int64_t r = 0; r < nrows; r++) { + keep[r] = dl_cell_i64(a, r) == dl_cell_i64(b, r); + count += keep[r]; } + ray_t* out; + if (count == nrows) { ray_retain(tbl); out = tbl; } + else out = dl_table_take_mask(tbl, keep, count); + ray_free(keep_block); return out; } +/* Apply dl_filter_col_eq for every pair of positions in body sharing a + * variable. Consumes tbl, returns an owned table or RAY_ERROR/NULL. */ +static ray_t* dl_filter_repeated_vars(ray_t* tbl, const dl_body_t* body) { + for (int i = 0; i < body->arity && tbl && !RAY_IS_ERR(tbl); i++) { + if (body->vars[i] == DL_CONST) continue; + for (int j = i + 1; j < body->arity; j++) { + if (body->vars[j] != body->vars[i]) continue; + ray_t* f = dl_filter_col_eq(tbl, i, j); + ray_release(tbl); + tbl = f; + if (!tbl || RAY_IS_ERR(tbl)) return tbl; + } + } + return tbl; +} + /* Helper: build a fully-owned broadcast column for a constant head slot. * * Returns a fresh ray_t* vec with refcount 1, caller-owned. The caller is @@ -1328,7 +1492,7 @@ static ray_t* dl_project(ray_t* tbl, const int* col_indices, int n_out, } ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, - int delta_pos, int rule_idx, ray_graph_t* g) { + const dl_delta_t* delta, int rule_idx, ray_graph_t* g) { /* Materializing approach: execute body atoms one at a time. * * For each positive body atom, we get the relation table and apply @@ -1352,14 +1516,23 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, int rel_idx = dl_find_rel(prog, body->pred); if (rel_idx < 0) { if (accum) ray_release(accum); return NULL; } dl_rel_t* rel = &prog->rels[rel_idx]; - ray_t* body_tbl = rel->table; + /* Semi-naive: exactly one body position reads the iteration delta; + * every other occurrence of the same predicate reads the full + * relation so old×new combinations are derived (audit §1.1). */ + ray_t* body_tbl = (delta && delta->pos == b && delta->table) + ? delta->table : rel->table; ray_retain(body_tbl); /* Apply constant filters */ for (int c = 0; c < body->arity; c++) { if (body->vars[c] == DL_CONST) { + /* Only the "eav" relation's v column (position 2) is ever + * DATOM-tagged (audit #1.5) — everywhere else (the "a" + * column included) a plain I64/SYM cell is a genuine, + * untagged value and the lenient compare is correct. */ + bool strict_tag = c == 2 && strcmp(body->pred, DL_EAV_PRED) == 0; ray_t* filtered = dl_filter_eq(body_tbl, c, body->const_vals[c], - body->const_types[c]); + body->const_types[c], strict_tag); ray_release(body_tbl); if (!filtered) { /* Treat as genuine failure — dl_filter_eq returns an @@ -1379,6 +1552,15 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, } } + body_tbl = dl_filter_repeated_vars(body_tbl, body); + if (!body_tbl) { if (accum) ray_release(accum); prog->eval_err = true; return NULL; } + if (RAY_IS_ERR(body_tbl)) { + ray_error_free(body_tbl); + if (accum) ray_release(accum); + prog->eval_err = true; + return NULL; + } + if (accum == NULL) { /* First body atom: accum = body_tbl */ accum = body_tbl; @@ -1520,8 +1702,9 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, ray_retain(neg_tbl); for (int c = 0; c < body->arity; c++) { if (body->vars[c] == DL_CONST) { + bool strict_tag = c == 2 && strcmp(body->pred, DL_EAV_PRED) == 0; ray_t* filtered = dl_filter_eq(neg_tbl, c, body->const_vals[c], - body->const_types[c]); + body->const_types[c], strict_tag); ray_release(neg_tbl); if (!filtered) { ray_release(accum); @@ -1538,6 +1721,15 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, } } + neg_tbl = dl_filter_repeated_vars(neg_tbl, body); + if (!neg_tbl) { ray_release(accum); prog->eval_err = true; return NULL; } + if (RAY_IS_ERR(neg_tbl)) { + ray_error_free(neg_tbl); + ray_release(accum); + prog->eval_err = true; + return NULL; + } + int lkeys[DL_MAX_ARITY], rkeys[DL_MAX_ARITY]; int n_keys = 0; for (int c = 0; c < body->arity; c++) { @@ -1554,6 +1746,13 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, ray_t* result = dl_antijoin_tables(accum, neg_tbl, lkeys, rkeys, n_keys); ray_release(accum); accum = result; + } else if (ray_table_nrows(neg_tbl) > 0) { + /* No join keys: the negated literal is ground (or all-fresh + * variables). A non-empty match falsifies every accumulated + * row (audit §1.3); an empty match leaves accum untouched. */ + ray_t* empty = dl_table_take_mask(accum, NULL, 0); + ray_release(accum); + accum = empty; } ray_release(neg_tbl); break; @@ -2632,11 +2831,22 @@ static void dl_build_source_prov(dl_program_t* prog, dl_rel_t* rel, for (int c = 0; c < body->arity; c++) { ray_t* bcol = ray_table_get_col_idx(brel->table, c); if (!bcol) { match = false; break; } - int64_t cell = ((int64_t*)ray_data(bcol))[br]; int v = body->vars[c]; if (v == DL_CONST) { - if (cell != body->const_vals[c]) { match = false; break; } + /* Type-aware compare — matches dl_col_eq_row's + * rules (incl. F64 columns/literals and + * DATOM-tagged I64 columns) rather than a raw + * int64 bit-compare, which would silently + * mismatch an F64 literal against an I64 column + * (and vice versa). strict_tag mirrors dl_compile_rule: + * only the "eav" relation's v column is ever tagged. */ + bool strict_tag = c == 2 && strcmp(body->pred, DL_EAV_PRED) == 0; + if (!dl_col_eq_row(bcol, br, body->const_vals[c], + body->const_types[c], strict_tag)) { + match = false; break; + } } else if (var_set[v]) { + int64_t cell = ((int64_t*)ray_data(bcol))[br]; if (cell != var_vals[v]) { match = false; break; } } /* body-only variable: unconstrained, always matches */ @@ -2711,7 +2921,7 @@ static void dl_build_provenance(dl_program_t* prog) { ray_graph_t* g = ray_graph_new(NULL); if (!g) continue; - ray_op_t* output = dl_compile_rule(prog, rule, -1, r, g); + ray_op_t* output = dl_compile_rule(prog, rule, NULL, r, g); if (!output) { ray_graph_free(g); continue; } ray_t* raw = ray_execute(g, output); @@ -2806,7 +3016,7 @@ int dl_eval(dl_program_t* prog) { ray_graph_t* g = ray_graph_new(NULL); if (!g) { prog->eval_err = true; continue; } - ray_op_t* output = dl_compile_rule(prog, rule, -1, stratum_rule_idx[ri], g); + ray_op_t* output = dl_compile_rule(prog, rule, NULL, stratum_rule_idx[ri], g); if (!output) { /* dl_compile_rule marks eval_err on genuine failures; a bare * NULL means "rule has no rows this pass" — not a fault. */ @@ -2924,21 +3134,13 @@ int dl_eval(dl_program_t* prog) { if (!delta_tables[body_rel] || ray_table_nrows(delta_tables[body_rel]) == 0) continue; - /* Swap in delta relation for this body position */ - ray_t* saved = prog->rels[body_rel].table; - prog->rels[body_rel].table = delta_tables[body_rel]; - + dl_delta_t d = { b, delta_tables[body_rel] }; ray_graph_t* g = ray_graph_new(NULL); - if (!g) { - prog->rels[body_rel].table = saved; - prog->eval_err = true; - continue; - } + if (!g) { prog->eval_err = true; continue; } - ray_op_t* output = dl_compile_rule(prog, rule, b, stratum_rule_idx[ri], g); + ray_op_t* output = dl_compile_rule(prog, rule, &d, stratum_rule_idx[ri], g); if (!output) { ray_graph_free(g); - prog->rels[body_rel].table = saved; /* dl_compile_rule sets eval_err itself on genuine * failures; NULL without the flag means "rule yields * no rows this iteration" and should not fault. */ @@ -2947,7 +3149,6 @@ int dl_eval(dl_program_t* prog) { ray_t* raw_result = ray_execute(g, output); ray_graph_free(g); - prog->rels[body_rel].table = saved; if (!raw_result) continue; if (RAY_IS_ERR(raw_result)) { prog->eval_err = true; ray_error_free(raw_result); continue; } @@ -3174,7 +3375,7 @@ ray_t* ray_assert_fact_fn(ray_t** args, int64_t n) { if (value->type == -RAY_I64) { v_val = value->i64; } else if (value->type == -RAY_SYM) { - v_val = value->i64; /* sym intern ID is already i64 */ + v_val = DL_DATOM_TAG_SYM | value->i64; /* tag so it can't collide with a plain integer */ } else { return ray_error("type", "assert-fact: value must be an integer or symbol"); } @@ -3242,7 +3443,7 @@ ray_t* ray_retract_fact_fn(ray_t** args, int64_t n) { if (value->type == -RAY_I64) match_v = value->i64; else if (value->type == -RAY_SYM) - match_v = value->i64; + match_v = DL_DATOM_TAG_SYM | value->i64; /* same tag assert-fact wrote */ else return ray_error("type", "retract-fact: value must be an integer or symbol"); @@ -3341,7 +3542,8 @@ ray_t* ray_scan_eav_fn(ray_t** args, int64_t n) { if (a_val == attr_id) { re = ray_vec_append(re, &e_data[r]); if (RAY_IS_ERR(re)) { ray_release(rv); return re; } - rv = ray_vec_append(rv, &v_data[r]); + int64_t v_val = dl_datom_untag(v_data[r]); + rv = ray_vec_append(rv, &v_val); if (RAY_IS_ERR(rv)) { ray_release(re); return rv; } } } @@ -3384,7 +3586,7 @@ ray_t* ray_scan_eav_fn(ray_t** args, int64_t n) { if (e_data[r] != entity_id) continue; int64_t a_val = ray_read_sym(ray_data(a_col), r, a_col->type, a_col->attrs); if (a_val == attr_id) { - return ray_i64(v_data[r]); + return ray_i64(dl_datom_untag(v_data[r])); } } @@ -3455,7 +3657,7 @@ ray_t* ray_pull_fn(ray_t** args, int64_t n) { keys = ray_vec_append(keys, &a_val); if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } - ray_t* val = ray_i64(v_data[r]); + ray_t* val = ray_i64(dl_datom_untag(v_data[r])); if (RAY_IS_ERR(val)) { ray_release(keys); ray_release(vals); return val; } vals = ray_list_append(vals, val); ray_release(val); @@ -3666,24 +3868,42 @@ static ray_t* dl_set_body_pos(dl_rule_t* rule, int bidx, int pos, dl_body_set_const_typed(rule, bidx, pos, node->i64, RAY_I64); return NULL; } + if (node->type == -RAY_F64) { + int64_t bits; memcpy(&bits, &node->f64, sizeof bits); + dl_body_set_const_typed(rule, bidx, pos, bits, RAY_F64); + return NULL; + } if (node->type == -RAY_SYM) { ray_t* s = ray_sym_str(node->i64); - if (s && strcmp(ray_str_ptr(s), "_") == 0) { - /* Wildcard: create a fresh variable. Bound-check against the - * fixed var-map size — the named path (dl_var_get_or_create) - * already guards this; without the same guard here a rule with - * >256 wildcards would write past vars->syms[]. */ + bool is_wildcard = s && strcmp(ray_str_ptr(s), "_") == 0; + if (is_wildcard) { + /* Wildcard: create a fresh variable, quoted or not ('_' and + * bare _ are both the wildcard, never a variable reference). + * Bound-check against the fixed var-map size — the named path + * (dl_var_get_or_create) already guards this; without the same + * guard here a rule with >256 wildcards would write past + * vars->syms[]. */ if (vars->n >= DL_MAX_ARITY * DL_MAX_BODY) return ray_error("domain", "rule: too many variables"); int vi = vars->n++; vars->syms[vi] = -1 - vi; dl_body_set_var(rule, bidx, pos, vi); - } else { + return NULL; + } + if (node->attrs & ATTR_QUOTED) { + /* 'foo / :foo — a literal symbol constant. */ dl_body_set_const_typed(rule, bidx, pos, node->i64, RAY_SYM); + return NULL; } - return NULL; - } - if (node->type == -RAY_STR) { + /* Bare, unquoted symbol: a reference to a host-language bound + * variable (e.g. `sid` from `(set sid ...)`), not a literal. + * Fall through to the ray_eval fallback below so it resolves to + * the variable's current value instead of being (mis)treated as + * the literal symbol sharing its name — audit #1.5: this is + * exactly the kind of value that can carry a DATOM-tagged v-column + * payload, so it must reach dl_col_eq_row with the *evaluated* + * constant's real type (I64/SYM/...), not always RAY_SYM. */ + } else if (node->type == -RAY_STR) { /* Quoted string literal in body: intern as sym so it compares * equal to other sym-interned constants. Record the source type * as RAY_STR so the row-equality helper can also try a tagged- @@ -3698,8 +3918,18 @@ static ray_t* dl_set_body_pos(dl_rule_t* rule, int bidx, int pos, return val ? val : ray_error("type", "rule: cannot evaluate constant in body"); if (val->type == -RAY_I64) { dl_body_set_const_typed(rule, bidx, pos, val->i64, RAY_I64); + } else if (val->type == -RAY_F64) { + int64_t bits; memcpy(&bits, &val->f64, sizeof bits); + dl_body_set_const_typed(rule, bidx, pos, bits, RAY_F64); } else if (val->type == -RAY_SYM) { dl_body_set_const_typed(rule, bidx, pos, val->i64, RAY_SYM); + } else if (val->type == -RAY_STR) { + /* Same treatment as the literal STR branch above: intern as sym + * so `(set s "Alice")` followed by `(where (?e :name s))` agrees + * with writing the literal `(where (?e :name "Alice"))` inline — + * both end up as a RAY_STR-typed constant naming the same sym. */ + int64_t sym = ray_sym_intern(ray_str_ptr(val), ray_str_len(val)); + dl_body_set_const_typed(rule, bidx, pos, sym, RAY_STR); } else { ray_release(val); return ray_error("type", "rule: unsupported constant type in body"); @@ -3721,9 +3951,9 @@ static ray_t* dl_parse_body_clause(dl_rule_t* rule, ray_t* clause, /* -- Triple pattern: (?e :attr ?v) -- */ if (dl_is_triple_pattern(clause)) { - /* Register as 3-arity atom on "eav" relation: + /* Register as 3-arity atom on the DL_EAV_PRED relation: * position 0 = entity, 1 = attr (constant), 2 = value */ - int bidx = dl_rule_add_atom(rule, "eav", 3); + int bidx = dl_rule_add_atom(rule, DL_EAV_PRED, 3); if (bidx < 0) return ray_error("domain", "rule: too many body literals"); ray_t* err; @@ -3746,7 +3976,7 @@ static ray_t* dl_parse_body_clause(dl_rule_t* rule, ray_t* clause, if (dl_is_triple_pattern(inner)) { /* Negated triple: (not (?e :attr ?v)) */ - int bidx = dl_rule_add_neg(rule, "eav", 3); + int bidx = dl_rule_add_neg(rule, DL_EAV_PRED, 3); if (bidx < 0) return ray_error("domain", "rule: too many body literals"); ray_t* err; @@ -3994,6 +4224,10 @@ static ray_t* dl_parse_rule_from_head_and_body(dl_rule_t* out, ray_t* head, } else if (harg->type == -RAY_I64) { dl_rule_head_const_typed(out, i, harg->i64, RAY_I64); } else if (harg->type == -RAY_SYM) { + /* Unlike dl_set_body_pos (body positions), a head position + * never evaluates a bare symbol as a bound-variable reference + * -- it is always taken as the literal symbol constant here, + * quoted or not. */ dl_rule_head_const_typed(out, i, harg->i64, RAY_SYM); } else if (harg->type == -RAY_F64) { int64_t bits; @@ -4043,9 +4277,15 @@ ray_t* ray_rule_fn(ray_t** args, int64_t n) { dl_var_map_t vars; memset(&vars, 0, sizeof(vars)); dl_rule_t rule; + /* dl_parse_rule_from_head_and_body can fail before its own dl_rule_init + * runs (e.g. malformed head); zero rule up front so n_body == 0 in that + * case and dl_rule_free_exprs below is always safe. */ + memset(&rule, 0, sizeof(rule)); ray_t* perr = dl_parse_rule_from_head_and_body(&rule, args[0], &args[1], n - 1, &vars, NULL); - if (perr) return perr; + if (perr) { dl_rule_free_exprs(&rule); return perr; } + /* Success: rule's trees move into g_dl_rules, which owns them until + * ray_dl_reset_rules — no clone/free here. */ memcpy(&g_dl_rules[g_dl_n_rules++], &rule, sizeof(dl_rule_t)); return ray_bool(true); } @@ -4084,6 +4324,12 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { return ray_error("type", "query: expected (find ...) as second argument"); } + if (find_len - 1 > DL_MAX_ARITY) { + ray_release(db); + return ray_error("domain", "query: find supports at most %d variables, got %lld", + DL_MAX_ARITY, (long long)(find_len - 1)); + } + /* Collect find variable sym IDs */ int64_t find_var_syms[DL_MAX_ARITY]; int n_find_vars = 0; @@ -4154,7 +4400,7 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { /* Parse body clauses into the query rule */ for (int64_t i = 1; i < where_len; i++) { ray_t* err = dl_parse_body_clause(&qrule, where_elems[i], &vars, NULL); - if (err) { ray_release(db); return err; } + if (err) { dl_rule_free_exprs(&qrule); ray_release(db); return err; } } qrule.n_vars = vars.n; @@ -4178,13 +4424,29 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { * RUNTIME id (sym-domain Phase 2) — the EAV table may * carry FILE-domain columns. Raw-copy fast path when * the column is runtime-domain (exact no-op pre-flip). - * Mirrors the env-backed EDB conversion below. */ + * Mirrors the env-backed EDB conversion below. + * + * v column (c == 2), audit #1.5: a hand-built or + * deserialized datoms table can carry the value column as + * a genuine RAY_SYM vector rather than assert-fact's + * DATOM-tagged I64 encoding. A RAY_SYM column can only + * ever hold a symbol, never an integer, so OR-ing in + * DL_DATOM_TAG_SYM here is unambiguous — it makes these + * cells agree with assert-fact's own tagging so + * dl_col_eq_row's strict_tag path (below) matches a SYM/ + * STR literal against them instead of silently returning + * zero rows. A *legacy* I64 v column holding bare + * (untagged) sym ids is deliberately left unmatched by + * strict_tag -- that bare-integer ambiguity is exactly + * what tagging removes (see DL_DATOM_TAG_SYM above). */ ray_t* i64col = ray_vec_new(RAY_I64, nrows_db); if (i64col && !RAY_IS_ERR(i64col)) { i64col->len = nrows_db; int64_t* d = (int64_t*)ray_data(i64col); - for (int64_t r = 0; r < nrows_db; r++) - d[r] = sym_cell_runtime_id(col, r); + for (int64_t r = 0; r < nrows_db; r++) { + int64_t id = sym_cell_runtime_id(col, r); + d[r] = (c == 2) ? (DL_DATOM_TAG_SYM | id) : id; + } eav_tbl = ray_table_add_col(eav_tbl, ray_table_col_name(db, c), i64col); ray_release(i64col); } @@ -4192,7 +4454,7 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { eav_tbl = ray_table_add_col(eav_tbl, ray_table_col_name(db, c), col); } } - dl_add_edb(prog, "eav", eav_tbl, 3); + dl_add_edb(prog, DL_EAV_PRED, eav_tbl, 3); ray_release(eav_tbl); } @@ -4201,25 +4463,41 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { int64_t rlen = ray_len(rules_clause); for (int64_t i = 1; i < rlen; i++) { dl_rule_t irule; + /* dl_parse_inline_rule can fail before its own dl_rule_init runs + * (e.g. malformed head); zero irule up front so n_body == 0 in + * that case and dl_rule_free_exprs below is always safe. */ + memset(&irule, 0, sizeof(irule)); ray_t* rerr = dl_parse_inline_rule(&irule, re[i], prog); if (rerr) { + dl_rule_free_exprs(&irule); + dl_rule_free_exprs(&qrule); dl_program_free(prog); ray_release(db); return rerr; } if (dl_add_rule(prog, &irule) < 0) { + dl_rule_free_exprs(&irule); + dl_rule_free_exprs(&qrule); dl_program_free(prog); ray_release(db); return ray_error("domain", "query: too many rules"); } + dl_rule_free_exprs(&irule); } } else { for (int i = 0; i < g_dl_n_rules; i++) dl_add_rule(prog, &g_dl_rules[i]); } - /* Add the synthetic query rule */ - dl_add_rule(prog, &qrule); + /* Add the synthetic query rule. dl_add_rule deep-clones the trees into + * prog, so qrule's own trees must be freed here on every path below. */ + if (dl_add_rule(prog, &qrule) < 0) { + dl_rule_free_exprs(&qrule); + dl_program_free(prog); + ray_release(db); + return ray_error("memory", "query: cannot add query rule"); + } + dl_rule_free_exprs(&qrule); /* Auto-register env-bound EDB tables referenced from rule bodies. * @@ -4252,7 +4530,7 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { } if (!pred_name || pred_name[0] == '\0') continue; - if (strcmp(pred_name, "eav") == 0) continue; + if (strcmp(pred_name, DL_EAV_PRED) == 0) continue; if (dl_find_rel(prog, pred_name) >= 0) continue; int64_t env_sym = ray_sym_intern(pred_name, strlen(pred_name)); @@ -4308,9 +4586,24 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { * so each cell must be re-expressed as a RUNTIME id * (sym-domain Phase 2) — env tables may carry * FILE-domain columns. Raw-copy fast path when the - * column is runtime-domain (exact no-op pre-flip). */ - for (int64_t r = 0; r < nrows_env; r++) - d[r] = sym_cell_runtime_id(col, r); + * column is runtime-domain (exact no-op pre-flip). + * + * DL_DATOM_TAG_SYM (audit #1.5): tag column 2 (the v + * column) the same way the primary eav table above + * does, but ONLY when this table is registered under + * DL_EAV_PRED itself -- every other env-bound relation + * is an ordinary user predicate, never DATOM-tagged. + * The `strcmp(pred_name, DL_EAV_PRED) == 0 continue` + * a few lines up currently makes that case + * unreachable (a rule body can't yet name an + * env-bound table "eav"), but the check is kept here + * so this loop stays correct if that skip is ever + * relaxed. */ + bool tag_v = c == 2 && strcmp(pred_name, DL_EAV_PRED) == 0; + for (int64_t r = 0; r < nrows_env; r++) { + int64_t id = sym_cell_runtime_id(col, r); + d[r] = tag_v ? (DL_DATOM_TAG_SYM | id) : id; + } next_clean = ray_table_add_col(clean, ray_table_col_name(env_val, c), i64col); ray_release(i64col); } else { @@ -4341,6 +4634,22 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { } } + /* Admission: every body predicate must now resolve to a relation — + * an EDB, an env-bound table registered above, or a rule head (IDB + * created by dl_add_rule). Anything else is a typo, not "no rows". */ + for (int ri = 0; ri < prog->n_rules; ri++) { + dl_rule_t* rr = &prog->rules[ri]; + for (int bi = 0; bi < rr->n_body; bi++) { + dl_body_t* bd = &rr->body[bi]; + const char* pn = (bd->type == DL_POS || bd->type == DL_NEG) ? bd->pred + : (bd->type == DL_AGG) ? bd->agg_pred : NULL; + if (!pn || !pn[0] || dl_find_rel(prog, pn) >= 0) continue; + dl_program_free(prog); + ray_release(db); + return ray_error("domain", "query: unknown relation '%s'", pn); + } + } + /* Stratify and evaluate */ if (dl_stratify(prog) != 0) { dl_program_free(prog); @@ -4383,8 +4692,12 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { ray_t* result = ray_table_new(n_find_vars); for (int i = 0; i < n_find_vars && i < (int)ncols; i++) { ray_t* col = ray_table_get_col_idx(raw, i); - if (col) - result = ray_table_add_col(result, find_var_syms[i], col); + if (!col) continue; + ray_t* clean = dl_untag_i64_col(col); /* returns retained col when nothing is tagged */ + if (!clean || RAY_IS_ERR(clean)) { ray_release(result); dl_program_free(prog); ray_release(db); + return clean ? clean : ray_error("memory", "query: untag"); } + result = ray_table_add_col(result, find_var_syms[i], clean); + ray_release(clean); } /* Handle empty result: ensure schema is correct */ @@ -4539,5 +4852,7 @@ ray_t* ray_dl_free_fn(ray_t* x) { /* Reset global Datalog rule storage (called from ray_lang_destroy) */ void ray_dl_reset_rules(void) { + for (int i = 0; i < g_dl_n_rules; i++) + dl_rule_free_exprs(&g_dl_rules[i]); g_dl_n_rules = 0; } diff --git a/src/ops/datalog.h b/src/ops/datalog.h index 3947c581d..81cce7db8 100644 --- a/src/ops/datalog.h +++ b/src/ops/datalog.h @@ -90,6 +90,45 @@ typedef struct dl_expr { /* Variable index sentinel: constant value, not a variable */ #define DL_CONST (-1) +/* Predicate name of the built-in 3-arity entity/attribute/value relation + * that ray_query_fn registers from the `db` argument (and that the triple- + * pattern `(?e :attr ?v)` sugar compiles atoms against). This is the only + * relation whose column 2 (the v column) is ever DATOM-tagged (below) -- + * the strict_tag gates in dl_col_eq_row's callers, and the two + * dl_rule_add_atom(rule, DL_EAV_PRED, 3) triple-pattern call sites, all key + * off this one name so the coupling between "this predicate" and "this + * column may carry a DATOM tag" is explicit and in one place. */ +#define DL_EAV_PRED "eav" + +/* ===== DATOM value tag scheme (v column of a datoms table) ===== + * assert-fact stores a symbol/string value in an otherwise-plain I64 + * cell with one of these tags OR'd into the top bits so it can never + * collide with a bare integer equal to the same intern id. dl_col_eq_row + * strips the tag (via the const_type of the body literal) to compare; + * user-visible reads (pull, scan-eav, query projection) strip it via + * dl_datom_untag so callers keep seeing plain intern ids. + * + * Value-range limit: only the top 3 bits (61-63) are reserved for the tag + * and its sign guard (see dl_datom_untag below), so a *positive* I64 value + * of 2^61 or greater stored in the datoms v column -- or appearing in any + * I64 query result column that flows through dl_untag_i64_col -- has its + * top bits indistinguishable from a tag and is masked down to its low 61 + * bits on output. This is a pre-existing limit of reusing the top bits for + * tagging, not something this fix introduces further constraints on; it + * simply means the v column (and any I64 result derived from it) is not a + * safe place to store the full 63-bit positive integer range. */ +#define DL_DATOM_TAG_SYM ((int64_t)0x2000000000000000) +#define DL_DATOM_TAG_STR ((int64_t)0x4000000000000000) +#define DL_DATOM_TAG_MASK ((int64_t)0x6000000000000000) +#define DL_DATOM_PAYLOAD ((int64_t)0x1FFFFFFFFFFFFFFF) +/* A negative plain integer has every high bit set by sign extension, so it + * spuriously matches DL_DATOM_TAG_MASK; guard with v >= 0 since a genuine + * tagged cell is always non-negative (built from a small, non-negative + * intern id OR'd with a tag that never sets the sign bit) -- without this, + * untagging would corrupt ordinary negative I64 result values (e.g. from + * datalog arithmetic) by masking off their sign-extended high bits. */ +static inline int64_t dl_datom_untag(int64_t v) { return (v >= 0 && (v & DL_DATOM_TAG_MASK)) ? (v & DL_DATOM_PAYLOAD) : v; } + /* Maximum arity for any relation */ #define DL_MAX_ARITY 16 @@ -342,6 +381,28 @@ dl_expr_t* dl_expr_var(int var_idx); /* Create a binary operation expression (OP_ADD, OP_SUB, OP_MUL, OP_DIV) */ dl_expr_t* dl_expr_binop(int op, dl_expr_t* left, dl_expr_t* right); +/* ===== Expression tree ownership ===== + * + * A dl_rule_t owns the expression trees its body[] points to + * (assign_expr, cmp_lhs_expr, cmp_rhs_expr). dl_add_rule deep-clones the + * rule it is given, so the caller retains ownership of the trees it built + * and must free them itself (dl_rule_free_exprs). dl_program_free frees + * the expression trees owned by every rule in the program. The rules in + * g_dl_rules[] own their trees until ray_dl_reset_rules frees them. */ + +/* Recursively free an expression tree. NULL-safe. */ +void dl_expr_free(dl_expr_t* e); + +/* Deep-copy an expression tree. NULL -> NULL. Returns NULL on OOM. */ +dl_expr_t* dl_expr_clone(const dl_expr_t* e); + +/* Free and NULL every expression tree owned by rule->body[]. */ +void dl_rule_free_exprs(dl_rule_t* rule); + +/* Replace every expression in rule->body[] with a deep clone of itself. + * Returns 0 on success, -1 on OOM (rule is left expr-free on failure). */ +int dl_rule_clone_exprs(dl_rule_t* rule); + /* ===== Internal (used by compiler) ===== */ /* Find relation by name. Returns index or -1. */ @@ -351,11 +412,19 @@ int dl_find_rel(dl_program_t* prog, const char* name); * Creates it with the correct arity if it doesn't exist yet. */ int dl_ensure_idb(dl_program_t* prog, const char* name, int arity); +/* Which body position, if any, reads the semi-naive delta instead of + * the full relation. NULL delta = evaluate against full relations. */ +typedef struct { + int pos; /* index into rule->body[] */ + ray_t* table; /* delta table for that position (borrowed) */ +} dl_delta_t; + /* Compile one rule into a ray_graph_t for one fixpoint iteration. - * delta_pos: which body atom uses the delta relation (-1 for initial pass). + * delta: which body position (if any) reads the semi-naive delta table + * instead of the full relation; NULL means evaluate against full relations. * rule_idx: index of this rule in prog->rules (used for provenance). * Returns the output node in g that produces new head tuples. */ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, - int delta_pos, int rule_idx, ray_graph_t* g); + const dl_delta_t* delta, int rule_idx, ray_graph_t* g); #endif /* RAYFORCE_DATALOG_H */ diff --git a/src/ops/exec.c b/src/ops/exec.c index 6326424db..93b549448 100644 --- a/src/ops/exec.c +++ b/src/ops/exec.c @@ -904,9 +904,9 @@ static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, * context. Also skip null elements when building the probe * buffer so a non-null col row doesn't accidentally match the * sentinel value of a null set element. */ - bool col_has_nulls = !ray_is_atom(col) && (col->attrs & RAY_ATTR_HAS_NULLS); + bool col_has_nulls = !ray_is_atom(col) && ray_vec_may_have_nulls(col); bool col_atom_null = ray_is_atom(col) && RAY_ATOM_IS_NULL(col); - bool set_has_nulls = !ray_is_atom(set) && (set->attrs & RAY_ATTR_HAS_NULLS); + bool set_has_nulls = !ray_is_atom(set) && ray_vec_may_have_nulls(set); #define READ_I64(dst, vec, type, idx) do { \ const void* _d = ray_data(vec); \ @@ -1152,7 +1152,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 (col->attrs & RAY_ATTR_HAS_NULLS) { + } else if (ray_vec_may_have_nulls(col)) { for (int64_t i = 0; i < r->len; i++) if (ray_vec_is_null(input, i)) b[i] = 0; } @@ -1305,7 +1305,6 @@ bool ray_slice_group_probe(ray_graph_t* g, ray_op_t* root, ray_t* by_col) { * this predicate is one conjunct of several, not the whole filter. */ if (!in0 || in0->opcode == OP_FILTER) return false; if (by_col->type != RAY_SYM || ray_is_atom(by_col)) return false; - if (by_col->attrs & RAY_ATTR_HAS_NULLS) return false; ray_idx_kind_t kind = ray_index_kind(by_col); if (kind != RAY_IDX_HASH && kind != RAY_IDX_PART) return false; ray_op_t* pred = op_child(g, root, 1); @@ -2264,11 +2263,13 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } } - /* 3. Hash/part EQ: integer or SYM; re-check HAS_NULLS. + /* 3. Hash/part EQ: nonzero SYM keys remain eligible + * even when other rows are null; indexes omit null rows. * A part hit is already one contiguous physical span, so * it stays eligible at any density. */ if (cmp_op == OP_EQ && !is_float && - !(col->attrs & RAY_ATTR_HAS_NULLS)) { + (col->type == RAY_SYM ? key_i != 0 : + !ray_vec_may_have_nulls(col))) { /* SYM equality: idx_filter_decode passes the global intern id; * the hash was built over per-column domain ids. Resolve here. */ bool sym_probe_skip = false; @@ -2362,11 +2363,11 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } if (cop == OP_EQ && !eq_col && ray_index_kind(c) == RAY_IDX_HASH && - !(c->attrs & RAY_ATTR_HAS_NULLS)) { + (c->type == RAY_SYM ? ki != 0 : !ray_vec_may_have_nulls(c))) { eq_col = c; eq_key = ki; } else if (cop == OP_GE || cop == OP_GT || cop == OP_LE || cop == OP_LT) { - if (c->attrs & RAY_ATTR_HAS_NULLS) { shape_ok = false; break; } + if (ray_vec_may_have_nulls(c)) { shape_ok = false; break; } if (!rg_col) rg_col = c; else if (rg_col != c) { shape_ok = false; break; } if (cop == OP_GE) { if (ki > lo) lo = ki; } diff --git a/src/ops/expr.c b/src/ops/expr.c index 7d2b6470c..436697d4b 100644 --- a/src/ops/expr.c +++ b/src/ops/expr.c @@ -397,7 +397,7 @@ bool try_linear_sumavg_input_i64(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, * any nullable term would poison the sum with NULL_I{16,32,64} * sentinels. Refuse the fast plan and let the caller fall back * to the generic masked path. */ - if (col->attrs & RAY_ATTR_HAS_NULLS) return false; + if (ray_vec_may_have_nulls(col)) return false; out_plan->term_ptrs[i] = ray_data(col); out_plan->term_types[i] = col->type; out_plan->coeff_i64[i] = lin.coeff_i64[i]; @@ -428,7 +428,7 @@ bool try_prod_sumavg_input_f64(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, if (!ca || !cb || RAY_IS_ERR(ca) || RAY_IS_ERR(cb)) return false; if (RAY_IS_PARTED(ca->type) || ca->type == RAY_MAPCOMMON) return false; if (RAY_IS_PARTED(cb->type) || cb->type == RAY_MAPCOMMON) return false; - if ((ca->attrs & RAY_ATTR_HAS_NULLS) || (cb->attrs & RAY_ATTR_HAS_NULLS)) + if (ray_vec_may_have_nulls(ca) || ray_vec_may_have_nulls(cb)) return false; #define PROD_OK_T(t) ((t) == RAY_F64 || (t) == RAY_I64 || (t) == RAY_I32 || \ (t) == RAY_I16 || (t) == RAY_U8 || (t) == RAY_BOOL) @@ -731,11 +731,11 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { /* Determine whether any lane in this column may be null. * For parted columns the wrapper attrs may not reflect * individual segments — scan all segments. */ - bool col_nulls = (col->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool col_nulls = ray_vec_has_nulls(col); if (RAY_IS_PARTED(col->type)) { ray_t** segs = (ray_t**)ray_data(col); for (int64_t s = 0; s < col->len; s++) - if (segs[s] && (segs[s]->attrs & RAY_ATTR_HAS_NULLS)) + if (segs[s] && ray_vec_has_nulls(segs[s])) col_nulls = true; } /* Nullable SYM is out of scope: sym ids are indistinguishable @@ -2268,7 +2268,7 @@ ray_t* exec_pred_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, * the per-element walk is required since there is no per-row bitmap to * bulk-OR. */ static void propagate_nulls(ray_t* src, ray_t* dst, int64_t len) { - if (!(src->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE))) return; + if (!ray_vec_may_have_nulls(src)) return; for (int64_t i = 0; i < len; i++) { if (ray_vec_is_null(src, i)) ray_vec_set_null(dst, i, true); @@ -2291,7 +2291,7 @@ static bool scalar_is_null(ray_t* x) { /* Check if a vector might contain nulls (accounts for slices). */ static bool vec_may_have_nulls(ray_t* v) { - return (v->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE)) != 0; + return ray_vec_may_have_nulls(v); } static int8_t ew_value_base_type(ray_t* x) { @@ -3191,6 +3191,13 @@ static void binary_range(ray_op_t* op, int8_t out_type, #define RV_READ(i) (rp_f64 ? rp_f64[i] : rp_f32 ? (double)rp_f32[i] : rp_i64 ? (double)rp_i64[i] : rp_i32 ? (double)rp_i32[i] : rp_u32 ? (double)rp_u32[i] : rp_i16 ? (double)rp_i16[i] : rp_bool ? (double)rp_bool[i] : (r_scalar && (rhs->type == -RAY_F64 || rhs->type == RAY_F64 || rhs->type == -RAY_F32 || rhs->type == RAY_F32)) ? r_f64 : (double)r_i64) #define LV_READ_I64(i) (lp_i64 ? lp_i64[i] : lp_i32 ? (int64_t)lp_i32[i] : lp_u32 ? (int64_t)lp_u32[i] : lp_i16 ? (int64_t)lp_i16[i] : lp_bool ? (int64_t)lp_bool[i] : l_i64) #define RV_READ_I64(i) (rp_i64 ? rp_i64[i] : rp_i32 ? (int64_t)rp_i32[i] : rp_u32 ? (int64_t)rp_u32[i] : rp_i16 ? (int64_t)rp_i16[i] : rp_bool ? (int64_t)rp_bool[i] : r_i64) +/* Integer-output arms read integer-family operands EXACTLY (#524): the + * double readers above round every i64 past 2^53 — each TIMESTAMP, hash or + * packed key — before the integer op, so `(- D C)` on two stamp columns + * came out 64 ns off and `(> big big+1)` said false. A float operand keeps + * the truncating double read (src_is_i64_all is loop-invariant). */ +#define LV_INT(i) (src_is_i64_all ? LV_READ_I64(i) : (int64_t)LV_READ(i)) +#define RV_INT(i) (src_is_i64_all ? RV_READ_I64(i) : (int64_t)RV_READ(i)) /* Compute once: is lhs/rhs integer-family (not float)? Used by BOOL path. */ int l_is_int = !(lp_f64 || lp_f32 || (l_scalar && @@ -3298,10 +3305,10 @@ static void binary_range(ray_op_t* op, int8_t out_type, } else if (out_type == RAY_I64 || out_type == RAY_TIMESTAMP) { int64_t* odst = (int64_t*)dst; switch (op->opcode) { - case OP_ADD: for(int64_t i=0;iri?li:ri;}break; + case OP_MOD: for(int64_t i=0;iri?li:ri;}break; default: for(int64_t i=0;iopcode) { - case OP_ADD: for(int64_t i=0;iri?li:ri;}break; + case OP_MOD: for(int64_t i=0;iri?li:ri;}break; default: for(int64_t i=0;iopcode) { - case OP_ADD: for(int64_t i=0;iri?li:ri;}break; + case OP_MOD: for(int64_t i=0;iri?li:ri;}break; default: for(int64_t i=0;iopcode) { - case OP_ADD: for(int64_t i=0;iri?li:ri;}break; + case OP_MOD: for(int64_t i=0;iri?li:ri;}break; default: for(int64_t i=0;idouble * sentinel recognition. */ switch (op->opcode) { - case OP_EQ: for(int64_t i=0;iri;}break; - case OP_GE: for(int64_t i=0;i=ri;}break; + case OP_EQ: for(int64_t i=0;iri;}break; + case OP_GE: for(int64_t i=0;i=ri;}break; case OP_AND: for(int64_t i=0;i 0) ? seg_ends[seg - 1] : 0; int64_t local_row = row - seg_start; parted_copy_cells(dst, base, out_attrs, i, segs[seg], local_row, 1); - if ((segs[seg]->attrs & RAY_ATTR_HAS_NULLS) && + if (ray_vec_may_have_nulls(segs[seg]) && ray_vec_is_null(segs[seg], local_row)) ray_vec_set_null(dst_col, i, true); } @@ -182,7 +182,7 @@ static ray_t* exec_filter_parted_vec(ray_t* parted_col, ray_t* pred, if (!segs[s]) continue; int64_t seg_len = segs[s]->len; char* dst = (char*)ray_data(result); - bool seg_has_nulls = (segs[s]->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool seg_has_nulls = ray_vec_may_have_nulls(segs[s]); if (seg_has_nulls) { for (int64_t i = 0; i < seg_len; i++) { if (pred_data[pred_off + i]) { diff --git a/src/ops/fused_pred.c b/src/ops/fused_pred.c index 0768de087..11b4eb4e4 100644 --- a/src/ops/fused_pred.c +++ b/src/ops/fused_pred.c @@ -34,6 +34,7 @@ * fused_group.h (ray_fused_group_supported). */ +#include "vec/vec.h" #include "ops/fused_group.h" /* ray_fused_group_supported decl */ #include "ops/fused_pred.h" #include "table/domain.h" /* sym-domain resolution */ @@ -132,9 +133,8 @@ static int fp_atom_col_compatible(int8_t atom_type, int8_t col_type) { * and losing the fused path cost them ~70x for an identical result. */ static int fp_col_supported_op(const ray_t* col, int eq_or_ne) { if (!col) return 0; - if (col->attrs & RAY_ATTR_HAS_NULLS) - return eq_or_ne && (col->type == RAY_SYM || col->type == RAY_STR); - return 1; + if (eq_or_ne && (col->type == RAY_SYM || col->type == RAY_STR)) return 1; + return !ray_vec_has_nulls(col); } /* Strict form — no nullable column at all. Used by the shapes whose @@ -754,7 +754,7 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, int64_t nsv = ray_len(sv); int64_t out_n = 0; for (int64_t i = 0; i < nsv; i++) { - if ((sv->attrs & RAY_ATTR_HAS_NULLS) && ray_vec_is_null(sv, i)) + if (ray_vec_may_have_nulls(sv) && ray_vec_is_null(sv, i)) continue; switch (st) { case RAY_BOOL: diff --git a/src/ops/fused_topk.c b/src/ops/fused_topk.c index 10dd0778c..7ec4b17b3 100644 --- a/src/ops/fused_topk.c +++ b/src/ops/fused_topk.c @@ -336,7 +336,7 @@ ray_t* ray_fused_topk_select(ray_t* tbl, ctx.keys[i].attrs = col->attrs; ctx.keys[i].esz = ray_sym_elem_size(kt, col->attrs); ctx.keys[i].desc = sort_descs[i]; - ctx.keys[i].has_nulls = (col->attrs & RAY_ATTR_HAS_NULLS) ? 1 : 0; + ctx.keys[i].has_nulls = ray_vec_may_have_nulls(col) ? 1 : 0; ctx.keys[i].nulls_first = sort_nulls_first(sort_descs[i]); ctx.keys[i].dom_runtime = (kt == RAY_SYM && diff --git a/src/ops/group.c b/src/ops/group.c index a16f63771..4a1671e00 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -90,7 +90,7 @@ static inline double group_fp_at(const void* data, int8_t t, int64_t row) { static inline double group_pack_i64_as_f64(ray_t* col, int64_t row) { int64_t v = read_col_i64(ray_data(col), row, col->type, col->attrs); ray_t* src = (col->attrs & RAY_ATTR_SLICE) ? col->slice_parent : col; - if (src && (src->attrs & RAY_ATTR_HAS_NULLS)) { + if (src && ray_vec_may_have_nulls(src)) { int64_t sent = agg_int_null_sentinel_for(col->type); if (sent != 0 && v == sent) return (double)NAN; } @@ -103,7 +103,7 @@ static inline double group_pack_i64_as_f64(ray_t* col, int64_t row) { static inline int64_t group_pack_y_i64(ray_t* col, int64_t row) { int64_t v = read_col_i64(ray_data(col), row, col->type, col->attrs); ray_t* src = (col->attrs & RAY_ATTR_SLICE) ? col->slice_parent : col; - if (src && (src->attrs & RAY_ATTR_HAS_NULLS)) { + if (src && ray_vec_may_have_nulls(src)) { int64_t sent = agg_int_null_sentinel_for(col->type); if (sent != 0 && v == sent) return NULL_I64; } @@ -1365,7 +1365,7 @@ ray_t* distinct_radix_first_ids(ray_t* input) { /* The kernel canonicalizes every NaN to one value. The eager * hashset only does that under the HAS_NULLS gate (ungated NaNs * are pairwise-distinct there) — bail so behavior is identical. */ - if (!(input->attrs & RAY_ATTR_HAS_NULLS)) return NULL; + if (!ray_vec_may_have_nulls(input)) return NULL; break; default: return NULL; @@ -2227,7 +2227,7 @@ static ray_t* rank_per_group_buf(ray_t* src, med_par_ctx_t ctx = { .base = ray_data(src), .src_type = t, - .has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0, + .has_nulls = ray_vec_may_have_nulls(src), .use_quantile = use_quantile, .q = q, .idx_buf = idx_buf, @@ -2378,7 +2378,7 @@ static int64_t mode_scalar_group(ray_t* src, const int64_t* rows, &hdr, (size_t)cap * sizeof(mode_scalar_entry_t)); if (!ht) return -2; uint64_t mask = cap - 1; - bool has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(src); int64_t best_count = 0, best_row = -1, best_pos = INT64_MAX; for (int64_t i = 0; i < cnt; i++) { if ((i & 65535) == 0 && ray_interrupted()) { @@ -2432,7 +2432,7 @@ static int64_t mode_guid_group(ray_t* src, const int64_t* rows, if (!ht) return -2; uint64_t mask = cap - 1; const uint8_t* base = (const uint8_t*)ray_data(src); - bool has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(src); int64_t best_count = 0, best_row = -1, best_pos = INT64_MAX; for (int64_t i = 0; i < cnt; i++) { if ((i & 65535) == 0 && ray_interrupted()) { @@ -2939,7 +2939,7 @@ ray_t* ray_topk_per_group_buf(ray_t* src, topk_par_ctx_t ctx = { .base = ray_data(src), .src_type = t, - .has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0, + .has_nulls = ray_vec_may_have_nulls(src), .k = k, .desc = desc, .idx_buf = idx_buf, @@ -2990,7 +2990,7 @@ ray_t* ray_wide_minmax_per_group_buf(ray_t* src, uint16_t op, int64_t n_groups) { if (!src || RAY_IS_ERR(src) || n_groups < 0) return NULL; if (!agg_needs_row_gather(src->type, op)) return NULL; /* caller falls back */ - bool has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(src); ray_t* out = src->type == RAY_LIST ? ray_list_new(n_groups) @@ -3106,7 +3106,7 @@ ray_t* exec_reduction(ray_graph_t* g, ray_op_t* op, ray_t* input) { /* Sentinel-based per-element null detection happens inside * REDUCE_LOOP_I/F via the type-correct NULL_* constant; the * has_nulls attribute below is the vec-level fast-path gate. */ - bool has_nulls = (input->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(input); /* Selection-aware reduction: when a lazy WHERE filter has installed * g->selection on the graph and the column we're reducing matches @@ -3550,7 +3550,7 @@ bool ght_compute_layout(ght_layout_t* out, uint32_t n_keys, uint32_t n_aggs, if (vslot >= 0 && agg_vecs[a]) { ray_t* src = (agg_vecs[a]->attrs & RAY_ATTR_SLICE) ? agg_vecs[a]->slice_parent : agg_vecs[a]; - if (src && (src->attrs & RAY_ATTR_HAS_NULLS)) { + if (src && ray_vec_may_have_nulls(src)) { af2 |= GHT_AF2_NULLABLE; sent = agg_int_null_sentinel_for(agg_vecs[a]->type); out->any_agg_null = 1; @@ -3564,7 +3564,7 @@ bool ght_compute_layout(ght_layout_t* out, uint32_t n_keys, uint32_t n_aggs, agg_vecs2 && agg_vecs2[a]) { ray_t* ysrc = (agg_vecs2[a]->attrs & RAY_ATTR_SLICE) ? agg_vecs2[a]->slice_parent : agg_vecs2[a]; - if (ysrc && (ysrc->attrs & RAY_ATTR_HAS_NULLS)) { + if (ysrc && ray_vec_may_have_nulls(ysrc)) { af2 |= GHT_AF2_Y_NULLABLE; out->any_agg_null = 1; } @@ -3998,16 +3998,16 @@ static inline const int64_t* ght_null_words_at(const ght_layout_t* ly, ly->key_off[ly->n_keys]); } -/* True when key column kv (or its slice parent) carries the HAS_NULLS attr and - * so may yield a null at some row. Replaces the old per-key `1u << k` nullable +/* True when a key needs a separate null marker. SYM/STR canonical empty + * payloads already identify their null group; other types need the marker. Replaces the old per-key `1u << k` nullable * bitmask (which silently dropped keys past index 7 / was UB past 31): callers * hoist a single any_nullable summary out of the row loop, then re-test this * per key ONLY on the rare null-bearing path — correct at any key count * (unbounded-slots cut 4). */ static inline bool ray_key_may_be_null(const ray_t* kv) { - if (!kv) return false; + if (!kv || kv->type == RAY_SYM || kv->type == RAY_STR) return false; const ray_t* src = (kv->attrs & RAY_ATTR_SLICE) ? kv->slice_parent : kv; - return src && (src->attrs & RAY_ATTR_HAS_NULLS); + return src && ray_vec_may_have_nulls(src); } /* ── Inline-STR key resolution (descriptor stored in the entry/row) ── @@ -6441,6 +6441,7 @@ static void minmax_scan_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t int64_t r = match_idx ? match_idx[i] : i; \ if (!match_idx && c->rowsel && !group_rowsel_pass(c->rowsel, r)) continue; \ int64_t v = (int64_t)CAST kd[r]; \ + if (t == RAY_SYM && v == 0) continue; \ if (v < kmin) kmin = v; \ if (v > kmax) kmax = v; \ } \ @@ -7058,6 +7059,7 @@ static inline int32_t da_composite_gid(da_ctx_t* c, int64_t r) { for (uint32_t k = 0; k < c->n_keys; k++) { int64_t val = read_signed_by_esz(c->key_ptrs[k], r, c->key_esz[k], da_key_is_unsigned(c->key_types[k])); + if (c->key_types[k] == RAY_SYM && val == 0) val = c->key_mins[k]; gid += (int32_t)((val - c->key_mins[k]) * c->key_strides[k]); } return gid; @@ -7070,6 +7072,7 @@ static inline int32_t da_composite_gid_##SUFFIX(da_ctx_t* c, int64_t r) { \ int32_t gid = 0; \ for (uint32_t k = 0; k < c->n_keys; k++) { \ int64_t val = (int64_t)((const KTYPE*)c->key_ptrs[k])[r]; \ + if (c->key_types[k] == RAY_SYM && val == 0) val = c->key_mins[k]; \ gid += (int32_t)((val - c->key_mins[k]) * c->key_strides[k]); \ } \ return gid; \ @@ -7471,7 +7474,7 @@ static inline void scalar_accum_row(scalar_ctx_t* c, da_accum_t* acc, int64_t r) } } else if (op == OP_MIN) { if (is_f) { if (fv == fv && fv < acc->min_val[a].f) acc->min_val[a].f = fv; } - else if (c->agg_types[a] == RAY_SYM) { + else if (c->agg_types[a] == RAY_SYM && !int_null) { /* Lex compare for SYM; INT64_MAX = "not seen yet". */ if (acc->min_val[a].i == INT64_MAX || sym_lex_lt(ray_sym_vec_domain(c->agg_cols[a]), iv, acc->min_val[a].i)) @@ -7481,7 +7484,7 @@ static inline void scalar_accum_row(scalar_ctx_t* c, da_accum_t* acc, int64_t r) if (!is_null && nn) nn[a]++; } else if (op == OP_MAX) { if (is_f) { if (fv == fv && fv > acc->max_val[a].f) acc->max_val[a].f = fv; } - else if (c->agg_types[a] == RAY_SYM) { + else if (c->agg_types[a] == RAY_SYM && !int_null) { if (acc->max_val[a].i == INT64_MIN || sym_lex_gt(ray_sym_vec_domain(c->agg_cols[a]), iv, acc->max_val[a].i)) acc->max_val[a].i = iv; @@ -7673,7 +7676,7 @@ static inline void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64 /* NaN comparisons are always false, but make the skip * explicit. */ if (fv == fv && fv < acc->min_val[idx].f) acc->min_val[idx].f = fv; - } else if (c->agg_types[a] == RAY_SYM) { + } else if (c->agg_types[a] == RAY_SYM && !int_null) { /* Lex compare for SYM; INT64_MAX = "not seen yet". */ if (acc->min_val[idx].i == INT64_MAX || sym_lex_lt(ray_sym_vec_domain(c->agg_cols[a]), iv, acc->min_val[idx].i)) @@ -7685,7 +7688,7 @@ static inline void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64 } else if (op == OP_MAX) { if (is_f) { if (fv == fv && fv > acc->max_val[idx].f) acc->max_val[idx].f = fv; - } else if (c->agg_types[a] == RAY_SYM) { + } else if (c->agg_types[a] == RAY_SYM && !int_null) { if (acc->max_val[idx].i == INT64_MIN || sym_lex_gt(ray_sym_vec_domain(c->agg_cols[a]), iv, acc->max_val[idx].i)) acc->max_val[idx].i = iv; @@ -7726,11 +7729,13 @@ static void da_accum_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t en if (da_pf && RAY_LIKELY(i + DA_PF_DIST < end)) { \ int64_t pf_r = match_idx ? match_idx[i + DA_PF_DIST] : (i + DA_PF_DIST); \ int64_t pfk = (int64_t)KCAST kp[pf_r]; \ + if (c->key_types[0] == RAY_SYM && pfk == 0) pfk = kmin; \ __builtin_prefetch(&acc->count[(int32_t)(pfk - kmin)], 1, 1); \ if (acc->sum) __builtin_prefetch( \ &acc->sum[(size_t)(int32_t)(pfk - kmin) * n_aggs], 1, 1); \ } \ int64_t kv = (int64_t)KCAST kp[r]; \ + if (c->key_types[0] == RAY_SYM && kv == 0) kv = kmin; \ da_accum_row(c, acc, (int32_t)(kv - kmin), r); \ } \ } while (0) @@ -9464,7 +9469,7 @@ static bool sg_shape_eligible(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (!ae || ae->base.opcode != OP_SCAN) return false; ray_t* col = ray_table_get_col(tbl, ae->sym); if (!col || ray_is_atom(col)) return false; - if (col->attrs & RAY_ATTR_HAS_NULLS) return false; + if (ray_vec_has_nulls(col)) return false; if (!agg_type_admitted(aop, col->type)) return false; switch (col->type) { case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: @@ -9480,7 +9485,7 @@ static bool sg_shape_eligible(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (!ae2 || ae2->base.opcode != OP_SCAN) return false; ray_t* col2 = ray_table_get_col(tbl, ae2->sym); if (!col2 || ray_is_atom(col2)) return false; - if (col2->attrs & RAY_ATTR_HAS_NULLS) return false; + if (ray_vec_has_nulls(col2)) return false; if (!agg_type_admitted(aop, col2->type)) return false; switch (col2->type) { case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: @@ -10899,15 +10904,14 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, agg_types[a] = agg_vecs[a]->type; sc_int_null_sentinel[a] = agg_int_null_sentinel_for(agg_vecs[a]->type); /* Only flag int-null for storage types whose sentinel is - * meaningful. BOOL/U8/SYM use 0 as their default - * "sentinel" which collides with legitimate values - * (FALSE / zero byte / SYM id 0); gating those would silently - * drop real rows from SUM/MIN/MAX. F64 has its own NaN path. */ + * meaningful. BOOL/U8 are non-nullable; SYM zero is the + * canonical empty value and must be skipped by aggregates. + * F64 has its own NaN path. */ int8_t t = agg_vecs[a]->type; bool is_sentinel_typed = (t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || - t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP); - sc_int_null_has[a] = is_sentinel_typed && (agg_vecs[a]->attrs & RAY_ATTR_HAS_NULLS); - if ((agg_vecs[a]->attrs & RAY_ATTR_HAS_NULLS) && + t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_SYM); + sc_int_null_has[a] = is_sentinel_typed && ray_vec_may_have_nulls(agg_vecs[a]); + if (ray_vec_may_have_nulls(agg_vecs[a]) && (group_fp_type(agg_vecs[a]->type) || is_sentinel_typed)) sc_any_nullable = true; } else { @@ -11159,7 +11163,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, bool agg0_has_nulls = n_aggs > 0 && (sc_int_null_has[0] || (agg_vecs[0] && group_fp_type(agg_vecs[0]->type) && - (agg_vecs[0]->attrs & RAY_ATTR_HAS_NULLS))); + ray_vec_may_have_nulls(agg_vecs[0]))); if (n_aggs == 1 && !match_idx && !rowsel && agg_ptrs[0] != NULL && !agg0_has_nulls) { uint16_t op0 = ext->agg_ops[0]; int8_t t0 = agg_types[0]; @@ -11297,7 +11301,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, wscan = sm->total_pass; } } - bool hn = (agg_vecs[a]->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool hn = ray_vec_may_have_nulls(agg_vecs[a]); ray_t* atom = agg_wide_reduce(agg_vecs[a], aop, wsel, wscan, hn); if (wsel_blk) ray_release(wsel_blk); ray_t* col = agg_vecs[a]->type == RAY_LIST @@ -11452,7 +11456,7 @@ da_path:; ray_t* ysrc = (yv2->attrs & RAY_ATTR_SLICE) ? yv2->slice_parent : yv2; if (!y_fp && !y_int) da_eligible = false; /* SYM/STR/GUID/… */ - else if (!y_fp && ysrc && (ysrc->attrs & RAY_ATTR_HAS_NULLS)) + else if (!y_fp && ysrc && ray_vec_may_have_nulls(ysrc)) da_eligible = false; /* nullable int y */ } } @@ -11475,11 +11479,12 @@ da_path:; && t != RAY_BOOL && t != RAY_U8 && t != RAY_I16) { da_eligible = false; } - /* DA path cannot represent nulls — fall back to HT path. */ + /* SYM zero is a valid dense group index. Other nullable key + * types still require the hash path for their sentinels. */ if (key_vecs[k]) { ray_t* src = (key_vecs[k]->attrs & RAY_ATTR_SLICE) ? key_vecs[k]->slice_parent : key_vecs[k]; - if (src && (src->attrs & RAY_ATTR_HAS_NULLS)) + if (t != RAY_SYM && ray_vec_may_have_nulls(src)) da_eligible = false; } } @@ -11558,6 +11563,14 @@ da_path:; if (mm_mins[w] < kmin) kmin = mm_mins[w]; if (mm_maxs[w] > kmax) kmax = mm_maxs[w]; } + /* Reserve slot 0 for the canonical empty symbol without + * spanning the gap from id 0 to this column's nonempty ids. + * Runtime ids are shared across all columns, so that gap can + * dwarf the actual key range (e.g. after a wide CSV import). */ + if (key_types[k] == RAY_SYM) { + if (kmin == INT64_MAX) { kmin = 1; kmax = 0; } + kmin--; + } da_key_min[k] = kmin; /* kmax - kmin may overflow i64 when keys span full range. * Compute in uint64_t and reject if the span exceeds i64. */ @@ -11646,7 +11659,7 @@ da_path:; ray_t* ysrc = (agg_vecs2[a]->attrs & RAY_ATTR_SLICE) ? agg_vecs2[a]->slice_parent : agg_vecs2[a]; if (group_fp_type(agg_vecs2[a]->type) && - ysrc && (ysrc->attrs & RAY_ATTR_HAS_NULLS)) + ysrc && ray_vec_may_have_nulls(ysrc)) da_any_nullable = true; } if (agg_prod[a].enabled) { @@ -11664,16 +11677,14 @@ da_path:; agg_f64_mask |= ((uint64_t)1 << a); da_int_null_sentinel[a] = agg_int_null_sentinel_for(agg_vecs[a]->type); /* Only set the int-null mask bit for storage types whose - * sentinel is meaningful. BOOL/U8/SYM use 0 as their default - * "sentinel" which collides with legitimate values - * (FALSE / zero byte / SYM id 0); gating those would silently - * drop real rows from SUM/MIN/MAX. F64 has its own NaN path. */ + * sentinel is meaningful. BOOL/U8 are non-nullable; SYM + * zero is skipped by aggregates. F64 has its own NaN path. */ int8_t t = agg_vecs[a]->type; bool is_sentinel_typed = (t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || - t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP); - if (is_sentinel_typed && (agg_vecs[a]->attrs & RAY_ATTR_HAS_NULLS)) + t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_SYM); + if (is_sentinel_typed && ray_vec_may_have_nulls(agg_vecs[a])) da_int_null_mask |= ((uint64_t)1 << a); - if ((agg_vecs[a]->attrs & RAY_ATTR_HAS_NULLS) && + if (ray_vec_may_have_nulls(agg_vecs[a]) && (group_fp_type(agg_vecs[a]->type) || is_sentinel_typed)) da_any_nullable = true; } else { @@ -12114,7 +12125,8 @@ da_path:; for (uint32_t s = 0; s < n_slots; s++) { if (da_count[s] < da_keep_min) continue; int64_t offset = ((int64_t)s / da_key_stride[k]) % da_key_range[k]; - int64_t key_val = da_key_min[k] + offset; + int64_t key_val = (src_col->type == RAY_SYM && offset == 0) + ? 0 : da_key_min[k] + offset; write_col_i64(ray_data(key_col), gi, key_val, src_col->type, key_col->attrs); gi++; } @@ -12199,7 +12211,7 @@ da_path:; if (sp_eligible && key_vecs[0]) { ray_t* src = (key_vecs[0]->attrs & RAY_ATTR_SLICE) ? key_vecs[0]->slice_parent : key_vecs[0]; - if (src && (src->attrs & RAY_ATTR_HAS_NULLS)) + if (kt != RAY_SYM && ray_vec_may_have_nulls(src)) sp_eligible = false; } bool sp_need_sum = false; @@ -12215,7 +12227,7 @@ da_path:; * NULL_F64 sentinels. Fall back to slower paths that * mask nulls properly. (The multi-key radix HT at * accum_from_entry inherits the same nullable-agg gap.) */ - if (agg_vecs[a] && (agg_vecs[a]->attrs & RAY_ATTR_HAS_NULLS)) + if (agg_vecs[a] && ray_vec_may_have_nulls(agg_vecs[a])) sp_eligible = false; else sp_need_sum = true; @@ -12987,7 +12999,7 @@ ht_path:; if (agg_vecs[a]) { ray_t* src = (agg_vecs[a]->attrs & RAY_ATTR_SLICE) ? agg_vecs[a]->slice_parent : agg_vecs[a]; - if (src && (src->attrs & RAY_ATTR_HAS_NULLS)) + if (src && ray_vec_may_have_nulls(src)) v2_ok = false; } } @@ -13695,9 +13707,12 @@ v2_emit:; /* Pre-allocate agg result vectors. These VLAs scale with n_aggs * (the ≤8-agg ht_path guard is retired — 9/17/65-agg legacy shapes * reach here); ght_compute_layout has already accepted this n_aggs, - * so it is within the layout stride/slot budget. */ - agg_out_t agg_outs[n_aggs]; - ray_t* agg_cols[n_aggs]; + * so it is within the layout stride/slot budget. Sized by vla_aggs, + * not n_aggs: a table `distinct` is a grouped plan with zero + * aggregates, and a zero-length VLA is UB (#515) — the sanitized + * build aborted here. Every loop below is bounded by n_aggs. */ + agg_out_t agg_outs[vla_aggs]; + ray_t* agg_cols[vla_aggs]; for (uint32_t a = 0; a < n_aggs; a++) { uint16_t agg_op = ext->agg_ops[a]; ray_t* agg_col = agg_vecs[a]; diff --git a/src/ops/hll.c b/src/ops/hll.c index a87985c0b..5e24eb5d1 100644 --- a/src/ops/hll.c +++ b/src/ops/hll.c @@ -391,7 +391,7 @@ ray_t* ray_count_distinct_approx(ray_t* x) { .vec = x, .type = t, .attrs = x->attrs, - .has_nulls = (x->attrs & RAY_ATTR_HAS_NULLS) != 0, + .has_nulls = ray_vec_may_have_nulls(x), .shards = shards, .p = RAY_HLL_DEFAULT_P, .n_workers = nw, @@ -569,7 +569,7 @@ int ray_count_distinct_approx_pg_buf(ray_t* src, .vec = src, .type = t, .attrs = src->attrs, - .has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0, + .has_nulls = ray_vec_may_have_nulls(src), .idx_buf = idx_buf, .offsets = offsets, .counts = counts, @@ -817,7 +817,7 @@ int ray_count_distinct_approx_pg_stream(ray_t* src, .n_groups = n_groups, .type = t, .attrs = src->attrs, - .has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0, + .has_nulls = ray_vec_may_have_nulls(src), .p = p, .m = m, }; diff --git a/src/ops/idiom.c b/src/ops/idiom.c index b43944ae3..3cd4d4c1f 100644 --- a/src/ops/idiom.c +++ b/src/ops/idiom.c @@ -21,6 +21,7 @@ * SOFTWARE. */ +#include "vec/vec.h" #include "idiom.h" #include "opt.h" #include "mem/sys.h" @@ -127,14 +128,14 @@ static bool pre_no_nulls_on_asc_input(ray_graph_t* g, ray_op_t* node) { ray_t* lit = ext->literal; /* Only safe to rewrite if the literal is a vector with no nulls. */ if (!ray_is_vec(lit)) return false; - return !(lit->attrs & RAY_ATTR_HAS_NULLS); + return !ray_vec_has_nulls(lit); } if (src->opcode == OP_SCAN) { ray_t* col = scan_source_col(g, src); if (!col) return false; if (!ray_is_vec(col) && !RAY_IS_PARTED(col->type)) return false; - return !(col->attrs & RAY_ATTR_HAS_NULLS); + return !ray_vec_has_nulls(col); } return false; diff --git a/src/ops/idxop.c b/src/ops/idxop.c index e39765767..6927a52dc 100644 --- a/src/ops/idxop.c +++ b/src/ops/idxop.c @@ -31,6 +31,7 @@ #include "lang/eval.h" #include "ops/ops.h" #include "ops/rowsel.h" +#include "ops/hash.h" /* ray_hash_bytes: STR hash-index key word */ #include #include #include @@ -96,13 +97,48 @@ static uint64_t numeric_key_word(const uint8_t* base, int8_t type, int64_t i) { return (uint64_t)k; } +/* STR hash-index key word: a 64-bit hash of the bytes. Two distinct + * strings may share a word, so every STR key compare in the builder and + * the probes ALSO compares the payload (str_rows_eq / str_row_eq_bytes) + * and keeps walking on a payload mismatch — the bucket table may hold two + * groups with the same word. */ +static inline uint64_t str_key_word(const char* p, size_t l) { + return p ? ray_hash_bytes(p, l) : 0; +} + +/* Row i of `v` as the hash-index key word: numeric → numeric_key_word, + * SYM → the column-domain id (width-aware), STR → str_key_word. */ +static uint64_t hash_row_key_word(ray_t* v, const uint8_t* base, int64_t i) { + if (v->type == RAY_SYM) return (uint64_t)ray_read_sym(base, i, RAY_SYM, v->attrs); + if (v->type == RAY_STR) { + size_t l = 0; + const char* p = ray_str_vec_get(v, i, &l); + return str_key_word(p, l); + } + return numeric_key_word(base, v->type, i); +} + +static bool str_row_eq_bytes(ray_t* v, int64_t i, const char* p, size_t l) { + size_t il = 0; + const char* ip = ray_str_vec_get(v, i, &il); + if (!ip) ip = ""; + if (!p) p = ""; + return il == l && memcmp(ip, p, l) == 0; +} + +static bool str_rows_eq(ray_t* v, int64_t i, int64_t j) { + size_t jl = 0; + const char* jp = ray_str_vec_get(v, j, &jl); + return str_row_eq_bytes(v, i, jp, jl); +} + /* Returns true iff numeric vector v is non-descending. v1 scope: rejects * (returns false) if any null or NaN is present — callers turn false into a * verify error. Caller has already ensured numeric_elem_size(v->type) > 0. */ static bool vec_is_ascending(const ray_t* v) { int64_t n = v->len; if (n < 2) return true; - if (v->attrs & RAY_ATTR_HAS_NULLS) { + if (ray_vec_may_have_nulls(v)) { for (int64_t i = 0; i < n; i++) if (ray_vec_is_null((ray_t*)v, i)) return false; } @@ -177,14 +213,16 @@ static bool vec_all_distinct(const ray_t* v) { if (!slot) return false; const uint8_t* base = (const uint8_t*)ray_data((ray_t*)v); bool ok = true; + bool is_str = (v->type == RAY_STR); for (int64_t i = 0; i < n && ok; i++) { if (ray_vec_is_null((ray_t*)v, i)) continue; - uint64_t hi = numeric_key_word(base, v->type, i); + uint64_t hi = hash_row_key_word((ray_t*)v, base, i); uint64_t h = mix64(hi) & mask; for (;;) { int64_t cur = slot[h]; if (cur == 0) { slot[h] = i + 1; break; } - if (numeric_key_word(base, v->type, cur - 1) == hi) { ok = false; break; } /* dup */ + if (hash_row_key_word((ray_t*)v, base, cur - 1) == hi && + (!is_str || str_rows_eq((ray_t*)v, cur - 1, i))) { ok = false; break; } /* dup */ h = (h + 1) & mask; } } @@ -214,6 +252,71 @@ static ray_t* ray_index_alloc(ray_idx_kind_t kind, int8_t parent_type, int64_t p return idx; } +/* -------------------------------------------------------------------------- + * Table-resident key index (RAY_IDX_UKEY) + * + * A table's aux is zero-init, so unlike a vector there is nothing to snapshot + * and restore — attach is a pointer write plus the attrs bit, detach clears + * both. Refcounting rides the type-agnostic RAY_ATTR_HAS_INDEX arms of + * ray_retain_owned_refs / ray_release_owned_refs, so the index dies with the + * table and a copied table is handled by the caller (a fresh table starts + * without one). + * -------------------------------------------------------------------------- */ + +ray_t* ray_index_build_ukey(const int64_t* kci, int64_t nk, int64_t entries) { + if (nk <= 0 || nk > RAY_UKEY_MAX_COLS) return NULL; + for (int64_t k = 0; k < nk; k++) + if (kci[k] < 0 || kci[k] > INT16_MAX) return NULL; /* kci is int16 */ + uint64_t cap = 16; + while (cap < (uint64_t)entries * 2) { + if (cap > (UINT64_MAX >> 1)) return ray_error("oom", NULL); + cap <<= 1; + } + ray_t* slots = ray_vec_new(RAY_I64, (int64_t)cap); + if (!slots || RAY_IS_ERR(slots)) return slots ? slots : ray_error("oom", NULL); + slots->len = (int64_t)cap; + memset(ray_data(slots), 0, (size_t)cap * sizeof(int64_t)); + + ray_t* idx = ray_index_alloc(RAY_IDX_UKEY, RAY_TABLE, 0); + if (!idx || RAY_IS_ERR(idx)) { ray_release(slots); return idx ? idx : ray_error("oom", NULL); } + ray_index_t* ix = ray_index_payload(idx); + ix->u.ukey.slots = slots; + ix->u.ukey.mask = cap - 1; + ix->u.ukey.nrows = 0; + ix->u.ukey.n_tomb = 0; + ix->u.ukey.nk = nk; + for (int64_t k = 0; k < nk; k++) ix->u.ukey.kci[k] = (int16_t)kci[k]; + return idx; +} + +bool ray_table_ukey_attach(ray_t* tbl, ray_t* idx) { + if (!tbl || tbl->type != RAY_TABLE || !idx || RAY_IS_ERR(idx)) return false; + if (tbl->attrs & RAY_ATTR_HAS_INDEX) return false; + tbl->index = idx; + tbl->_idx_pad = NULL; + tbl->attrs |= RAY_ATTR_HAS_INDEX; + return true; +} + +ray_index_t* ray_table_ukey_get(ray_t* tbl) { + if (!tbl || tbl->type != RAY_TABLE) return NULL; + if (!(tbl->attrs & RAY_ATTR_HAS_INDEX)) return NULL; + ray_t* idx = tbl->index; + if (!idx || RAY_IS_ERR(idx) || idx->type != RAY_INDEX) return NULL; + ray_index_t* ix = ray_index_payload(idx); + return ix->kind == RAY_IDX_UKEY ? ix : NULL; +} + +void ray_table_ukey_drop(ray_t* tbl) { + if (!tbl || tbl->type != RAY_TABLE) return; + if (!(tbl->attrs & RAY_ATTR_HAS_INDEX)) return; + ray_t* idx = tbl->index; + tbl->index = NULL; + tbl->_idx_pad = NULL; + tbl->attrs &= (uint8_t)~RAY_ATTR_HAS_INDEX; + if (idx && !RAY_IS_ERR(idx)) ray_release(idx); +} + /* -------------------------------------------------------------------------- * Saved-aux retain / release * @@ -240,6 +343,10 @@ void ray_index_retain_saved(ray_index_t* ix) { void ray_index_release_payload(ray_index_t* ix) { switch ((ray_idx_kind_t)ix->kind) { + case RAY_IDX_UKEY: + if (ix->u.ukey.slots && !RAY_IS_ERR(ix->u.ukey.slots)) + ray_release(ix->u.ukey.slots); + break; case RAY_IDX_HASH: if (ix->u.hash.table && !RAY_IS_ERR(ix->u.hash.table)) ray_release(ix->u.hash.table); @@ -290,8 +397,42 @@ void ray_index_release_payload(ray_index_t* ix) { } } +int ray_index_child_blocks(const ray_index_t* ix, ray_t** out, int cap) { + ray_t* c[4] = { NULL, NULL, NULL, NULL }; + switch ((ray_idx_kind_t)ix->kind) { + case RAY_IDX_UKEY: c[0] = ix->u.ukey.slots; break; + case RAY_IDX_HASH: + c[0] = ix->u.hash.table; c[1] = ix->u.hash.gkeys; + c[2] = ix->u.hash.offs; c[3] = ix->u.hash.rows; + break; + case RAY_IDX_SORT: c[0] = ix->u.sort.perm; break; + case RAY_IDX_BLOOM: c[0] = ix->u.bloom.bits; break; + case RAY_IDX_CHUNK_ZONE: + c[0] = ix->u.chunk_zone.mins; c[1] = ix->u.chunk_zone.maxs; + c[2] = ix->u.chunk_zone.null_bits; + break; + case RAY_IDX_PART: + c[0] = ix->u.part.keys; c[1] = ix->u.part.starts; c[2] = ix->u.part.lens; + break; + case RAY_IDX_DICT: + c[0] = ix->u.dict.codes; c[1] = ix->u.dict.first_occ; + break; + case RAY_IDX_ZONE: + case RAY_IDX_NONE: + break; + } + int n = 0; + for (int i = 0; i < 4 && n < cap; i++) + if (c[i] && !RAY_IS_ERR(c[i])) out[n++] = c[i]; + return n; +} + void ray_index_retain_payload(ray_index_t* ix) { switch ((ray_idx_kind_t)ix->kind) { + case RAY_IDX_UKEY: + if (ix->u.ukey.slots && !RAY_IS_ERR(ix->u.ukey.slots)) + ray_retain(ix->u.ukey.slots); + break; case RAY_IDX_HASH: if (ix->u.hash.table && !RAY_IS_ERR(ix->u.hash.table)) ray_retain(ix->u.hash.table); @@ -794,7 +935,9 @@ ray_t* ray_index_attach_built(ray_t** vp, ray_t* idx) { return ray_error("type", "attach_built: not an index object"); bool is_dict = (ray_index_payload(idx)->kind == RAY_IDX_DICT); bool is_hash = (ray_index_payload(idx)->kind == RAY_IDX_HASH); - ray_t* v = prepare_attach_ex(vp, "index", is_dict, is_hash); /* rc=1 → ray_cow no-op */ + /* STR carries the dict and (since the vector-needle find work) the hash; + * SYM carries the hash. rc=1 → ray_cow no-op. */ + ray_t* v = prepare_attach_ex(vp, "index", is_dict || is_hash, is_hash); if (RAY_IS_ERR(v)) return v; return attach_finalize(v, idx); } @@ -823,6 +966,10 @@ ray_t* ray_index_attach_dict(ray_t** vp) { static int idx_child_slots(ray_index_t* ix, ray_t** slots[4]) { int n = 0; switch (ix->kind) { + /* RAY_IDX_UKEY is runtime-only and lives on a table, which is never + * written as a column, so it has nothing to persist. Named rather + * than left to the default so the omission reads as deliberate. */ + case RAY_IDX_UKEY: break; case RAY_IDX_HASH: slots[n++] = &ix->u.hash.table; slots[n++] = &ix->u.hash.gkeys; slots[n++] = &ix->u.hash.offs; slots[n++] = &ix->u.hash.rows; break; @@ -938,8 +1085,11 @@ ray_t* ray_index_inline_map(uint8_t* region) { * -------------------------------------------------------------------------- */ ray_t* ray_index_attach_hash(ray_t** vp) { - ray_t* v = prepare_attach_ex(vp, "hash", false, true); /* allow_sym: RAY_SYM uses domain ids */ + /* allow_str: keyed on a byte hash with payload-verified compares; + * allow_sym: RAY_SYM uses domain ids. */ + ray_t* v = prepare_attach_ex(vp, "hash", true, true); if (RAY_IS_ERR(v)) return v; + bool is_str = (v->type == RAY_STR); int64_t n = v->len; /* Build-time capacity: sized by rows for O(1) inserts. */ @@ -949,14 +1099,19 @@ ray_t* ray_index_attach_hash(ray_t** vp) { ray_t* btab_hdr = NULL; ray_t* rgid_hdr = NULL; + ray_t* gfirst_hdr = NULL; int64_t* btab = (int64_t*)scratch_alloc(&btab_hdr, (size_t)bcap * sizeof(int64_t)); int64_t* rgid = (int64_t*)scratch_alloc(&rgid_hdr, (size_t)(n > 0 ? n : 1) * sizeof(int64_t)); + /* STR: first row of each group, for the payload compare on a word hit. */ + int64_t* gfirst = is_str ? (int64_t*)scratch_alloc(&gfirst_hdr, + (size_t)(n > 0 ? n : 1) * sizeof(int64_t)) : NULL; ray_t* gkeys = ray_vec_new(RAY_I64, n > 0 ? n : 1); /* worst case: all distinct */ - if (!btab || !rgid || !gkeys || RAY_IS_ERR(gkeys)) { + if (!btab || !rgid || (is_str && !gfirst) || !gkeys || RAY_IS_ERR(gkeys)) { scratch_free(btab_hdr); scratch_free(rgid_hdr); + scratch_free(gfirst_hdr); if (gkeys && !RAY_IS_ERR(gkeys)) ray_release(gkeys); return ray_error("oom", NULL); } @@ -970,29 +1125,32 @@ ray_t* ray_index_attach_hash(ray_t** vp) { if (RAY_UNLIKELY((i & 0xFFFF) == 0 && ray_interrupted())) { scratch_free(btab_hdr); scratch_free(rgid_hdr); + scratch_free(gfirst_hdr); ray_release(gkeys); return ray_error("cancel", "interrupted"); } - if (ray_vec_is_null(v, i)) { rgid[i] = -1; continue; } /* SYM is null-free → always false */ - int64_t kw = (v->type == RAY_SYM) - ? ray_read_sym(base, i, RAY_SYM, v->attrs) /* domain id, width-aware */ - : (int64_t)numeric_key_word(base, v->type, i); + if (ray_vec_is_null(v, i)) { rgid[i] = -1; continue; } + int64_t kw = (int64_t)hash_row_key_word(v, base, i); uint64_t slot = mix64((uint64_t)kw) & bmask; for (;;) { int64_t gp1 = btab[slot]; if (gp1 == 0) { btab[slot] = n_groups + 1; gk[n_groups] = kw; + if (gfirst) gfirst[n_groups] = i; rgid[i] = n_groups; n_groups++; break; } - if (gk[gp1 - 1] == kw) { rgid[i] = gp1 - 1; break; } + /* STR: a word hit is only a group hit when the bytes agree. */ + if (gk[gp1 - 1] == kw && + (!is_str || str_rows_eq(v, gfirst[gp1 - 1], i))) { rgid[i] = gp1 - 1; break; } slot = (slot + 1) & bmask; } n_keys++; } scratch_free(btab_hdr); + scratch_free(gfirst_hdr); gkeys->len = n_groups; /* CSR slices: counting pass over rgid. offs doubles as the fill @@ -1157,6 +1315,9 @@ static ray_index_t* hash_probe_setup(ray_t* col, int64_t key, if (ix->kind != RAY_IDX_HASH) return NULL; if (ix->built_for_len != col->len) return NULL; if (!hash_key_in_range(col->type, key)) return NULL; + /* Hash builders omit null rows. A zero-symbol probe must use the scan + * path, which also handles indexes persisted before this convention. */ + if (col->type == RAY_SYM && key == 0) return NULL; /* SYM ids are valid probe keys (non-negative domain ids); all other * non-numeric types are rejected by hash_key_in_range above. */ if (col->type != RAY_SYM && numeric_elem_size(col->type) == 0) return NULL; @@ -1182,6 +1343,37 @@ static ray_index_t* hash_probe_setup(ray_t* col, int64_t key, return ix; } +/* STR twin of hash_probe_setup: the key is the needle's bytes. Walks the + * bucket table on the byte-hash word and confirms each word hit against the + * payload of the group's first row (rows[offs[gid]]) — a distinct string with + * the same word is a different group further along the chain. */ +static ray_index_t* hash_probe_setup_str(ray_t* col, const char* p, size_t l, + int64_t* gid) { + *gid = -1; + if (!col || RAY_IS_ERR(col) || !ray_is_vec(col) || col->type != RAY_STR) return NULL; + if (!(col->attrs & RAY_ATTR_HAS_INDEX) || !col->index) return NULL; + ray_index_t* ix = ray_index_payload(col->index); + if (ix->kind != RAY_IDX_HASH) return NULL; + if (ix->built_for_len != col->len) return NULL; + if (!ix->u.hash.table || !ix->u.hash.gkeys || + !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); + 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); + for (;;) { + int64_t gp1 = tbl[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; } + slot = (slot + 1) & ix->u.hash.mask; + } + return ix; +} + /* v1 routing eligibility — structural gate shared by every consult function. * Checks that col is a flat (non-parted, non-MAPCOMMON) vector carrying a * fresh index of the requested kind. Does NOT gate on HAS_NULLS: hash and @@ -1205,7 +1397,18 @@ static bool idx_fresh(ray_t* col, ray_idx_kind_t kind) { * (The pre-existing hash-eq probe keeps bare idx_fresh: its builder * skips null rows, making null-bearing probes structurally correct.) */ static bool idx_fresh_nonull(ray_t* col, ray_idx_kind_t kind) { - return idx_fresh(col, kind) && !(col->attrs & RAY_ATTR_HAS_NULLS); + if (!idx_fresh(col, kind)) return false; + if (col->type == RAY_SYM) { + ray_index_t* ix = ray_index_payload(col->index); + /* Builders already counted non-null rows. Keep admission O(1) + * instead of rescanning the column on each indexed lookup. */ + if (kind == RAY_IDX_HASH) + return ix->u.hash.rows && ix->u.hash.rows->len == col->len; + if (kind == RAY_IDX_BLOOM) return ix->u.bloom.n_keys == col->len; + if (kind == RAY_IDX_ZONE) return ix->u.zone.n_nulls == 0; + if (kind == RAY_IDX_PART) return true; /* builder rejects nulls */ + } + return !ray_vec_has_nulls(col); } /* -------------------------------------------------------------------------- @@ -1555,9 +1758,13 @@ ray_t* ray_index_in_rowsel(ray_t* col, ray_t* set_vec) { /* Gate: integer-family or SYM column with a fresh hash/part index. */ ray_idx_kind_t kind = ray_index_kind(col); if ((kind != RAY_IDX_HASH && kind != RAY_IDX_PART) || - !idx_fresh_nonull(col, kind)) return NULL; + !(col && col->type == RAY_SYM ? idx_fresh(col, kind) + : idx_fresh_nonull(col, kind))) return NULL; bool col_is_float = (col->type == RAY_F32 || col->type == RAY_F64); if (col_is_float) return NULL; + /* A STR hash index is keyed on byte hashes — the int64 probes below do + * not apply (the eval-level `in` consults it via ray_index_find_vec). */ + if (col->type == RAY_STR) return NULL; bool col_is_sym = (col->type == RAY_SYM); /* set_vec must be a non-atom vec of the matching family: SYM set for a @@ -1595,6 +1802,10 @@ ray_t* ray_index_in_rowsel(ray_t* col, ray_t* set_vec) { if (!s) continue; int64_t dom_id = ray_sym_vec_lookup(col, ray_str_ptr(s), ray_str_len(s)); + if (dom_id == 0 && kind == RAY_IDX_HASH) { + ray_release(set_hdr); + return NULL; /* null membership needs the scan path */ + } if (dom_id >= 0) set_scratch[ulen++] = dom_id; } else { @@ -1944,7 +2155,7 @@ ray_t* ray_index_range_rowsel(ray_t* col, uint16_t cmp_op, ray_t* ray_sorted_range_rowsel(ray_t* col, uint16_t cmp_op, int64_t key_i, double key_f, bool is_float) { if (!col || RAY_IS_ERR(col) || cmp_op == OP_NE) return NULL; - if (!ray_attr_is_sorted(col) || (col->attrs & RAY_ATTR_HAS_NULLS)) + if (!ray_attr_is_sorted(col) || ray_vec_may_have_nulls(col)) return NULL; bool col_is_float = (col->type == RAY_F32 || col->type == RAY_F64); @@ -2237,7 +2448,7 @@ ray_t* ray_index_attach_part(ray_t** vp) { if (v->type != RAY_SYM && !vec_is_ascending(v)) return ray_error("domain", "parted: column is not laid out as ascending value-blocks"); - if (v->type == RAY_SYM && (v->attrs & RAY_ATTR_HAS_NULLS)) { + if (v->type == RAY_SYM && ray_vec_may_have_nulls(v)) { for (int64_t i = 0; i < n; i++) if (ray_vec_is_null(v, i)) return ray_error("domain", "parted: column contains nulls"); @@ -2359,7 +2570,11 @@ ray_t* ray_index_drop(ray_t** vp) { /* After ray_cow, *vp may be a freshly copied block. In ray_alloc_copy, * the index pointer was retained by ray_retain_owned_refs (via the * RAY_ATTR_HAS_INDEX branch we add in heap.c), so v->index here is - * still the live, owned index ray_t. */ + * still the live, owned index ray_t — EXCEPT for a table, whose key map + * ray_alloc_copy deliberately does not carry to the copy. The copy has + * no index left to detach, which is the state this function exists to + * reach, so it is already done. */ + if (!(v->attrs & RAY_ATTR_HAS_INDEX) || !v->index) return v; ray_t* idx = v->index; ray_index_t* ix = ray_index_payload(idx); @@ -2445,6 +2660,16 @@ ray_t* ray_index_info(ray_t* v) { if (RAY_IS_ERR(r)) goto fail; switch ((ray_idx_kind_t)ix->kind) { + case RAY_IDX_UKEY: + r = dict_append_sym_i64(&keys, &vals, "n_keys", ix->u.ukey.nrows); + if (RAY_IS_ERR(r)) goto fail; + r = dict_append_sym_i64(&keys, &vals, "capacity", (int64_t)(ix->u.ukey.mask + 1)); + if (RAY_IS_ERR(r)) goto fail; + r = dict_append_sym_i64(&keys, &vals, "n_key_cols", ix->u.ukey.nk); + if (RAY_IS_ERR(r)) goto fail; + r = dict_append_sym_i64(&keys, &vals, "n_tombstones", ix->u.ukey.n_tomb); + if (RAY_IS_ERR(r)) goto fail; + break; case RAY_IDX_ZONE: if (ix->parent_type == RAY_F32 || ix->parent_type == RAY_F64) { int64_t kmin = ray_sym_intern("min", 3); @@ -2566,8 +2791,8 @@ static ray_t* attr_set_unique(ray_t* v) { if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("type", "attr: null"); if (!ray_is_vec(v)) return ray_error("type", "unique: attribute applies to vectors only"); - if (numeric_elem_size(v->type) == 0) - return ray_error("nyi", "unique: only numeric vectors supported in v1 (type %d)", (int)v->type); + if (numeric_elem_size(v->type) == 0 && v->type != RAY_SYM && v->type != RAY_STR) + return ray_error("nyi", "unique: only numeric/sym/str vectors supported (type %d)", (int)v->type); if (v->attrs & RAY_ATTR_SLICE) return ray_error("type", "unique: cannot attribute a slice; materialize first"); if (!vec_all_distinct(v)) @@ -2725,9 +2950,12 @@ int64_t ray_index_find_row(ray_t* col, int64_t key) { if (!col || RAY_IS_ERR(col)) return -2; int8_t t = col->type; if (t == RAY_F32 || t == RAY_F64) return -2; + if (t == RAY_STR) return -2; /* byte-keyed: see ray_index_find_atom */ - /* idx_fresh_nonull: freshness + kind check + null-bearing gate. */ - if (!idx_fresh_nonull(col, RAY_IDX_HASH)) return -2; + /* Nonzero symbol equality is safe even when other rows are null. */ + if (t == RAY_SYM) { + if (key == 0 || !idx_fresh(col, RAY_IDX_HASH)) return -2; + } else if (!idx_fresh_nonull(col, RAY_IDX_HASH)) return -2; /* Out-of-range key cannot equal any stored value of this type. */ if (!hash_key_in_range(t, key)) return -1; @@ -2755,7 +2983,7 @@ int64_t ray_index_sym_slices(ray_t* col, ray_t* keys, if (col->type != RAY_SYM) return -1; ray_idx_kind_t kind = ray_index_kind(col); if ((kind != RAY_IDX_HASH && kind != RAY_IDX_PART) || - !idx_fresh_nonull(col, kind)) return -1; + !idx_fresh(col, kind)) return -1; bool atom = (keys->type == -RAY_SYM); int64_t nkeys; @@ -2774,6 +3002,7 @@ int64_t ray_index_sym_slices(ray_t* col, ray_t* keys, ray_t* str = atom ? ray_sym_str(keys->i64) : ray_sym_vec_cell(keys, i); if (!str) continue; int64_t dom = ray_sym_vec_lookup(col, ray_str_ptr(str), ray_str_len(str)); + if (dom == 0 && kind == RAY_IDX_HASH) { ray_free(dhdr); return -1; } if (dom >= 0) doms[nd++] = dom; } if (nd == 0) { ray_free(dhdr); return 0; } @@ -2838,6 +3067,9 @@ int ray_index_hash_group(ray_t* col, int64_t key, *rows_out = NULL; *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 + * "out of range" below would wrongly read as provably absent. */ + if (col->type == RAY_STR) return -1; int64_t gid = -1; ray_index_t* ix = hash_probe_setup(col, key, &gid); if (!ix) { @@ -2852,3 +3084,225 @@ int ray_index_hash_group(ray_t* col, int64_t key, *n_out = of[gid + 1] - of[gid]; return 1; } + +/* -------------------------------------------------------------------------- + * Hash-index find for one atom / a vector of needles (the eval-level `find`, + * `in` and dict lookup) and the append carry. Keyed per column type: + * integer family → value (ray_index_find_row), SYM → the needle re-expressed + * in the COLUMN's domain, STR → the needle's bytes. + * -------------------------------------------------------------------------- */ + +/* Integer-family atom → int64 key. Returns false for any other atom kind + * (float and cross-family needles keep the scan's promotion semantics). */ +static bool int_atom_key(const ray_t* a, int64_t* k) { + switch (a->type) { + case -RAY_I64: + case -RAY_TIMESTAMP: *k = a->i64; return true; + case -RAY_I32: + case -RAY_DATE: + case -RAY_TIME: *k = (int64_t)a->i32; return true; + case -RAY_I16: *k = (int64_t)a->i16; return true; + case -RAY_BOOL: + case -RAY_U8: *k = (int64_t)a->b8; return true; + default: return false; + } +} + +/* A runtime-domain symbol id → this column's domain id, or -1 when the + * column's domain does not hold the symbol (provably absent). */ +static int64_t sym_id_in_col_domain(ray_t* col, int64_t runtime_id) { + if (ray_sym_vec_domain(col) == ray_sym_runtime_domain()) return runtime_id; + ray_t* s = ray_sym_str(runtime_id); + if (!s) return -1; + return ray_sym_vec_lookup(col, ray_str_ptr(s), ray_str_len(s)); +} + +int64_t ray_index_find_atom(ray_t* col, ray_t* a) { + if (!col || RAY_IS_ERR(col) || !a || RAY_IS_ERR(a)) return -2; + if (!ray_is_atom(a) || RAY_ATOM_IS_NULL(a)) return -2; + /* SYM mirrors ray_index_find_row: a nonzero symbol probe is sound even + * when other rows are null, so only freshness is required there. */ + if (col->type == RAY_SYM ? !idx_fresh(col, RAY_IDX_HASH) + : !idx_fresh_nonull(col, RAY_IDX_HASH)) return -2; + switch (col->type) { + case RAY_SYM: { + if (a->type != -RAY_SYM) return -2; + int64_t id = sym_id_in_col_domain(col, a->i64); + if (id < 0) return -1; + return ray_index_find_row(col, id); /* id 0 (SYM null) → -2 */ + } + case RAY_STR: { + if (a->type != -RAY_STR) return -2; + int64_t gid = -1; + 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]]; + } + default: { + int64_t k = 0; + if (!int_atom_key(a, &k)) return -2; + return ray_index_find_row(col, k); + } + } +} + +int ray_index_find_vec(ray_t* col, ray_t* nd, int64_t* out, bool* any_miss) { + if (!col || RAY_IS_ERR(col) || !nd || RAY_IS_ERR(nd) || !out) return 0; + if (!ray_is_vec(nd) || ray_is_atom(nd)) return 0; + if (col->type == RAY_SYM ? !idx_fresh(col, RAY_IDX_HASH) + : !idx_fresh_nonull(col, RAY_IDX_HASH)) return 0; + int64_t m = nd->len; + bool miss = false; + const uint8_t* nb = (const uint8_t*)ray_data(nd); + bool nd_nulls = (nd->attrs & RAY_ATTR_HAS_NULLS) != 0; + + if (col->type == RAY_SYM) { + if (nd->type != RAY_SYM) return 0; + bool same_dom = (ray_sym_vec_domain(col) == ray_sym_vec_domain(nd)); + for (int64_t i = 0; i < m; i++) { + int64_t id; + if (same_dom) { + id = ray_read_sym(nb, i, RAY_SYM, nd->attrs); + } else { + ray_t* s = ray_sym_vec_cell(nd, i); + id = s ? ray_sym_vec_lookup(col, ray_str_ptr(s), ray_str_len(s)) : -1; + } + /* id 0 is the SYM null: the scan / hashset own null equality. */ + int64_t r = (id < 0) ? -1 : ray_index_find_row(col, id); + if (r == -2) return 0; + if (r < 0) { out[i] = NULL_I64; miss = true; } else out[i] = r; + } + } else if (col->type == RAY_STR) { + if (nd->type != RAY_STR) return 0; + for (int64_t i = 0; i < m; i++) { + if (nd_nulls && ray_vec_is_null(nd, i)) { out[i] = NULL_I64; miss = true; continue; } + size_t l = 0; + const char* p = ray_str_vec_get(nd, i, &l); + int64_t gid = -1; + 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]]; + } + } else { + /* Integer-family column and needles only: float equality (NaN, -0) + * and cross-family promotion belong to the scan / hashset paths. */ + if (col->type == RAY_F32 || col->type == RAY_F64) return 0; + if (nd->type == RAY_F32 || nd->type == RAY_F64 || numeric_elem_size(nd->type) == 0) return 0; + for (int64_t i = 0; i < m; i++) { + if (nd_nulls && ray_vec_is_null(nd, i)) { out[i] = NULL_I64; miss = true; continue; } + int64_t r = ray_index_find_row(col, set_vec_read_i64(nb, nd->type, i)); + if (r == -2) return 0; + if (r < 0) { out[i] = NULL_I64; miss = true; } else out[i] = r; + } + } + if (any_miss) *any_miss = miss; + return 1; +} + +/* Carry `src`'s hash index onto `dst`, a fresh vector holding src's rows + * followed by appended rows. Rebuilds nothing over the old rows: the group + * tables are copied and each appended row is probed once and added as a new + * single-row group. An appended row that repeats a key is left alone — the + * CSR row slices would need re-laying (O(n), the re-attach cost the carry + * exists to avoid) and a `unique` marker would stop being true — so dst + * simply stays unindexed, as every concat result did before. */ +void ray_index_carry_append(ray_t* src, ray_t* dst) { + if (!src || RAY_IS_ERR(src) || !dst || RAY_IS_ERR(dst)) return; + if (!ray_is_vec(dst) || dst->type != src->type || dst->len < src->len) return; + if (dst->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE | RAY_ATTR_HAS_INDEX)) return; + if (!idx_fresh_nonull(src, RAY_IDX_HASH)) return; + int8_t t = src->type; + if (t == RAY_F32 || t == RAY_F64) return; + if (t == RAY_SYM && ray_sym_vec_domain(src) != ray_sym_vec_domain(dst)) return; + ray_index_t* sx = ray_index_payload(src->index); + if (!sx->u.hash.table || !sx->u.hash.gkeys || !sx->u.hash.offs || !sx->u.hash.rows) return; + + int64_t n0 = src->len, n1 = dst->len, add = n1 - n0; + int64_t og = sx->u.hash.n_groups, ok = sx->u.hash.n_keys; + if (add > INT64_MAX - og || add > INT64_MAX - ok) return; /* no signed overflow below */ + bool is_str = (t == RAY_STR); + + 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); + 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); + 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); + 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); + 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)); + 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)); + } else { + memset(tbl, 0, (size_t)cap * sizeof(int64_t)); + 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; + } + } + + /* Appended rows: probe with equality; a hit means a repeated key. */ + const uint8_t* base = (const uint8_t*)ray_data(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; + for (;;) { + int64_t gp1 = tbl[slot]; + if (gp1 == 0) break; + if (gk[gp1 - 1] == kw && + (!is_str || str_rows_eq(dst, rw[of[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; + gk[ng] = kw; + rw[nk] = r; + of[ng + 1] = nk + 1; + ng++; nk++; + } + gkeys->len = ng; offs->len = ng + 1; rows->len = nk; table->len = (int64_t)cap; + + ray_t* idx = ray_index_alloc(RAY_IDX_HASH, t, n1); + if (!idx || RAY_IS_ERR(idx)) { + ray_release(gkeys); ray_release(offs); ray_release(rows); ray_release(table); + return; + } + ray_index_t* ix = ray_index_payload(idx); + ix->u.hash.table = table; + ix->u.hash.gkeys = gkeys; + ix->u.hash.offs = offs; + ix->u.hash.rows = rows; + ix->u.hash.mask = mask; + ix->u.hash.n_keys = nk; + ix->u.hash.n_groups = ng; + /* Every appended key is new, so `unique` stays true and a single-row + * group is trivially ordered by any column: the markers carry over. */ + ix->u.hash.order_sym = sx->u.hash.order_sym; + ix->markers = sx->markers; + attach_finalize(dst, idx); +} diff --git a/src/ops/idxop.h b/src/ops/idxop.h index 973b31976..2f1cc8361 100644 --- a/src/ops/idxop.h +++ b/src/ops/idxop.h @@ -48,6 +48,11 @@ #include #include "mem/heap.h" /* RAY_ATTR_HAS_INDEX */ +/* Maximum key columns a RAY_IDX_UKEY map covers. Chosen so the arm fits + * the existing union (see the static assert below); a wider key simply gets + * no index and falls back to the per-call build. */ +#define RAY_UKEY_MAX_COLS 8 + /* Index kinds. Stored in ray_index_t.kind. */ typedef enum { RAY_IDX_NONE = 0, @@ -73,6 +78,12 @@ typedef enum { * permitted on RAY_STR (it stores codes alongside the descriptors, leaving * the column's own representation untouched). */ RAY_IDX_DICT = 7, + /* Key-tuple -> row map for keyed upsert. RUNTIME-ONLY and attached to + * the RAY_TABLE object rather than to a column, because the key spans + * several columns. Never persisted: serde masks attrs down to + * HAS_NULLS and col_save strips HAS_INDEX, so it cannot reach a file. + * See the ukey arm of ray_index_t.u below. */ + RAY_IDX_UKEY = 8, } ray_idx_kind_t; /* Marker bits stored in ray_index_t.markers (block-resident attributes @@ -172,9 +183,43 @@ typedef struct { ray_t* first_occ; /* RAY_I32 vec, n_distinct entries: first-occ row */ int64_t n_distinct; } dict; + struct { /* RAY_IDX_UKEY */ + /* Open addressing over the whole key tuple: slot = row + 1, + * 0 = empty. Rows are entered in row order, so a probe from + * the hash slot meets duplicates lowest-row first — the row + * the linear scan would have picked. + * + * `nrows` is the table row count this map describes. Any + * mutation that changes the row count leaves it behind and the + * map is rebuilt; a rewrite of a key cell that keeps the count + * must drop the index explicitly (upsert itself never rewrites + * key cells — a matched row updates non-key columns only). */ + ray_t* slots; /* RAY_I64 vec, mask+1 entries */ + uint64_t mask; /* capacity - 1 (capacity is a power of two) */ + int64_t nrows; + /* Slots vacated by a deleted row. They are not free: clearing a + * slot in the middle of a probe chain would orphan whatever was + * displaced past it, so a deleted entry becomes UKEY_SLOT_TOMB and + * probing walks over it. Counted because a tombstone occupies a + * slot without being a row, and a capacity test that ignored them + * would let the array fill completely — at which point the + * free-slot scan in upsert_map_put would not terminate. */ + int64_t n_tomb; + int64_t nk; /* number of key columns */ + /* Column positions. int16 keeps this arm inside the hash arm's + * 64 bytes now that n_tomb shares it; a table with more than + * INT16_MAX columns simply gets no map. */ + int16_t kci[RAY_UKEY_MAX_COLS]; + } ukey; } u; } ray_index_t; +/* The ukey arm is sized to land exactly on the hash arm's 64 bytes so + * ray_index_t does not grow: it is stored inline in persisted column files, + * and a larger payload would change that on-disk layout for every kind. */ +_Static_assert(sizeof(((ray_index_t*)0)->u.ukey) <= sizeof(((ray_index_t*)0)->u.hash), + "RAY_IDX_UKEY payload must not grow ray_index_t"); + /* On-disk index persistence stores the RAY_INDEX object and its child vecs as * contiguous 32-byte-aligned ray_t blocks mmap'd in place (no serialization). * For the trailing child blocks to stay 32-aligned, the index payload must be a @@ -243,6 +288,28 @@ ray_t* ray_index_inline_map(uint8_t* region); * pre-attach aux state byte-for-byte. Returns *vp. */ ray_t* ray_index_drop(ray_t** vp); +/* ===== Table-resident key index (RAY_IDX_UKEY) ===== + * Attached to a RAY_TABLE, not to a vector, so the generic attach path does + * not apply: a table's aux is zero-init, there is nothing to snapshot and + * restore. Retain/release ride the type-agnostic RAY_ATTR_HAS_INDEX arms in + * heap.c, so the index dies with the table. */ + +/* Build a standalone RAY_IDX_UKEY sized for `entries` rows (caller attaches + * or releases). The slot vector is allocated zeroed. */ +ray_t* ray_index_build_ukey(const int64_t* kci, int64_t nk, int64_t entries); + +/* Attach `idx` to `tbl`, taking ownership of the caller's reference. + * Returns false (and keeps the caller's reference) if `tbl` already carries + * an index — the caller drops first. */ +bool ray_table_ukey_attach(ray_t* tbl, ray_t* idx); + +/* The attached ukey payload, or NULL when the table carries no index or one + * of another kind. */ +ray_index_t* ray_table_ukey_get(ray_t* tbl); + +/* Detach and release any index on `tbl`. Safe on a table with none. */ +void ray_table_ukey_drop(ray_t* tbl); + /* ===== Introspection ===== */ static inline bool ray_index_has(const ray_t* v) { @@ -369,6 +436,35 @@ ray_t* ray_index_in_rowsel(ray_t* col, ray_t* set_vec); * scan correctly surfaces null-equality searches. */ int64_t ray_index_find_row(ray_t* col, int64_t key); +/* ===== Hash-index find: one atom / a vector of needles ===== + * + * ray_index_find_atom: like ray_index_find_row but keyed by an ATOM, so it + * also serves SYM columns (the symbol re-expressed in the column's domain) + * and STR columns (the bytes). Same contract: >= 0 first row, -1 provably + * absent, -2 not eligible (no fresh null-free hash index, null / float / + * cross-family needle) — caller falls back to the scan. + * + * ray_index_find_vec: one probe per needle of the typed vector `needles` + * into `out[needles->len]` (first matching row, NULL_I64 on a miss; a null + * needle misses — the index is only consulted on null-free columns). + * Returns 1 when handled, 0 when not eligible (out is then unspecified and + * the caller builds its own hash). Integer-family needles for an + * integer-family column, SYM for SYM (any domain), STR for STR. */ +int64_t ray_index_find_atom(ray_t* col, ray_t* atom); +int ray_index_find_vec(ray_t* col, ray_t* needles, int64_t* out, bool* any_miss); + +/* ===== Hash-index carry across an append ===== + * + * `dst` is a fresh (rc=1, unsliced, unindexed, null-free) vector whose first + * src->len rows are src's rows and whose tail is appended rows. When src + * carries a fresh null-free hash index and every appended row is a NEW key, + * dst gets an equivalent index in O(groups + appended) without re-hashing the + * old rows; markers (`unique`) and the within-group order symbol carry over. + * A repeated key, a float column, a SYM domain change or OOM leave dst + * unindexed (the caller re-attaches if it wants one). Best-effort: never + * fails the append. */ +void ray_index_carry_append(ray_t* src, ray_t* dst); + /* ===== Hash-index group slice (CSR accessor) ===== * * Resolve `key` to its group's contiguous ascending row-id slice. @@ -473,6 +569,12 @@ void ray_index_retain_saved(ray_index_t* ix); /* Release per-kind payload children (keys/table/perm/bits...). */ void ray_index_release_payload(ray_index_t* ix); +/* The payload child blocks of an index (the same set retain/release walk), + * written to out[0..cap) — returns the count (at most 4). Footprint + * accounting (ray_shallow_bytes / ray_retained_bytes) sums them; a + * RAY_MARK_MMAP index's children live inside the column's mapping and are + * charged there, so callers skip them. */ +int ray_index_child_blocks(const ray_index_t* ix, ray_t** out, int cap); /* Retain per-kind payload children. */ void ray_index_retain_payload(ray_index_t* ix); diff --git a/src/ops/internal.h b/src/ops/internal.h index e49c017c5..108371e0e 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -287,7 +287,7 @@ static inline void col_propagate_str_pool_parted(ray_t* dst, ray_t** segs, int64 static inline void col_propagate_nulls_gather(ray_t* dst, const ray_t* src, const int64_t* indices, int64_t count) { - bool src_has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool src_has_nulls = ray_vec_may_have_nulls(src); for (int64_t r = 0; r < count; r++) { if (indices[r] < 0 || (src_has_nulls && ray_vec_is_null((ray_t*)src, indices[r]))) @@ -300,7 +300,7 @@ static inline void col_propagate_nulls_gather(ray_t* dst, const ray_t* src, static inline void col_propagate_nulls_range(ray_t* dst, int64_t dst_off, const ray_t* src, int64_t src_off, int64_t count) { - if (!(src->attrs & RAY_ATTR_HAS_NULLS)) return; + if (!ray_vec_may_have_nulls(src)) return; for (int64_t i = 0; i < count; i++) { if (ray_vec_is_null((ray_t*)src, src_off + i)) ray_vec_set_null(dst, dst_off + i, true); @@ -312,7 +312,7 @@ static inline void col_propagate_nulls_range(ray_t* dst, int64_t dst_off, static inline void col_propagate_nulls_filter(ray_t* dst, const ray_t* src, const uint8_t* mask, int64_t src_len) { - if (!(src->attrs & RAY_ATTR_HAS_NULLS)) return; + if (!ray_vec_may_have_nulls(src)) return; int64_t out = 0; for (int64_t i = 0; i < src_len; i++) { if (mask[i]) { @@ -327,7 +327,7 @@ static inline void col_propagate_nulls_filter(ray_t* dst, const ray_t* src, static inline ray_t* parted_str_append_elem(ray_t* out, ray_t* seg, int64_t local_idx, const char* pool_base) { - if ((seg->attrs & RAY_ATTR_HAS_NULLS) && ray_vec_is_null(seg, local_idx)) { + if (ray_vec_may_have_nulls(seg) && ray_vec_is_null(seg, local_idx)) { out = ray_str_vec_append(out, "", 0); if (!RAY_IS_ERR(out)) ray_vec_set_null(out, out->len - 1, true); diff --git a/src/ops/join.c b/src/ops/join.c index e73cedf59..bc8e744c0 100644 --- a/src/ops/join.c +++ b/src/ops/join.c @@ -49,7 +49,7 @@ static int join_store_key_cell(ray_t* dst, int64_t dst_row, ray_t* src, int64_t src_row) { if (!dst || !src || dst_row < 0 || src_row < 0) return -1; - if ((src->attrs & RAY_ATTR_HAS_NULLS) && ray_vec_is_null(src, src_row)) { + if (ray_vec_may_have_nulls(src) && ray_vec_is_null(src, src_row)) { ray_vec_set_null(dst, dst_row, true); return 0; } @@ -1205,7 +1205,7 @@ static ray_t* exec_join_flat(ray_graph_t* g, ray_op_t* op, ray_t* left_table, ra { bool any_nullable = false; for (uint32_t k = 0; k < n_keys && !any_nullable; k++) - if (build_keys[k] && (build_keys[k]->attrs & RAY_ATTR_HAS_NULLS)) + if (build_keys[k] && ray_vec_may_have_nulls(build_keys[k])) any_nullable = true; if (any_nullable) { int64_t null_rows = 0; @@ -3506,17 +3506,17 @@ static ray_t* exec_window_join_flat(ray_graph_t* g, ray_op_t* op, } if (left_n > 0) memset(lt_null, 0, (size_t)left_n); if (right_n > 0) memset(rt_null, 0, (size_t)right_n); - if (lt_time_vec->attrs & RAY_ATTR_HAS_NULLS) + if (ray_vec_may_have_nulls(lt_time_vec)) for (int64_t i = 0; i < left_n; i++) if (ray_vec_is_null(lt_time_vec, i)) lt_null[i] = 1; - if (rt_time_vec->attrs & RAY_ATTR_HAS_NULLS) + if (ray_vec_may_have_nulls(rt_time_vec)) for (int64_t i = 0; i < right_n; i++) if (ray_vec_is_null(rt_time_vec, i)) rt_null[i] = 1; for (uint32_t k = 0; k < n_eq; k++) { - if (lt_eq[k]->attrs & RAY_ATTR_HAS_NULLS) + if (ray_vec_may_have_nulls(lt_eq[k])) for (int64_t i = 0; i < left_n; i++) if (ray_vec_is_null(lt_eq[k], i)) lt_null[i] = 1; - if (rt_eq[k]->attrs & RAY_ATTR_HAS_NULLS) + if (ray_vec_may_have_nulls(rt_eq[k])) for (int64_t i = 0; i < right_n; i++) if (ray_vec_is_null(rt_eq[k], i)) rt_null[i] = 1; } @@ -3550,9 +3550,9 @@ static ray_t* exec_window_join_flat(ray_graph_t* g, ray_op_t* op, * key answers groups with no right pass at all). Falls back to the * sort-merge when the per-group right-time monotonicity precondition * fails. */ - bool rt_no_nulls = !(rt_time_vec->attrs & RAY_ATTR_HAS_NULLS); + bool rt_no_nulls = !ray_vec_may_have_nulls(rt_time_vec); for (uint32_t k = 0; k < n_eq && rt_no_nulls; k++) - if (rt_eq[k]->attrs & RAY_ATTR_HAS_NULLS) rt_no_nulls = false; + if (ray_vec_may_have_nulls(rt_eq[k])) rt_no_nulls = false; if (asof_hash_group_match(n_eq, lt_eq, rt_eq, eq_xlut, eq_xn, lt_time, rt_time, lt_null, rt_null, left_n, right_n, @@ -3603,14 +3603,14 @@ static ray_t* exec_window_join_flat(ray_graph_t* g, ray_op_t* op, bool l_presorted = !eq_xdomain && ((n_eq == 0 && ray_attr_is_sorted(lt_time_vec)) || (n_eq == 1 - && !(lt_time_vec->attrs & RAY_ATTR_HAS_NULLS) + && !ray_vec_may_have_nulls(lt_time_vec) && ray_index_kind(lt_eq[0]) == RAY_IDX_PART /* reject a stale part index (parent length changed since build) */ && ray_index_payload(lt_eq[0]->index)->built_for_len == lt_eq[0]->len && asof_time_sorted_within_parts(lt_eq[0], lt_time))); bool r_presorted = (n_eq == 0 && ray_attr_is_sorted(rt_time_vec)) || (n_eq == 1 - && !(rt_time_vec->attrs & RAY_ATTR_HAS_NULLS) + && !ray_vec_may_have_nulls(rt_time_vec) && ray_index_kind(rt_eq[0]) == RAY_IDX_PART /* reject a stale part index (parent length changed since build) */ && ray_index_payload(rt_eq[0]->index)->built_for_len == rt_eq[0]->len diff --git a/src/ops/opt.c b/src/ops/opt.c index 208416c9c..a7fec81b6 100644 --- a/src/ops/opt.c +++ b/src/ops/opt.c @@ -25,6 +25,7 @@ #define _GNU_SOURCE #endif +#include "vec/vec.h" #include "opt.h" #include "idiom.h" #include "core/profile.h" @@ -2054,7 +2055,7 @@ static void pass_partition_pruning(ray_graph_t* g, ray_op_t* root) { /* Read set elements — skip nulls in the literal so a null * sentinel can never match a partition key. */ int64_t next = 0; - bool set_has_nulls = (lit->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool set_has_nulls = ray_vec_may_have_nulls(lit); for (int64_t i = 0; i < set_len; i++) { if (set_has_nulls && ray_vec_is_null(lit, i)) continue; if (narrow32) { diff --git a/src/ops/pivot.c b/src/ops/pivot.c index 8a2b5d0a5..699f33f90 100644 --- a/src/ops/pivot.c +++ b/src/ops/pivot.c @@ -840,8 +840,8 @@ static ray_t* exec_if_eager(ray_graph_t* g, ray_op_t* op) { if (!then_scalar && !else_scalar && then_v->type == RAY_STR && else_v->type == RAY_STR && len <= then_v->len && len <= else_v->len && - !(then_v->attrs & RAY_ATTR_HAS_NULLS) && - !(else_v->attrs & RAY_ATTR_HAS_NULLS)) { + !ray_vec_may_have_nulls(then_v) && + !ray_vec_may_have_nulls(else_v)) { ray_t* then_pool = str_vec_pool_obj(then_v); ray_t* else_pool = str_vec_pool_obj(else_v); if (then_pool == else_pool || !then_pool || !else_pool) { diff --git a/src/ops/query.c b/src/ops/query.c index 4934d118c..81b511640 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -258,7 +258,7 @@ static bool query_key_reader_read(query_key_reader_t* r, int64_t row, *out = 0; if (!RAY_IS_PARTED(r->col->type) && r->col->type != RAY_MAPCOMMON) { - *is_null = (r->col->attrs & RAY_ATTR_HAS_NULLS) && ray_vec_is_null(r->col, row); + *is_null = ray_vec_is_null(r->col, row); if (*is_null) return true; if (r->base_type == RAY_F64) memcpy(out, &((double*)ray_data(r->col))[row], 8); else *out = read_col_i64(ray_data(r->col), row, r->base_type, r->col->attrs); @@ -287,7 +287,7 @@ static bool query_key_reader_read(query_key_reader_t* r, int64_t row, ray_t* seg = r->segs[r->seg_idx]; if (!seg) return false; int64_t local = row - r->seg_start; - *is_null = (seg->attrs & RAY_ATTR_HAS_NULLS) && ray_vec_is_null(seg, local); + *is_null = ray_vec_is_null(seg, local); if (*is_null) return true; if (r->base_type == RAY_F64) memcpy(out, &((double*)ray_data(seg))[local], 8); else *out = read_col_i64(ray_data(seg), local, r->base_type, seg->attrs); @@ -2694,7 +2694,7 @@ static bool simplify_agg_idiom(ray_t* val_expr, ray_t* tbl, if (!col_expr || col_expr->type != -RAY_SYM || (col_expr->attrs & ATTR_QUOTED)) return false; ray_t* col = ray_table_get_col(tbl, col_expr->i64); - if (!col || (col->attrs & RAY_ATTR_HAS_NULLS)) return false; + if (!col || ray_vec_has_nulls(col)) return false; *op_out = is_first ? OP_MIN : OP_MAX; *arg_out = col_expr; @@ -3719,7 +3719,7 @@ static ray_t* try_count_distinct_v2_rewrite( if (!K_cols[j]) return NULL; int8_t kct_j = K_cols[j]->type; if (RAY_IS_PARTED(kct_j) || kct_j == RAY_MAPCOMMON) return NULL; - if (K_cols[j]->attrs & RAY_ATTR_HAS_NULLS) return NULL; + if (ray_vec_has_nulls(K_cols[j])) return NULL; int kct_ok_j = (kct_j == RAY_SYM || kct_j == RAY_BOOL || kct_j == RAY_U8 || kct_j == RAY_I16 || kct_j == RAY_I32 || kct_j == RAY_I64 || kct_j == RAY_DATE || kct_j == RAY_TIME || kct_j == RAY_TIMESTAMP); @@ -3730,7 +3730,7 @@ static ray_t* try_count_distinct_v2_rewrite( if (!X_col) return NULL; int8_t xct = X_col->type; if (RAY_IS_PARTED(xct) || xct == RAY_MAPCOMMON) return NULL; - if (X_col->attrs & RAY_ATTR_HAS_NULLS) return NULL; + if (ray_vec_has_nulls(X_col)) return NULL; int X_esz = ray_sym_elem_size(xct, X_col->attrs); if (K_esz_total + X_esz > 16) return NULL; /* X gets the same per-type acceptability check as the K columns @@ -5111,7 +5111,7 @@ static int try_count_simple_compare(ray_t* tbl, ray_t* where_expr, int64_t* out_ ray_t* col = ray_table_get_col(tbl, col_expr->i64); if (!col || col->len != ray_table_nrows(tbl)) return 0; - if ((col->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE)) != 0) return 0; + if (ray_vec_may_have_nulls(col)) return 0; switch (col->type) { case RAY_BOOL: @@ -6016,7 +6016,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { if (dep_candidate && base_sym >= 0) { ray_t* base_col = ray_table_get_col(tbl, base_sym); dep_candidate = base_col && key_type_i64_projectable(base_col->type) && - !(base_col->attrs & RAY_ATTR_HAS_NULLS); + !ray_vec_has_nulls(base_col); } /* Exact-size carve (unbounded): at most nk dependent-key entries can * ever be collected (one per by-dict pair). On the dependent-key @@ -7819,7 +7819,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { ray_t* dst = NULL; if (sc->type == RAY_STR) { dst = ray_vec_new(RAY_STR, out_groups); - bool src_has_nulls = (sc->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool src_has_nulls = ray_vec_may_have_nulls(sc); for (int64_t gi = 0; gi < out_groups && dst && !RAY_IS_ERR(dst); gi++) { if (src_has_nulls && ray_vec_is_null(sc, fi[gi])) { dst = ray_str_vec_append(dst, "", 0); @@ -8008,7 +8008,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { uint8_t esz = ray_sym_elem_size(sct, dst->attrs); const char* sb = (const char*)ray_data(sc); char* db = (char*)ray_data(dst); - bool src_has_nulls = (sc->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool src_has_nulls = ray_vec_may_have_nulls(sc); if (src_has_nulls) { for (int64_t gi = 0; gi < ngroups; gi++) { memcpy(db + (size_t)gi * esz, @@ -8029,7 +8029,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { uint8_t esz = ray_sym_elem_size(sct, sc->attrs); const char* sb = (const char*)ray_data(sc); char* db = (char*)ray_data(dst); - bool src_has_nulls = (sc->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool src_has_nulls = ray_vec_may_have_nulls(sc); if (src_has_nulls) { for (int64_t gi = 0; gi < ngroups; gi++) { memcpy(db + (size_t)gi * esz, @@ -8444,7 +8444,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { ray_t* dst = NULL; if (sc->type == RAY_STR) { dst = ray_vec_new(RAY_STR, n_groups); - bool src_has_nulls = (sc->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool src_has_nulls = ray_vec_may_have_nulls(sc); if (src_has_nulls) { for (int64_t gi = 0; gi < n_groups && dst && !RAY_IS_ERR(dst); gi++) { if (ray_vec_is_null(sc, fi[gi])) { @@ -9338,7 +9338,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { memset(gk_null, 0, (size_t)n_groups * sizeof(uint8_t)); if (grp_key_col) { - bool gk_has_nulls = (grp_key_col->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool gk_has_nulls = ray_vec_may_have_nulls(grp_key_col); if (gk_has_nulls) { for (int64_t gi = 0; gi < n_groups; gi++) { if (kt == RAY_F64) { @@ -9428,7 +9428,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { * that maps to it. Terminate early once every group has * a first-row. */ bool orig_nulls_flag = orig_key_col - && (orig_key_col->attrs & RAY_ATTR_HAS_NULLS) != 0; + && ray_vec_may_have_nulls(orig_key_col); int64_t found = 0; for (int64_t r = 0; r < nrows_orig && found < n_groups; r++) { bool r_null = orig_nulls_flag && ray_vec_is_null(orig_key_col, r); @@ -10048,7 +10048,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { new_col->len = nrows_r; char* src = (char*)ray_data(col); char* dst = (char*)ray_data(new_col); - bool has_nulls = (col->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(col); if (has_nulls) { for (int64_t r = 0; r < nrows_r; r++) { memcpy(dst + r * esz, src + (nrows_r - 1 - r) * esz, esz); @@ -11306,7 +11306,7 @@ ray_t* ray_xbar_fn(ray_t* col, ray_t* bucket) { /* Propagate nulls if present. Walk per-element via * ray_vec_is_null (sentinel-based). */ - if (col->attrs & RAY_ATTR_HAS_NULLS) { + if (ray_vec_may_have_nulls(col)) { for (int64_t i = 0; i < n; i++) if (ray_vec_is_null(col, i)) ray_vec_set_null(out, i, true); @@ -11389,16 +11389,6 @@ static int8_t typeless_col_type(ray_t* payload) { return RAY_I64; } -/* HAS_NULLS for a payload that may be a slice: slices carry the flag on - * their parent. Over-approximation is harmless (the flag is a fast-path - * gate; sentinels in the payload are the source of truth). */ -static bool payload_may_have_nulls(const ray_t* v) { - if (v->attrs & RAY_ATTR_HAS_NULLS) return true; - if ((v->attrs & RAY_ATTR_SLICE) && v->slice_parent) - return (v->slice_parent->attrs & RAY_ATTR_HAS_NULLS) != 0; - return false; -} - /* Helper: convert a Rayfall list of atoms into a typed column vector by * appending to an existing column (for insert/upsert). */ static ray_t* append_atom_to_col(ray_t* col_vec, ray_t* atom) { @@ -11801,7 +11791,7 @@ static ray_t* update_scatter(ray_t** slots, int64_t c, const int64_t* rows, int6 return NULL; } const uint8_t* s = (const uint8_t*)ray_data(val); - bool vn = payload_may_have_nulls(val); + bool vn = ray_vec_may_have_nulls(val); for (int64_t i = 0; i < k; i++) { if (vn && ray_vec_is_null(val, i)) { ray_vec_set_null(col, rows[i], true); continue; } memcpy(d + (size_t)rows[i] * esz, s + (size_t)i * esz, esz); @@ -11859,6 +11849,23 @@ static ray_t* update_where_inplace(ray_t* tbl, int64_t inplace_sym, ray_t* dict, } *handled = true; + /* Only a write into a key column can invalidate upsert's key map, and + * that is the one mutation its recorded row count cannot see: a cell + * rewrite leaves the count alone. An update of any other column leaves + * the mapping exactly as it was — dropping it there would send the next + * batch back to rebuilding over every row for nothing. ucol[0..nu) is + * the complete set of columns this path writes. */ + { + ray_index_t* kix = ray_table_ukey_get(tbl); + if (kix) { + bool hits_key = false; + for (int64_t i = 0; i < nu && !hits_key; i++) + for (int64_t kk = 0; kk < kix->u.ukey.nk; kk++) + if (kix->u.ukey.kci[kk] == (int16_t)ucol[i]) { hits_key = true; break; } + if (hits_key) ray_table_ukey_drop(tbl); + } + } + /* Matched rows: index probe, else the legacy mask. */ ray_t* rows_hdr = NULL; int64_t* rows = NULL; int64_t k = 0; ray_t* err = NULL; @@ -13404,7 +13411,7 @@ static ray_t* validate_parted_payloads(ray_t* tbl, ray_t* owner = (payload->attrs & RAY_ATTR_SLICE) ? payload->slice_parent : payload; if ((dst == RAY_BOOL || dst == RAY_U8) && - (!owner || (owner->attrs & RAY_ATTR_HAS_NULLS))) + (!owner || ray_vec_may_have_nulls(owner))) return ray_error("type", "insert: physical column %lld (%s) has no null representation", (long long)c, ray_type_name(dst)); if (dst == RAY_SYM) { @@ -13962,6 +13969,10 @@ static ray_t* insert_parted_rows(ray_t* tbl, ray_t* key, ray_t* rows) { /* (insert table (list val1 val2 ...)) — append a row to a table * (insert parted partition-key rows) — grow the explicit live tail */ +/* Defined with the rest of the upsert key-map helpers below; the in-place + * insert arm needs it here. */ +static void ukey_extend_after_append(ray_t* tbl, int64_t nrows0); + ray_t* ray_insert_fn(ray_t** args, int64_t n) { return ray_insert(args, n); } @@ -14434,7 +14445,7 @@ ray_t* ray_insert(ray_t** args, int64_t n) { } else if (ray_is_atom(pay)) { res = append_atom_to_col(col, pay); } else if (pay->type == ct && ct == RAY_STR) { - bool pay_nulls = payload_may_have_nulls(pay); + bool pay_nulls = ray_vec_may_have_nulls(pay); res = col; int64_t m = ray_len(pay); for (int64_t k = 0; k < m && !RAY_IS_ERR(res); k++) { @@ -14453,7 +14464,7 @@ ray_t* ray_insert(ray_t** args, int64_t n) { ((pay->attrs & RAY_SYM_W_MASK) != RAY_SYM_W64 || pay->sym_domain != ray_sym_runtime_domain())) { /* Narrow or store-domain SYM payload: translate per cell. */ - bool pay_nulls = payload_may_have_nulls(pay); + bool pay_nulls = ray_vec_may_have_nulls(pay); res = col; int64_t m = ray_len(pay); for (int64_t k = 0; k < m && !RAY_IS_ERR(res); k++) { @@ -14473,7 +14484,7 @@ ray_t* ray_insert(ray_t** args, int64_t n) { * Raw cells carry their null sentinels; propagate the * flag with them. */ res = ray_vec_append_raw(col, ray_data(pay), ray_len(pay)); - if (!RAY_IS_ERR(res) && payload_may_have_nulls(pay)) + if (!RAY_IS_ERR(res) && ray_vec_may_have_nulls(pay)) res->attrs |= RAY_ATTR_HAS_NULLS; } else if (ray_is_vec(pay) || pay->type == RAY_LIST) { /* Differently-typed vector or generic list: coerce cell by @@ -14513,6 +14524,11 @@ ray_t* ray_insert(ray_t** args, int64_t n) { } col->len = nrows; } + } else { + /* insert appends without consulting keys, and in ascending row + * order, so the map's "duplicates answer lowest row first" + * invariant survives entering the new rows as they landed. */ + ukey_extend_after_append(tbl, nrows); } if (dict_vals) { ray_t** dv = (ray_t**)ray_data(dict_vals); @@ -14562,7 +14578,7 @@ ray_t* ray_insert(ray_t** args, int64_t n) { if (RAY_IS_ERR(new_col)) { ray_release(result); return new_col; } /* Copy existing data */ - bool src_has_nulls = (orig_col->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool src_has_nulls = ray_vec_may_have_nulls(orig_col); if (ct == RAY_STR) { for (int64_t r = 0; r < nrows; r++) { if (src_has_nulls && ray_vec_is_null(orig_col, r)) { @@ -14819,6 +14835,13 @@ typedef struct { uint64_t mask; } upsert_map_t; +/* Slot encoding. An occupied slot holds row + 1, so it is always >= 1 and + * the whole negative range is free for markers. A deleted entry becomes a + * tombstone rather than being cleared: a hole in the middle of a probe chain + * would end the walk early and orphan every entry displaced past it. */ +#define UKEY_SLOT_EMPTY ((int64_t)0) +#define UKEY_SLOT_TOMB ((int64_t)-1) + static bool upsert_map_init(upsert_map_t* mp, int64_t entries) { uint64_t cap = 16; while (cap < (uint64_t)entries * 2) cap <<= 1; @@ -14829,19 +14852,63 @@ static bool upsert_map_init(upsert_map_t* mp, int64_t entries) { return true; } +/* Entries are written in ascending row order, and a tombstone is never + * reused: taking one would put a later row ahead of an earlier one in its + * chain, which changes which of two duplicate keys a keyed upsert updates. */ static void upsert_map_put(upsert_map_t* mp, uint64_t h, int64_t row) { uint64_t s = h & mp->mask; - while (mp->slot[s] != 0) s = (s + 1) & mp->mask; + while (mp->slot[s] != UKEY_SLOT_EMPTY) s = (s + 1) & mp->mask; mp->slot[s] = row + 1; } +/* Rows nrows0..n-1 were just appended in row order. Entering them costs + * what the append already cost, and it keeps the map describing the table: + * left behind, it sends the next upsert back to rebuilding over every row, + * which is the whole cost this map exists to avoid. A map that cannot take + * them is dropped rather than left naming a shorter table. */ +static void ukey_extend_after_append(ray_t* tbl, int64_t nrows0) { + ray_index_t* ix = ray_table_ukey_get(tbl); + if (!ix) return; + int64_t n = ray_table_nrows(tbl); + if (ix->u.ukey.nrows != nrows0 || n < nrows0 || + (uint64_t)(n + ix->u.ukey.n_tomb) * 2 > ix->u.ukey.mask + 1) { + ray_table_ukey_drop(tbl); + return; + } + ray_t* cols = ((ray_t**)ray_data(tbl))[1]; + if (!cols || RAY_IS_ERR(cols)) { ray_table_ukey_drop(tbl); return; } + ray_t** slots = (ray_t**)ray_data(cols); + int64_t kci[RAY_UKEY_MAX_COLS]; + int64_t nk = ix->u.ukey.nk; + for (int64_t k = 0; k < nk; k++) kci[k] = ix->u.ukey.kci[k]; + upsert_map_t map = { NULL, (int64_t*)ray_data(ix->u.ukey.slots), ix->u.ukey.mask }; + for (int64_t r = nrows0; r < n; r++) + upsert_map_put(&map, upsert_hash_row(slots, kci, nk, r), r); + ix->u.ukey.nrows = n; +} + +/* Does this table-resident map still describe the table, and can it take + * `m` more rows at the load factor it was sized for? A row count that moved + * without the map means something else wrote the table; a different key + * means a different upsert. */ +static bool ukey_fits(ray_index_t* ix, const int64_t* kci, int64_t nk, + int64_t nrows0, int64_t m) { + if (ix->u.ukey.nrows != nrows0 || ix->u.ukey.nk != nk) return false; + for (int64_t k = 0; k < nk; k++) + if (ix->u.ukey.kci[k] != (int16_t)kci[k]) return false; + /* Tombstones hold slots without being rows, so the load test counts them + * alongside the live entries. */ + return (uint64_t)(nrows0 + m + ix->u.ukey.n_tomb) * 2 <= ix->u.ukey.mask + 1; +} + static int64_t upsert_map_find(upsert_map_t* mp, uint64_t h, ray_t** slots, const int64_t* kci, int64_t nk, ray_t** cells) { uint64_t s = h & mp->mask; for (;;) { int64_t e = mp->slot[s]; - if (e == 0) return -1; - if (upsert_row_eq_atoms(slots, kci, nk, e - 1, cells)) return e - 1; + if (e == UKEY_SLOT_EMPTY) return -1; + if (e != UKEY_SLOT_TOMB && + upsert_row_eq_atoms(slots, kci, nk, e - 1, cells)) return e - 1; s = (s + 1) & mp->mask; } } @@ -15032,6 +15099,7 @@ static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, ray_t* err = NULL; upsert_map_t map = { NULL, NULL, 0 }; + ray_index_t* ukey = NULL; /* table-resident map, borrowed from tbl */ ray_t* work = NULL; if (src_cols) { @@ -15103,10 +15171,62 @@ static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, } } - if (!err && m > 1) { - if (!upsert_map_init(&map, nrows0 + m)) err = ray_error("oom", NULL); - for (int64_t r = 0; r < nrows0 && !err; r++) - upsert_map_put(&map, upsert_hash_row(slots, kci, nk, r), r); + /* The key->row map is what a bulk upsert actually costs. Built over every + * existing row on entry and freed on exit, it made a sequence of batches + * quadratic in the table size: the profile of a growing table is almost + * entirely hashing rows that were already there. When the table is a + * named binding mutated in place its object identity survives between + * calls, so the map lives on the table and is carried across them; the + * per-call cost becomes the batch, not the table. + * + * This covers a single-row upsert too, which otherwise scans the table + * for its one key. It matters less for the scan it saves than for the + * map it keeps honest: a single row appended outside the map moves the + * row count, and the next batch then finds the map stale and rebuilds + * it over everything — one interleaved row per batch was enough to put + * the whole quadratic back. */ + if (!err) { + /* A key wider than the arm gets no map — but an already attached one + * must go, not simply be skipped. This call still writes every + * non-key column of a matched row in place, and those may be the + * attached map's key columns; with no row appended the row count does + * not move either, so ukey_fits would accept it as fresh next time + * and answer from stale rows. */ + if (inplace && nk > RAY_UKEY_MAX_COLS) ray_table_ukey_drop(tbl); + if (inplace && nk <= RAY_UKEY_MAX_COLS) { + ukey = ray_table_ukey_get(tbl); + if (ukey && !ukey_fits(ukey, kci, nk, nrows0, m)) { + ray_table_ukey_drop(tbl); + ukey = NULL; + } + if (!ukey) { + ray_t* idx = ray_index_build_ukey(kci, nk, nrows0 + m); + if (idx && !RAY_IS_ERR(idx)) { + if (ray_table_ukey_attach(tbl, idx)) ukey = ray_table_ukey_get(tbl); + else ray_release(idx); + } + /* A map we could not build or attach is not an error: fall + * through to the scratch one and answer at the old cost. */ + if (ukey) { + map.slot = (int64_t*)ray_data(ukey->u.ukey.slots); + map.mask = ukey->u.ukey.mask; + for (int64_t r = 0; r < nrows0 && !err; r++) + upsert_map_put(&map, upsert_hash_row(slots, kci, nk, r), r); + ukey->u.ukey.nrows = nrows0; + } + } else { + map.slot = (int64_t*)ray_data(ukey->u.ukey.slots); + map.mask = ukey->u.ukey.mask; + } + } + /* Without a table to hang it on, a map is only worth building for a + * batch: for one row it costs the scan it would replace and is then + * thrown away. A single row keeps the scan. */ + if (!ukey && !err && m > 1) { + if (!upsert_map_init(&map, nrows0 + m)) err = ray_error("oom", NULL); + for (int64_t r = 0; r < nrows0 && !err; r++) + upsert_map_put(&map, upsert_hash_row(slots, kci, nk, r), r); + } } int64_t nrows = nrows0; @@ -15139,6 +15259,14 @@ static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, if (err && slots) upsert_rollback_appends(slots, ncols, nrows0); + /* A rolled-back batch leaves the map naming rows that no longer exist and + * a half-built one names nothing, so a failed call must not leave it on + * the table. A successful one records the row count it now describes. */ + if (ukey) { + if (err) { ray_table_ukey_drop(tbl); ukey = NULL; } + else ukey->u.ukey.nrows = nrows; + } + if (map.hdr) scratch_free(map.hdr); for (size_t i = 0; i < ncell; i++) if (owned[i] && cells[i]) ray_release(cells[i]); scratch_free(cells_hdr); @@ -15606,7 +15734,7 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { /* Copied rows must carry their null state across the rebuild — * mirror ray_insert_fn's copy loops (sentinel survives the raw * copy but RAY_ATTR_HAS_NULLS would otherwise be dropped). */ - bool src_has_nulls = (orig_col->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool src_has_nulls = ray_vec_may_have_nulls(orig_col); if (ct == RAY_STR) { for (int64_t r = 0; r < nrows; r++) { if (r == match_row && has_new_val) { @@ -16639,7 +16767,7 @@ static ray_t* window_join_impl(ray_t** args, int64_t n, int mode) { if (agg_raw[a] || agg_ops[a] == OP_COUNT) continue; ray_t* src = agg_src_vecs[a]; if (!src || right_nrows == 0) continue; - bool has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0; + bool has_nulls = ray_vec_may_have_nulls(src); if (has_nulls) { sorted_nn[a] = (uint8_t*)scratch_alloc(&sorted_nn_hdr[a], (size_t)right_nrows); @@ -18009,3 +18137,254 @@ ray_t* ray_asof_join_fn(ray_t** args, int64_t n) { ray_release(left); ray_release(right); ray_release(keys_vec); return r; } + + +/* ══════════════════════════════════════════ + * delete — remove the rows a predicate matches + * ══════════════════════════════════════════ */ + + +/* Move the survivors down over the deleted rows. Every column type stores a + * fixed-width element — a RAY_STR cell is a 16-byte descriptor and the pool it + * points into does not move with the row — so this is a memmove of the runs + * between deletions, not a per-cell copy. A boxed column releases the cells + * it drops first. Row order is preserved, so RAY_ATTR_SORTED stays true; + * an attached accelerator index does not, and is dropped. */ +static ray_t* delete_compact_cols(ray_t** slots, int64_t ncols, int64_t nrows, + const int64_t* rows, int64_t k) { + for (int64_t c = 0; c < ncols; c++) { + if (slots[c]->attrs & RAY_ATTR_HAS_INDEX) { + ray_t* drop_r = ray_index_drop(&slots[c]); + if (RAY_IS_ERR(drop_r)) return drop_r; + } + ray_t* col = slots[c]; + size_t esz = (col->type == RAY_LIST) ? sizeof(ray_t*) + : ray_sym_elem_size(col->type, col->attrs); + uint8_t* d = (uint8_t*)ray_data(col); + if (col->type == RAY_LIST) { + ray_t** cells = (ray_t**)d; + for (int64_t i = 0; i < k; i++) + if (cells[rows[i]]) ray_release(cells[rows[i]]); + } + int64_t dst = rows[0]; + for (int64_t i = 0; i < k; i++) { + int64_t src = rows[i] + 1; + int64_t end = (i + 1 < k) ? rows[i + 1] : nrows; + int64_t cnt = end - src; + if (cnt > 0) { + memmove(d + (size_t)dst * esz, d + (size_t)src * esz, (size_t)cnt * esz); + dst += cnt; + } + } + col->len = nrows - k; + } + return NULL; +} + +/* Compaction moves a surviving row from r to r - (deletions before r) and + * changes no key, so every entry keeps its bucket and only the row number it + * stores has to shift: one pass over the slot array, no hashing and no key + * reads. Entries naming a deleted row become tombstones. + * + * Patching costs that one pass whatever k is, while rebuilding costs a hash + * per survivor — so a large deletion is handed to the next upsert instead, + * which also reclaims the tombstones a patch would leave behind. */ +static void ukey_patch_after_delete(ray_t* tbl, const int64_t* rows, int64_t k, + int64_t nrows0) { + ray_index_t* ix = ray_table_ukey_get(tbl); + if (!ix) return; + int64_t left = nrows0 - k; + if (ix->u.ukey.nrows != nrows0 || k * 2 >= nrows0 || + (uint64_t)(nrows0 + ix->u.ukey.n_tomb) * 2 > ix->u.ukey.mask + 1) { + ray_table_ukey_drop(tbl); + return; + } + /* Old row -> new row, or -1 for a deleted one, built in one pass. Asking + * a binary search per slot instead cost log(k) on every slot of the + * capacity and dominated the patch; this is O(1) per slot. */ + ray_t* nr_hdr = NULL; + int64_t* newrow = (int64_t*)scratch_alloc(&nr_hdr, (size_t)nrows0 * sizeof(int64_t)); + if (!newrow) { ray_table_ukey_drop(tbl); return; } + for (int64_t r = 0, next = 0, ri = 0; r < nrows0; r++) { + if (ri < k && rows[ri] == r) { newrow[r] = -1; ri++; } + else newrow[r] = next++; + } + + int64_t* slot = (int64_t*)ray_data(ix->u.ukey.slots); + uint64_t cap = ix->u.ukey.mask + 1; + int64_t tomb = 0; + for (uint64_t s = 0; s < cap; s++) { + int64_t e = slot[s]; + if (e == UKEY_SLOT_EMPTY || e == UKEY_SLOT_TOMB) continue; + int64_t nr = newrow[e - 1]; + if (nr < 0) { slot[s] = UKEY_SLOT_TOMB; tomb++; } + else slot[s] = nr + 1; + } + scratch_free(nr_hdr); + ix->u.ukey.n_tomb += tomb; + ix->u.ukey.nrows = left; +} + +ray_t* ray_delete_fn(ray_t** args, int64_t n) { + return ray_delete(args, n); +} + +/* (delete {from: t where: }) — remove the rows the predicate matches. + * + * `from: 't` (a quoted symbol) removes them from the named table in place, + * keeping its upsert key map; `from: t` returns a new table without them. + * Both forms evaluate the predicate once and compact the same matched-row + * list with the same code, so they cannot disagree about which rows go. The + * functional form is deliberately NOT `select` over a negated predicate: that + * would be a second expression to keep in step with this one. */ +ray_t* ray_delete(ray_t** args, int64_t n) { + if (n < 1) return ray_error("arity", "delete: expects a query dict, got %lld args", (long long)n); + ray_t* dict = args[0]; + if (!dict || dict->type != RAY_DICT) + return ray_error("type", "delete: query must be a dict, got %s", dict ? ray_type_name(dict->type) : "null"); + + ray_t* from_expr = dict_get(dict, "from"); + if (!from_expr) return ray_error("domain", "delete: missing `from:` clause"); + ray_t* where_expr = dict_get(dict, "where"); + /* A delete with no predicate would empty the table, which is too easy to + * reach by leaving a clause out. Say so instead. */ + if (!where_expr) return ray_error("domain", "delete: missing `where:` clause"); + if (dict_get(dict, "by")) return ray_error("domain", "delete: `by:` is not supported"); + + int64_t inplace_sym = -1; + ray_t* tbl = ray_eval(from_expr); + if (RAY_IS_ERR(tbl)) return tbl; + if (tbl->type == -RAY_SYM) { + inplace_sym = tbl->i64; + ray_release(tbl); + tbl = ray_env_get(inplace_sym); + if (!tbl || RAY_IS_ERR(tbl)) return ray_error("domain", "delete: `from:` symbol is unbound"); + ray_retain(tbl); + } + if (tbl->type != RAY_TABLE) { + int8_t t = tbl->type; ray_release(tbl); + return ray_error("type", "delete: `from:` must be a table, got %s", ray_type_name(t)); + } + + /* A parted table's columns carry the RAY_PARTED_BASE wrapper and its + * partition key is RAY_MAPCOMMON; neither describes a flat element the + * compaction could move. Flatten once, as ray_update does — the in-place + * path declines a parted table anyway (upsert_col_ok rejects the + * wrapper), so this only feeds the copying form. */ + if (table_has_parted_columns(tbl)) { + ray_t* flat = ray_table_new(ray_table_ncols(tbl)); + if (!flat || RAY_IS_ERR(flat)) { ray_release(tbl); return flat ? flat : ray_error("oom", NULL); } + int64_t nc = ray_table_ncols(tbl); + for (int64_t c = 0; c < nc; c++) { + ray_t* fc = query_materialize_parted_col(ray_table_get_col_idx(tbl, c)); + if (!fc || RAY_IS_ERR(fc)) { ray_release(flat); ray_release(tbl); return fc ? fc : ray_error("oom", NULL); } + flat = ray_table_add_col(flat, ray_table_col_name(tbl, c), fc); + ray_release(fc); + if (!flat || RAY_IS_ERR(flat)) { ray_release(tbl); return flat ? flat : ray_error("oom", NULL); } + } + ray_release(tbl); + tbl = flat; + } + + int64_t ncols = ray_table_ncols(tbl); + int64_t nrows0 = ray_table_nrows(tbl); + if (ncols <= 0) { ray_release(tbl); return ray_error("domain", "delete: table has no columns"); } + + /* A slice column is a header-only view: ray_cow copies the header and + * leaves ray_data resolving into the parent's storage, so compacting the + * copy would move the PARENT's elements. The in-place path declines one + * through upsert_col_ok; the copying form has no such backstop, so refuse + * rather than corrupt a buffer somebody else owns. */ + for (int64_t c = 0; c < ncols; c++) + if (ray_table_get_col_idx(tbl, c)->attrs & RAY_ATTR_SLICE) { + ray_release(tbl); + return ray_error("domain", "delete: column %lld is a slice view", (long long)c); + } + + /* Decide in-place BEFORE evaluating the predicate. The predicate machinery + * binds the table's columns into a query scope (and builds a graph over + * the table), so reference counts are only quiet enough to read here. */ + bool inplace = inplace_sym >= 0 && tbl->rc == 2 && tbl->mmod == 0 && + !(tbl->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA)); + ray_t* live_cols = NULL; + if (inplace) { + live_cols = ((ray_t**)ray_data(tbl))[1]; + if (!live_cols || live_cols->rc != 1 || live_cols->len != ncols) inplace = false; + } + for (int64_t c = 0; inplace && c < ncols; c++) { + ray_t* col = ((ray_t**)ray_data(live_cols))[c]; + if (col->rc != 1 || !upsert_col_ok(col)) inplace = false; + } + + /* Matched rows, ascending — the same two paths the in-place where-update + * uses, so an indexed equality predicate is answered by the index here + * too. */ + ray_t* rows_hdr = NULL; int64_t* rows = NULL; int64_t k = 0; + ray_t* err = NULL; + if (!update_where_index_rows(tbl, where_expr, &rows_hdr, &rows, &k)) { + ray_t* mask = update_where_mask_vec(tbl, where_expr); + if (RAY_IS_ERR(mask)) { ray_release(tbl); return mask; } + int64_t mlen = mask->len; + const uint8_t* m = (const uint8_t*)ray_data(mask); + int64_t cnt = 0; + for (int64_t r = 0; r < mlen; r++) cnt += (m[r] != 0); + rows = (int64_t*)scratch_alloc(&rows_hdr, (size_t)(cnt > 0 ? cnt : 1) * sizeof(int64_t)); + if (!rows) err = ray_error("oom", NULL); + else for (int64_t r = 0; r < mlen; r++) if (m[r]) rows[k++] = r; + ray_release(mask); + if (err) { ray_release(tbl); return err; } + } + + /* Nothing matched: the in-place form leaves the binding and its map + * untouched, the functional form answers with the table as it stands. */ + if (k == 0) { + if (rows_hdr) scratch_free(rows_hdr); + if (inplace_sym >= 0) { ray_release(tbl); return ray_sym(inplace_sym); } + return tbl; + } + + if (inplace) { + ray_t** slots = (ray_t**)ray_data(live_cols); + ray_t* cerr = delete_compact_cols(slots, ncols, nrows0, rows, k); + if (cerr) { scratch_free(rows_hdr); ray_release(tbl); return cerr; } + ukey_patch_after_delete(tbl, rows, k, nrows0); + scratch_free(rows_hdr); + ray_release(tbl); + return ray_sym(inplace_sym); + } + + /* Functional form (and the fallback when a gate misses): private copies of + * the columns, then the same compaction. A fresh table carries no key + * map, which is correct — it describes rows this one does not have. */ + ray_t* work = ray_table_new(ncols); + if (!work || RAY_IS_ERR(work)) { + scratch_free(rows_hdr); ray_release(tbl); + return work ? work : ray_error("oom", NULL); + } + for (int64_t c = 0; c < ncols && !err; c++) { + ray_t* orig = ray_table_get_col_idx(tbl, c); + ray_retain(orig); + ray_t* cp = ray_cow(orig); + if (!cp || RAY_IS_ERR(cp)) { ray_release(orig); err = cp ? cp : ray_error("oom", NULL); break; } + work = ray_table_add_col(work, ray_table_col_name(tbl, c), cp); + ray_release(cp); + if (!work || RAY_IS_ERR(work)) { err = work ? work : ray_error("oom", NULL); work = NULL; } + } + if (!err) { + ray_t** wslots = (ray_t**)ray_data(((ray_t**)ray_data(work))[1]); + err = delete_compact_cols(wslots, ncols, nrows0, rows, k); + } + scratch_free(rows_hdr); + ray_release(tbl); + if (err) { if (work) ray_release(work); return err; } + /* `from: 't` promises the binding is amended and the symbol comes back, + * whether or not the in-place gate held — every sibling verb rebinds on + * this path. Returning the table instead left the binding with all its + * rows and handed the caller a value it did not ask for. */ + if (inplace_sym >= 0) { + ray_env_set(inplace_sym, work); + ray_release(work); + return ray_sym(inplace_sym); + } + return work; +} diff --git a/src/ops/rerank.c b/src/ops/rerank.c index 21926e126..64bfa095b 100644 --- a/src/ops/rerank.c +++ b/src/ops/rerank.c @@ -183,9 +183,7 @@ static ray_t* gather_rows_with_dist(ray_t* tbl, * HAS_NULLS on the parent. Mirror sort.c:3315's slice-aware * check so sliced source columns don't lose their nulls. */ bool src_has_nulls = - (src_col->attrs & RAY_ATTR_HAS_NULLS) || - ((src_col->attrs & RAY_ATTR_SLICE) && src_col->slice_parent && - (src_col->slice_parent->attrs & RAY_ATTR_HAS_NULLS)); + ray_vec_may_have_nulls(src_col); if (src_has_nulls) { for (int64_t r = 0; r < k; r++) { if (ray_vec_is_null(src_col, rowids[r])) diff --git a/src/ops/sort.c b/src/ops/sort.c index fb9249904..ffe69768f 100644 --- a/src/ops/sort.c +++ b/src/ops/sort.c @@ -948,7 +948,7 @@ void radix_encode_fn(void* arg, uint32_t wid, int64_t start, int64_t end) { switch (c->type) { case RAY_I64: case RAY_TIMESTAMP: { const int64_t* d = (const int64_t*)c->data; - bool has_nulls = c->col && (c->col->attrs & RAY_ATTR_HAS_NULLS); + bool has_nulls = c->col && ray_vec_may_have_nulls(c->col); bool nf = c->nulls_first; bool desc = c->desc; /* Null key: nf=true→sort first, nf=false→sort last. @@ -1025,7 +1025,7 @@ void radix_encode_fn(void* arg, uint32_t wid, int64_t start, int64_t end) { } case RAY_I32: case RAY_DATE: case RAY_TIME: { const int32_t* d = (const int32_t*)c->data; - bool has_nulls = c->col && (c->col->attrs & RAY_ATTR_HAS_NULLS); + bool has_nulls = c->col && ray_vec_may_have_nulls(c->col); bool nf = c->nulls_first; bool desc = c->desc; uint64_t null_e = (nf ^ desc) ? 0 : UINT64_MAX; @@ -1066,7 +1066,7 @@ void radix_encode_fn(void* arg, uint32_t wid, int64_t start, int64_t end) { } case RAY_I16: { const int16_t* d = (const int16_t*)c->data; - bool has_nulls = c->col && (c->col->attrs & RAY_ATTR_HAS_NULLS); + bool has_nulls = c->col && ray_vec_may_have_nulls(c->col); bool nf = c->nulls_first; bool desc = c->desc; if (has_nulls) { @@ -1098,7 +1098,7 @@ void radix_encode_fn(void* arg, uint32_t wid, int64_t start, int64_t end) { } case RAY_BOOL: case RAY_U8: { const uint8_t* d = (const uint8_t*)c->data; - bool has_nulls = c->col && (c->col->attrs & RAY_ATTR_HAS_NULLS); + bool has_nulls = c->col && ray_vec_may_have_nulls(c->col); bool nf = c->nulls_first; bool desc = c->desc; if (has_nulls) { @@ -1711,9 +1711,7 @@ static bool sort_str_msd_inplace(int64_t* sorted_idx, int64_t nrows, * from slice_parent, so check both attr slots — matches the * exec_sort post-sort propagation pattern. */ int64_t null_count = 0; - bool has_nulls = (col->attrs & RAY_ATTR_HAS_NULLS) || - ((col->attrs & RAY_ATTR_SLICE) && col->slice_parent && - (col->slice_parent->attrs & RAY_ATTR_HAS_NULLS)); + bool has_nulls = ray_vec_may_have_nulls(col); if (has_nulls) { int64_t w = 0; int64_t null_pos; @@ -2383,7 +2381,7 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first /* Narrow-int + has_nulls uses a +1-shifted encoding so * the null sentinel sits one byte beyond the data * range; reserve that extra byte for the radix pass. */ - if ((cols[0]->attrs & RAY_ATTR_HAS_NULLS) && + if (ray_vec_may_have_nulls(cols[0]) && (cols[0]->type == RAY_BOOL || cols[0]->type == RAY_U8 || cols[0]->type == RAY_I16) && key_nbytes_max < 8) { @@ -2592,7 +2590,7 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first bool nullable_f64_key = false; for (uint32_t k = 0; k < n_cols; k++) if (cols[k]->type == RAY_F64 && - (cols[k]->attrs & RAY_ATTR_HAS_NULLS)) { + ray_vec_may_have_nulls(cols[k])) { nullable_f64_key = true; break; } @@ -3459,7 +3457,7 @@ ray_t* ray_sort(ray_t** cols, uint8_t* descs, uint8_t* nulls_first, &sorted_keys, &keys_hdr); if (!idx || RAY_IS_ERR(idx)) return idx; - bool c0_shifted = (cols[0]->attrs & RAY_ATTR_HAS_NULLS) && + bool c0_shifted = ray_vec_may_have_nulls(cols[0]) && (cols[0]->type == RAY_BOOL || cols[0]->type == RAY_U8 || cols[0]->type == RAY_I16); @@ -3475,7 +3473,7 @@ ray_t* ray_sort(ray_t** cols, uint8_t* descs, uint8_t* nulls_first, radix_decode_into(ray_data(result), cols[0]->type, sorted_keys, nrows, descs ? descs[0] : 0); /* Propagate null bitmap using sorted indices */ - if (cols[0]->attrs & RAY_ATTR_HAS_NULLS) { + if (ray_vec_may_have_nulls(cols[0])) { int64_t* idx_data = (int64_t*)ray_data(idx); for (int64_t i = 0; i < nrows; i++) if (ray_vec_is_null(cols[0], idx_data[i])) @@ -3734,7 +3732,7 @@ sort_idx_ready:; * doesn't invert, so fall back to gather there. */ int8_t sk0_type = sort_vecs[0] ? sort_vecs[0]->type : 0; bool sk0_shifted = sort_vecs[0] && - (sort_vecs[0]->attrs & RAY_ATTR_HAS_NULLS) && + ray_vec_may_have_nulls(sort_vecs[0]) && (sk0_type == RAY_BOOL || sk0_type == RAY_U8 || sk0_type == RAY_I16); int64_t sort_key_sym = -1; @@ -3801,9 +3799,7 @@ sort_idx_ready:; if (!col) continue; col_propagate_str_pool(new_cols[c], col); /* Gather null bits in sorted order */ - bool src_has_nulls = (col->attrs & RAY_ATTR_HAS_NULLS) || - ((col->attrs & RAY_ATTR_SLICE) && col->slice_parent && - (col->slice_parent->attrs & RAY_ATTR_HAS_NULLS)); + bool src_has_nulls = ray_vec_may_have_nulls(col); if (src_has_nulls) { for (int64_t r = 0; r < gather_rows; r++) if (ray_vec_is_null(col, sorted_idx[r])) @@ -3954,7 +3950,7 @@ static void sorted_check_fn(void* raw, uint32_t wid, int64_t start, int64_t end) * reads raw i64, and the bail flag is polled per 4096-row block. * * Callers reach this only for null-free keys (ray_key_cols_sorted rejects - * HAS_NULLS up front, including for SYM/STR). That is not squeamishness + * actual nulls up front, including for SYM). That is not squeamishness * about in-band nulls: this loop ranks sym 0 by its domain string, i.e. * smallest, whereas the real sort places nulls by the `nulls_first` flag * independently of payload. See the note on ray_key_cols_sorted. */ @@ -3963,7 +3959,7 @@ static void sorted_check_fn(void* raw, uint32_t wid, int64_t start, int64_t end) (c->key_cols[1]->type == RAY_I64 || c->key_cols[1]->type == RAY_TIME || c->key_cols[1]->type == RAY_TIMESTAMP) && - !(c->key_cols[1]->attrs & RAY_ATTR_HAS_NULLS)) { + !ray_vec_may_have_nulls(c->key_cols[1])) { ray_t* sc = c->key_cols[0]; const void* sd = ray_data(sc); uint8_t sattrs = sc->attrs; @@ -4023,10 +4019,10 @@ static void sorted_check_fn(void* raw, uint32_t wid, int64_t start, int64_t end) /* Public: are these key columns already in sorted order under the sort's * lexicographic ordering (single uniform direction across all keys)? Only * null-free integer-family / SYM keys are decidable — anything else (float, - * STR/LIST, or a HAS_NULLS column) returns false so the caller must NOT + * STR/LIST, or a column containing nulls) returns false so the caller must NOT * assume sortedness (float NaN / null placement belong to the real sort). * - * The HAS_NULLS rejection stands even for SYM/STR, whose nulls are IN-BAND + * The null rejection stands even for SYM/STR, whose nulls are IN-BAND * ordinary values (sym id 0 is a real dictionary entry — the empty string at * position 0 of every symfile; a STR null is a zero-length descriptor). That * in-band property is what lets the fused predicate evaluator compare them for @@ -4053,7 +4049,7 @@ bool ray_key_cols_sorted(ray_t** key_cols, int64_t n_keys, uint8_t descending, * than silently treating an unorderable column as ordered. */ for (int64_t k = 0; k < n_keys; k++) { int8_t t = key_cols[k]->type; - if (key_cols[k]->attrs & RAY_ATTR_HAS_NULLS) return false; + if (ray_vec_has_nulls(key_cols[k])) return false; if (t != RAY_BOOL && t != RAY_U8 && t != RAY_I16 && t != RAY_I32 && t != RAY_I64 && t != RAY_DATE && t != RAY_TIME && t != RAY_TIMESTAMP && t != RAY_SYM) @@ -4087,7 +4083,8 @@ static void sort_note_part_order(ray_t* col, int64_t order_sym) { } static ray_t* sort_stamp_part_col_owned(ray_t* col, int64_t order_sym) { - if (!col || RAY_IS_ERR(col) || (col->attrs & RAY_ATTR_HAS_NULLS) || + if (!col || RAY_IS_ERR(col) || + (col->type != RAY_SYM && ray_vec_may_have_nulls(col)) || !sort_part_key_type(col->type)) return NULL; ray_t* w = col; @@ -4102,7 +4099,8 @@ static ray_t* sort_stamp_part_col_owned(ray_t* col, int64_t order_sym) { static ray_t* sort_stamp_ordered_table(ray_t* tbl, int64_t key_id, ray_t* key_col, int64_t order_sym) { - if (!key_col || (key_col->attrs & RAY_ATTR_HAS_NULLS) || + if (!key_col || + (key_col->type != RAY_SYM && ray_vec_may_have_nulls(key_col)) || !sort_part_key_type(key_col->type)) { ray_retain(tbl); return tbl; @@ -4219,7 +4217,7 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { bool detectable = true; for (int64_t k = 0; k < n_keys && detectable; k++) { int8_t t = key_cols[k]->type; - if (key_cols[k]->attrs & RAY_ATTR_HAS_NULLS) detectable = false; + if (ray_vec_has_nulls(key_cols[k])) detectable = false; else if (t != RAY_BOOL && t != RAY_U8 && t != RAY_I16 && t != RAY_I32 && t != RAY_I64 && t != RAY_DATE && t != RAY_TIME && t != RAY_TIMESTAMP && t != RAY_SYM) @@ -4333,7 +4331,7 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { * so fall back to gather in that case. */ int64_t decode_col_idx = -1; int8_t k0_type = key_cols[0]->type; - bool k0_shifted = (key_cols[0]->attrs & RAY_ATTR_HAS_NULLS) && + bool k0_shifted = ray_vec_may_have_nulls(key_cols[0]) && (k0_type == RAY_BOOL || k0_type == RAY_U8 || k0_type == RAY_I16); if (sorted_keys && n_keys == 1 && !RAY_IS_SYM(k0_type) && !k0_shifted) { @@ -4394,9 +4392,7 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { ray_t* col = ray_table_get_col_idx(tbl, c); if (!col) continue; col_propagate_str_pool(new_cols[c], col); - bool src_has_nulls = (col->attrs & RAY_ATTR_HAS_NULLS) || - ((col->attrs & RAY_ATTR_SLICE) && col->slice_parent && - (col->slice_parent->attrs & RAY_ATTR_HAS_NULLS)); + bool src_has_nulls = ray_vec_may_have_nulls(col); if (src_has_nulls) { for (int64_t r = 0; r < nrows; r++) if (ray_vec_is_null(col, idx_data[r])) @@ -4413,13 +4409,13 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { * semantics are not what downstream consumers (asof presort/index * paths) assume. */ if (!descending && - !(key_cols[0]->attrs & RAY_ATTR_HAS_NULLS) && + !ray_vec_may_have_nulls(key_cols[0]) && (k0_type == RAY_BOOL || k0_type == RAY_U8 || k0_type == RAY_I16 || k0_type == RAY_I32 || k0_type == RAY_I64 || k0_type == RAY_DATE || k0_type == RAY_TIME || k0_type == RAY_TIMESTAMP)) { for (int64_t c = 0; c < ncols; c++) { if (col_names[c] == key_ids[0] && new_cols[c] && - !(new_cols[c]->attrs & RAY_ATTR_HAS_NULLS)) { + !ray_vec_may_have_nulls(new_cols[c])) { new_cols[c]->attrs |= RAY_ATTR_SORTED; break; } diff --git a/src/ops/string.c b/src/ops/string.c index 4d474dd33..84f36e5bf 100644 --- a/src/ops/string.c +++ b/src/ops/string.c @@ -1166,7 +1166,7 @@ static bool substr_scalar_arg(ray_t* v, int64_t* out) { default: return false; } } - if (!ray_is_vec(v) || v->len != 1 || (v->attrs & RAY_ATTR_HAS_NULLS)) + if (!ray_is_vec(v) || v->len != 1 || ray_vec_may_have_nulls(v)) return false; switch (v->type) { case RAY_I64: *out = ((int64_t*)ray_data(v))[0]; return true; @@ -1180,7 +1180,7 @@ static bool substr_scalar_arg(ray_t* v, int64_t* out) { } static ray_t* substr_str_scalar_view(ray_t* input, int64_t start, int64_t length) { - if (!input || input->type != RAY_STR || (input->attrs & RAY_ATTR_HAS_NULLS)) + if (!input || input->type != RAY_STR) return NULL; int64_t nrows = input->len; @@ -1240,7 +1240,7 @@ static ray_t* substr_str_scalar_view(ray_t* input, int64_t start, int64_t length static bool substr_len_at(ray_t* len_v, int64_t row, int64_t* out) { if (!len_v || !out) return false; - if (len_v->attrs & RAY_ATTR_HAS_NULLS) { + if (ray_vec_may_have_nulls(len_v)) { if (ray_vec_is_null(len_v, row)) return false; } switch (len_v->type) { @@ -1264,8 +1264,7 @@ static bool substr_len_at(ray_t* len_v, int64_t row, int64_t* out) { static ray_t* substr_str_scalar_start_len_view(ray_t* input, int64_t start, ray_t* len_v) { - if (!input || input->type != RAY_STR || !len_v || - (input->attrs & RAY_ATTR_HAS_NULLS)) + if (!input || input->type != RAY_STR || !len_v) return NULL; if (len_v->type != RAY_I64 && len_v->type != RAY_I32) return NULL; @@ -1340,7 +1339,7 @@ static ray_t* substr_str_scalar_start_len_view(ray_t* input, static bool substr_scalar_is_null(ray_t* v) { if (!v) return false; if (ray_is_atom(v)) return RAY_ATOM_IS_NULL(v); - if (ray_is_vec(v) && v->len == 1 && (v->attrs & RAY_ATTR_HAS_NULLS)) + if (ray_is_vec(v) && v->len == 1 && ray_vec_may_have_nulls(v)) return ray_vec_is_null(v, 0); return false; } diff --git a/src/ops/system.c b/src/ops/system.c index d7f16e356..417b034ae 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -24,6 +24,7 @@ #include "lang/internal.h" #include "lang/env.h" #include "lang/eval.h" /* LAMBDA_PARAMS */ +#include "lang/nfo.h" /* NFO_FILENAME */ #include "lang/parse.h" #include "ops/ops.h" /* ray_is_lazy, ray_lazy_materialize */ #include "ops/internal.h" /* ray_group_perpart_runs — (.sys.mem) counter */ @@ -584,6 +585,7 @@ static size_t objsize_shallow(ray_t* v) { static bool objsize_push_index_children(ray_objsize_walk_t* w, ray_index_t* ix) { #define OBJSIZE_PUSH(child) do { if (!objsize_stack_push(w, (child))) return false; } while (0) switch ((ray_idx_kind_t)ix->kind) { + case RAY_IDX_UKEY: OBJSIZE_PUSH(ix->u.ukey.slots); break; case RAY_IDX_HASH: OBJSIZE_PUSH(ix->u.hash.table); OBJSIZE_PUSH(ix->u.hash.gkeys); OBJSIZE_PUSH(ix->u.hash.offs); OBJSIZE_PUSH(ix->u.hash.rows); @@ -638,7 +640,11 @@ static bool objsize_push_children(ray_objsize_walk_t* w, ray_t* v) { * aux bytes 8..15; the index pointer only occupies bytes 0..7. */ if (v->type == RAY_STR && v->str_pool) OBJSIZE_PUSH(v->str_pool); - return true; + /* A TABLE carries the keyed-upsert map here, but its schema and + * columns are still its own children: returning now would report a + * mapped table as nothing but its map. Fall through to the arm + * below. Only a vector has nothing further to walk. */ + if (v->type != RAY_TABLE) return true; } if (v->type == RAY_STR && v->str_pool) OBJSIZE_PUSH(v->str_pool); @@ -1372,12 +1378,37 @@ ray_t* ray_build_sys_args(int argc, char** argv) { } /* (.sys.args) -- return the application-arguments dict (empty if unset) */ +/* The launcher dict is built once at startup; `source` is the one key + * that changes while the process runs — the file currently being + * evaluated (the innermost `load`, or the command-line script), by the + * path that was actually opened, so a script can locate its neighbours + * from any working directory (#506). Empty at the REPL, under a pipe, + * or in a hook or timer outside any file — the same convention as + * `file`. bash's $BASH_SOURCE next to $0. */ ray_t* ray_sys_args_fn(ray_t** args, int64_t n) { (void)args; if (n != 0) return ray_error("domain", ".sys.args takes no arguments"); ray_t* d = (ray_t*)ray_runtime_get_sys_args(); - if (d) { ray_retain(d); return d; } - return ray_dict_new(ray_sym_vec_new(RAY_SYM_W64, 0), ray_list_new(0)); + ray_t* keys; ray_t* vals; + if (d) { + keys = ray_dict_keys(d); ray_retain(keys); /* append COWs the shared vectors */ + vals = ray_dict_vals(d); ray_retain(vals); + } else { + keys = ray_sym_vec_new(RAY_SYM_W64, 1); + vals = ray_list_new(1); + } + ray_t* nfo = ray_eval_get_nfo(); + ray_t* src = (nfo && !RAY_IS_ERR(nfo)) ? NFO_FILENAME(nfo) : NULL; + bool is_file = src && !RAY_IS_ERR(src) && src->type == -RAY_STR && + !(ray_str_len(src) == strlen(RAY_NFO_REPL_NAME) && + memcmp(ray_str_ptr(src), RAY_NFO_REPL_NAME, ray_str_len(src)) == 0); + ray_t* sv = is_file ? (ray_retain(src), src) : ray_str("", 0); + int64_t k = ray_sym_intern("source", 6); + keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); ray_release(sv); return keys; } + vals = ray_list_append(vals, sv); ray_release(sv); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + return ray_dict_new(keys, vals); } /* ══════════════════════════════════════════ @@ -1521,22 +1552,23 @@ ray_t* ray_hpost_fn(ray_t* handle, ray_t* msg) { /* Build {handle limit_bytes limit_frames queued_bytes queued_frames hwm_bytes} * for a live connection. */ static ray_t* ipc_tx_info_dict(int64_t h, const ray_ipc_tx_info_t* ti) { - static const char* const names[6] = { "handle", "limit_bytes", "limit_frames", + static const char* const names[7] = { "handle", "inbound", "limit_bytes", "limit_frames", "queued_bytes", "queued_frames", "hwm_bytes" }; - int64_t vals_i[6] = { h, ti->limit_bytes, ti->limit_frames, + int64_t vals_i[7] = { h, ti->inbound ? 1 : 0, ti->limit_bytes, ti->limit_frames, ti->queued_bytes, ti->queued_frames, ti->hwm_bytes }; - ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 6); - ray_t* vals = ray_list_new(6); + ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 7); + ray_t* vals = ray_list_new(7); if (!keys || RAY_IS_ERR(keys) || !vals || RAY_IS_ERR(vals)) { if (keys && !RAY_IS_ERR(keys)) ray_release(keys); if (vals && !RAY_IS_ERR(vals)) ray_release(vals); return ray_error("oom", NULL); } - for (int i = 0; i < 6; i++) { + for (int i = 0; i < 7; i++) { int64_t k = ray_sym_intern(names[i], strlen(names[i])); keys = ray_vec_append(keys, &k); if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } - ray_t* v = make_i64(vals_i[i]); + /* `inbound` is the direction: accepted here, or opened by .ipc.open */ + ray_t* v = (i == 1) ? ray_bool(vals_i[i] != 0) : make_i64(vals_i[i]); vals = ray_list_append(vals, v); ray_release(v); if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } } diff --git a/src/ops/tblop.c b/src/ops/tblop.c index d6c869858..7da33443a 100644 --- a/src/ops/tblop.c +++ b/src/ops/tblop.c @@ -1310,7 +1310,26 @@ ray_t* ray_alter_fn(ray_t** args, int64_t n) { * extra ref. */ ray_t* original_var = var; ray_retain(var); - ray_t* cow_result = ray_cow(var); + /* `alter` amends in place, and ray_cow only copies what is shared — + * but the retain above is unconditional, so ray_cow's own `rc == 1` + * test could never be true here and the copy path fired on every + * call. A one-element write copied the whole vector, and the cost + * of an alter scaled with the vector's length rather than with the + * write. Sole ownership after our retain is `rc == 2`: the + * binding's reference and ours. The other three exclusions keep the + * previous behaviour exactly — ray_cow returns an arena block as-is, + * and a slice or a mapped block is not ours to write through. */ + /* A dotted name is NOT a candidate. ray_env_get resolves `d.x` to the + * leaf living inside the container, which typically holds the only + * reference to it — so the leaf passes an rc test that says nothing + * about whether the CONTAINER is shared. Writing through it would be + * seen by every alias of the dict or table, and env_set_dotted's + * COW-rebuild of the chain cannot undo a write that already + * happened. The copy is what made that safe. */ + bool sole = !ray_sym_is_dotted(name_sym->i64) && + var->rc == 2 && var->mmod == 0 && + !(var->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA)); + ray_t* cow_result = sole ? var : ray_cow(var); /* ray_cow returns NULL when ray_alloc_copy returned NULL (heap * exhaustion past RAY_HEAP_MAX_ORDER) and a RAY_ERROR pointer * when alloc_copy hit its own len-overflow guard. Both leave diff --git a/src/ops/temporal.c b/src/ops/temporal.c index 9a6ab2541..8e216c17f 100644 --- a/src/ops/temporal.c +++ b/src/ops/temporal.c @@ -307,9 +307,7 @@ ray_t* ray_temporal_extract(ray_t* input, int field) { /* Slice-aware HAS_NULLS check: slices don't carry HAS_NULLS on * themselves, so inspect the parent when input is a slice. */ bool src_has_nulls = - (input->attrs & RAY_ATTR_HAS_NULLS) || - ((input->attrs & RAY_ATTR_SLICE) && input->slice_parent && - (input->slice_parent->attrs & RAY_ATTR_HAS_NULLS)); + ray_vec_may_have_nulls(input); /* src_has_nulls and the 32-/64-bit element dispatch are hoisted into the * context so the inner body is a tight typed kernel with no per-element * branches; the row range is chunked over the pool for large columns. */ @@ -414,9 +412,7 @@ ray_t* ray_temporal_truncate(ray_t* input, int kind) { /* Slice-aware HAS_NULLS check: slices don't carry HAS_NULLS on * themselves, so inspect the parent when input is a slice. */ bool src_has_nulls = - (input->attrs & RAY_ATTR_HAS_NULLS) || - ((input->attrs & RAY_ATTR_SLICE) && input->slice_parent && - (input->slice_parent->attrs & RAY_ATTR_HAS_NULLS)); + ray_vec_may_have_nulls(input); const char* base = (const char*)ray_data(input); int64_t bucket = (kind == RAY_EXTRACT_DAY) ? RTE_USEC_PER_DAY @@ -614,9 +610,7 @@ ray_t* exec_extract(ray_graph_t* g, ray_op_t* op) { /* Slice-aware HAS_NULLS check: slices don't carry HAS_NULLS on * themselves, so inspect the parent when input is a slice. */ bool src_has_nulls = - (input->attrs & RAY_ATTR_HAS_NULLS) || - ((input->attrs & RAY_ATTR_SLICE) && input->slice_parent && - (input->slice_parent->attrs & RAY_ATTR_HAS_NULLS)); + ray_vec_may_have_nulls(input); /* Preserve ray_morsel_init's one-time sequential-readahead hint for * mmap'd columns. The per-worker ray_morsel_init_range deliberately @@ -832,9 +826,7 @@ ray_t* exec_date_trunc(ray_graph_t* g, ray_op_t* op) { /* Slice-aware HAS_NULLS check: slices don't carry HAS_NULLS on * themselves, so inspect the parent when input is a slice. */ bool src_has_nulls = - (input->attrs & RAY_ATTR_HAS_NULLS) || - ((input->attrs & RAY_ATTR_SLICE) && input->slice_parent && - (input->slice_parent->attrs & RAY_ATTR_HAS_NULLS)); + ray_vec_may_have_nulls(input); /* Preserve ray_morsel_init's one-time sequential-readahead hint for * mmap'd columns. The per-worker ray_morsel_init_range deliberately diff --git a/src/ops/window.c b/src/ops/window.c index f0b526f1b..491b6d896 100644 --- a/src/ops/window.c +++ b/src/ops/window.c @@ -988,7 +988,7 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { uint8_t key_nbytes = radix_key_bytes(sort_vecs[0]->type); /* Narrow-int + has_nulls uses a +1-shifted encoding — * keep the radix pass aligned with the wider key. */ - if ((sort_vecs[0]->attrs & RAY_ATTR_HAS_NULLS) && + if (ray_vec_may_have_nulls(sort_vecs[0]) && (sort_vecs[0]->type == RAY_BOOL || sort_vecs[0]->type == RAY_U8 || sort_vecs[0]->type == RAY_I16) && diff --git a/src/store/col.c b/src/store/col.c index 3db8a4550..27a6b7516 100644 --- a/src/store/col.c +++ b/src/store/col.c @@ -875,7 +875,11 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { ray_index_t* ix = ray_index_payload(vec->index); header.attrs &= ~RAY_ATTR_HAS_INDEX; memcpy(header.aux, ix->saved_aux, 16); - persist_index = (vec->index != NULL); + /* STR indexes (dict, hash) are appended after the pool by the + * splayed builder (ray_col_append_index), which stamps the marker + * itself and refuses a file already carrying one — so a STR save + * must not stamp it here. */ + persist_index = (vec->index != NULL) && vec->type != RAY_STR; } /* HAS_LINK rebase: target sym ID lives at header.aux[8..15], diff --git a/src/store/journal.c b/src/store/journal.c index 0fd94c8c0..2d3a3932c 100644 --- a/src/store/journal.c +++ b/src/store/journal.c @@ -689,9 +689,8 @@ ray_err_t ray_journal_purge(void) { /* Close the active log FIRST: never unlink a path out from under * buffered writes (and Windows refuses to unlink an open file). */ if (g_journal.fp) { - fflush(g_journal.fp); - fclose(g_journal.fp); - g_journal.fp = NULL; + ray_err_t close_result = ray_journal_close(); + if (close_result != RAY_OK) return close_result; } ray_err_t result = RAY_OK; @@ -790,6 +789,15 @@ ray_err_t ray_journal_roll(void) { int n = snprintf(archive, sizeof(archive), "%s.%s.log", g_journal.base, stamp); if (n <= 0 || (size_t)n >= sizeof(archive)) return RAY_ERR_DOMAIN; + /* Rolls can happen more than once during a single UTC second. Keep the + * readable timestamp for the common case, but never let rename() replace + * an earlier archive when the timestamp collides. */ + for (unsigned int suffix = 1; file_exists(archive); suffix++) { + n = snprintf(archive, sizeof(archive), "%s.%s.%u.log", + g_journal.base, stamp, suffix); + if (n <= 0 || (size_t)n >= sizeof(archive)) return RAY_ERR_DOMAIN; + } + int flush_rc = fflush(g_journal.fp); int close_rc = fclose(g_journal.fp); g_journal.fp = NULL; diff --git a/src/store/splay.c b/src/store/splay.c index 921161070..d59bd0b2e 100644 --- a/src/store/splay.c +++ b/src/store/splay.c @@ -560,6 +560,24 @@ void ray_splay_build_indexes(const char* dir, ray_t* tbl) { continue; } + /* Explicit STR index: a grouped / unique hash on a STR column is keyed + * on byte hashes and row ids — neither depends on a domain — so the + * in-memory index persists verbatim, regardless of length. It takes + * the column's single index slot: the size-gated auto dictionary + * below is not built for it. */ + if (col->type == RAY_STR && ray_index_kind(col) == RAY_IDX_HASH) { + ray_t* nstr = ray_sym_str(ray_table_col_name(tbl, c)); + if (nstr && !RAY_IS_ERR(nstr)) { + char path[1024]; + 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(col->index), + col->len, RAY_STR); + } + continue; + } + if (col->len < (1 << 16)) continue; /* STR columns get a dictionary (group on int codes); numeric/temporal diff --git a/src/table/dict.c b/src/table/dict.c index 7214f8725..d37d4e2b5 100644 --- a/src/table/dict.c +++ b/src/table/dict.c @@ -21,10 +21,12 @@ * SOFTWARE. */ +#include "vec/vec.h" #include "dict.h" #include "table.h" #include "table/sym.h" #include "lang/internal.h" /* atom_eq for RAY_LIST key compares */ +#include "ops/idxop.h" /* ray_index_find_atom: keyed lookup via an attached hash */ #include /* -------------------------------------------------------------------------- @@ -200,6 +202,13 @@ int64_t ray_dict_find_idx(ray_t* d, ray_t* key_atom) { /* Typed-vector keys: atom type must match. */ if (key_atom->type != -kt) return -1; + /* Keys carrying a hash index (`.attr.set 'grouped` / `'unique`): one + * probe instead of the scan below. -2 = not eligible → scan. */ + if (ray_index_has(keys)) { + int64_t r = ray_index_find_atom(keys, key_atom); + if (r >= -1) return r; + } + /* Null-aware probe: a null key atom matches only null slots; a non-null * key atom must match a non-null slot of equal value. Without this, a * group dict containing both `0Nl` and `0` keys (now produced as @@ -207,7 +216,7 @@ int64_t ray_dict_find_idx(ray_t* d, ray_t* key_atom) { * to the first non-null zero — re-introducing the conflation we just * fixed in grouping. */ bool key_is_null = RAY_ATOM_IS_NULL(key_atom); - bool keys_have_nulls = (keys->attrs & RAY_ATTR_HAS_NULLS) != 0 + bool keys_have_nulls = ray_vec_may_have_nulls(keys) || (keys->attrs & RAY_ATTR_SLICE); if (key_is_null) { if (!keys_have_nulls) return -1; diff --git a/src/table/sym.c b/src/table/sym.c index 8dda62057..d91dbb3be 100644 --- a/src/table/sym.c +++ b/src/table/sym.c @@ -184,8 +184,7 @@ ray_err_t ray_sym_init(void) { * symbol the canonical "no value" representation for SYM columns: * a missing CSV cell, a null-marked SYM atom, and an explicit "" * literal all collapse to ID 0. SYM columns therefore never need - * a parallel null bitmap — RAY_ATTR_HAS_NULLS is structurally - * meaningless on SYM and is rejected on set. Done before + * a parallel null bitmap or HAS_NULLS flag to identify null cells. Done before * returning so every subsequent intern observes ID 0 as taken. */ int64_t empty_id = sym_intern_nolock( (uint32_t)ray_hash_bytes("", 0), "", 0, true); diff --git a/src/vec/vec.c b/src/vec/vec.c index 815dd1852..2b41fed3d 100644 --- a/src/vec/vec.c +++ b/src/vec/vec.c @@ -84,13 +84,6 @@ static inline bool sentinel_is_null(const ray_t* v, int64_t idx) { } } -/* True if v has any nulls. HAS_NULLS is preserved on the parent across - * index attach/detach (see attach_finalize), so this is the same one-bit - * test in both indexed and non-indexed cases. */ -static inline bool vec_any_nulls(const ray_t* v) { - return (v->attrs & RAY_ATTR_HAS_NULLS) != 0; -} - /* In-place drop of attached index — caller must hold a unique ref (rc==1) * on `v` itself. Used by mutation paths to invalidate the (now stale) * index before writing. HAS_NULLS was preserved through the attachment @@ -524,8 +517,8 @@ ray_t* ray_vec_concat(ray_t* a, ray_t* b) { /* Propagate null bitmaps from a and b. * Slices don't carry RAY_ATTR_HAS_NULLS — check RAY_ATTR_SLICE too. */ - if ((a->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE)) || - (b->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE))) { + if (ray_vec_may_have_nulls(a) || + ray_vec_may_have_nulls(b)) { for (int64_t i = 0; i < a->len; i++) { if (ray_vec_is_null((ray_t*)a, i)) { ray_err_t err = ray_vec_set_null_checked(result, i, true); @@ -659,8 +652,8 @@ ray_t* ray_vec_concat(ray_t* a, ray_t* b) { /* Propagate null bitmaps from a and b. * Slices don't carry RAY_ATTR_HAS_NULLS — check RAY_ATTR_SLICE too. */ - if ((a->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE)) || - (b->attrs & (RAY_ATTR_HAS_NULLS | RAY_ATTR_SLICE))) { + if (ray_vec_may_have_nulls(a) || + ray_vec_may_have_nulls(b)) { for (int64_t i = 0; i < a->len; i++) { if (ray_vec_is_null((ray_t*)a, i)) { ray_err_t err = ray_vec_set_null_checked(result, i, true); @@ -1568,7 +1561,7 @@ bool ray_vec_is_null(ray_t* vec, int64_t idx) { return ((const ray_str_t*)ray_data(vec))[idx].len == 0; /* Vec-level fast-path gate: HAS_NULLS clear means no null anywhere. */ - if (!vec_any_nulls(vec)) return false; + if (!(vec->attrs & RAY_ATTR_HAS_NULLS)) return false; /* Sentinels are the sole source of truth. BOOL/U8 are non-nullable * (rejected at the producer) so they can never reach here with @@ -1598,14 +1591,7 @@ ray_err_t ray_vec_copy_nulls(ray_t* dst, const ray_t* src) { /* Use ray_vec_is_null which handles slices and sentinel reads * transparently. For non-null sources this returns immediately. */ - bool has_any = false; - if (src->attrs & RAY_ATTR_SLICE) { - const ray_t* parent = src->slice_parent; - if (parent && (parent->attrs & RAY_ATTR_HAS_NULLS)) has_any = true; - } else { - if (src->attrs & RAY_ATTR_HAS_NULLS) has_any = true; - } - if (!has_any) return RAY_OK; + if (!ray_vec_may_have_nulls(src)) return RAY_OK; for (int64_t i = 0; i < dst->len && i < src->len; i++) { if (ray_vec_is_null((ray_t*)src, i)) { diff --git a/src/vec/vec.h b/src/vec/vec.h index 97368d4cd..a6aff1feb 100644 --- a/src/vec/vec.h +++ b/src/vec/vec.h @@ -33,6 +33,32 @@ */ #include +#include "mem/heap.h" + +/* Conservative null-check gate, not an exact count of nulls. SYM/STR encode + * null as id 0 / length 0 independently of metadata, including old persisted + * columns and raw gathers. Other vectors retain their HAS_NULLS fast path. + * Resolve slices here so callers never interpret their view attrs as proof + * that the underlying payload is null-free. This is a row-kernel gate, not + * a reason to reject a text optimization: equality can compare canonical + * payloads directly; paths requiring null-free data use has_nulls below. */ +static inline bool ray_vec_may_have_nulls(const ray_t* v) { + if (!v) return false; + if (v->type == RAY_SYM || v->type == RAY_STR) return true; + while ((v->attrs & RAY_ATTR_SLICE) && v->slice_parent) + v = v->slice_parent; + return (v->attrs & RAY_ATTR_HAS_NULLS) != 0; +} + +/* Exact admission check for optimizations which require null-free input. + * Text columns cannot prove that from attrs; inspect their payload instead. + * Keep this out of per-row loops (use may_have_nulls + is_null there). */ +static inline bool ray_vec_has_nulls(const ray_t* v) { + if (!ray_vec_may_have_nulls(v)) return false; + for (int64_t i = 0; i < v->len; i++) + if (ray_vec_is_null((ray_t*)v, i)) return true; + return false; +} /* Copy null bits from src to dst (sentinel-based). dst and src must have * the same length. Internal helper. */ diff --git a/test/main.c b/test/main.c index 583f2ab38..7c6149d99 100644 --- a/test/main.c +++ b/test/main.c @@ -162,6 +162,7 @@ extern const test_entry_t stress_matrix_entries[]; extern const test_entry_t stress_random_entries[]; extern const test_entry_t str_entries[]; extern const test_entry_t sym_entries[]; +extern const test_entry_t text_null_entries[]; extern const test_entry_t sys_entries[]; extern const test_entry_t table_entries[]; extern const test_entry_t term_entries[]; @@ -202,7 +203,7 @@ static const test_entry_t* const compiled_groups[] = { stress_eval_entries, stress_matrix_entries, stress_random_entries, - str_entries, sym_entries, sys_entries, table_entries, + text_null_entries, str_entries, sym_entries, sys_entries, table_entries, term_entries, traverse_entries, types_entries, vec_entries, window_entries, NULL, diff --git a/test/rfl/datalog/audit_regressions.rfl b/test/rfl/datalog/audit_regressions.rfl new file mode 100644 index 000000000..8f344deb6 --- /dev/null +++ b/test/rfl/datalog/audit_regressions.rfl @@ -0,0 +1,126 @@ +;; Regressions for docs/superpowers/specs/2026-09-08-datalog-audit.md. +;; Chain 1->2->...->8 (7 edges). Full transitive closure = 7*8/2 = 28 pairs. +(set g (datoms)) +(set g (assert-fact g 1 'edge 2)) +(set g (assert-fact g 2 'edge 3)) +(set g (assert-fact g 3 'edge 4)) +(set g (assert-fact g 4 'edge 5)) +(set g (assert-fact g 5 'edge 6)) +(set g (assert-fact g 6 'edge 7)) +(set g (assert-fact g 7 'edge 8)) + +;; §1.1 linear (already correct) and non-linear closure must agree. +(rule (lin ?x ?y) (?x :edge ?y)) +(rule (lin ?x ?z) (?x :edge ?y) (lin ?y ?z)) +(count (query g (find ?x ?y) (where (lin ?x ?y)))) -- 28 +(rule (nl ?x ?y) (?x :edge ?y)) +(rule (nl ?x ?z) (nl ?x ?y) (nl ?y ?z)) +(count (query g (find ?x ?y) (where (nl ?x ?y)))) -- 28 +;; the three pairs the old evaluator dropped +(count (query g (find ?x ?y) (where (nl ?x ?y) (== ?x 1) (== ?y 6)))) -- 1 +(count (query g (find ?x ?y) (where (nl ?x ?y) (== ?x 2) (== ?y 7)))) -- 1 +(count (query g (find ?x ?y) (where (nl ?x ?y) (== ?x 3) (== ?y 8)))) -- 1 + +;; §1.2 a repeated variable inside one atom is an equality constraint. +(count (query g (find ?x) (where (?x :edge ?x)))) -- 0 +(count (query g (find ?x) (where (lin ?x ?x)))) -- 0 +(set g2 (assert-fact g 5 'edge 5)) +(count (query g2 (find ?x) (where (?x :edge ?x)))) -- 1 +(at (at (query g2 (find ?x) (where (?x :edge ?x))) '?x) 0) -- 5 +;; ... and inside a negated atom: every node except the one with a self-loop +(count (query g2 (find ?x) (where (?x :edge ?y) (not (?x :edge ?x))))) -- 6 + +;; §1.3 a negated atom with no shared variables is a guard, not a no-op. +(count (query g (find ?x) (where (?x :edge ?y) (not (1 :edge 2))))) -- 0 +(count (query g (find ?x) (where (?x :edge ?y) (not (1 :edge 9))))) -- 7 +(count (query g (find ?x) (where (?x :edge ?y) (not (_ :edge 8))))) -- 0 +(count (query g (find ?x) (where (?x :edge ?y) (not (_ :edge 99))))) -- 7 + +;; §1.4 constant filters over F64 columns match numerically; other types error. +(set pts (table [pts__c0 pts__c1] (list [1 2 3] [1.0 2.0 3.0]))) +(count (query g (find ?x) (where (pts ?x 2)))) -- 1 +(count (query g (find ?x) (where (pts ?x 2.0)))) -- 1 +(at (at (query g (find ?x) (where (pts ?x 2.0))) '?x) 0) -- 2 +(count (query g (find ?x) (where (pts ?x 7)))) -- 0 +;; review follow-up: an F64 literal against an I64 EDB column must also +;; match numerically (dl_col_eq_row's `col->type == RAY_I64 && +;; const_type == RAY_F64` branch) -- the assertions above only exercise +;; F64/I64 literals against an F64 column. +(set ints (table [ints__c0 ints__c1] (list [1 2 3] [10 20 30]))) +(count (query g (find ?x) (where (ints ?x 20.0)))) -- 1 +(at (at (query g (find ?x) (where (ints ?x 20.0))) '?x) 0) -- 2 +(count (query g (find ?x) (where (ints ?x 21.0)))) -- 0 +(set strs (table [strs__c0 strs__c1] (list [1 2] ["a" "b"]))) +;; ray_fmt() only renders a RAY_ERROR's 7-byte code, not the detail text +;; ray_error() stashes in the thread-local buffer, so the visible text is +;; "error: domain" (query: evaluation failed wraps the inner "type" error +;; from dl_filter_eq as "domain") -- matches the existing `query: ... !- +;; domain` idiom used elsewhere for evaluation failures, e.g. +;; datalog_branch_cov.rfl:274. +(query g (find ?x) (where (strs ?x 1))) !- domain + +;; §1.6 a find clause wider than DL_MAX_ARITY (16) errors instead of truncating. +(set w (datoms)) +(set w (assert-fact w 1 'a 1)) +(count (key (query w (find ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n ?o ?p) (where (?a :a ?b) (?a :a ?c) (?a :a ?d) (?a :a ?e) (?a :a ?f) (?a :a ?g) (?a :a ?h) (?a :a ?i) (?a :a ?j) (?a :a ?k) (?a :a ?l) (?a :a ?m) (?a :a ?n) (?a :a ?o) (?a :a ?p))))) -- 16 +(query w (find ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n ?o ?p ?q) (where (?a :a ?b))) !- domain +;; §7.3 an unknown relation is an error, not an empty result. +(query g (find ?x) (where (nosuch ?x))) !- domain +(query g (find ?x) (where (?x :edge ?y) (not (nosuch ?x)))) !- domain + +;; §2.1 repeated queries with an arithmetic expression must not grow the heap. +(set ld (datoms)) +(set ld (assert-fact ld 1 'v 1)) +(set ld (assert-fact ld 2 'v 2)) +(set lq (fn [i] (count (query ld (find ?e ?y) (where (?e :v ?x) (= ?y (+ ?x 1))))))) +(map lq (til 50)) +;; `(set lb0 ...)` permanently retains its own boxed result -- a fixed cost +;; unrelated to the datalog query loop below -- which would bias a single +;; capture against every later comparison. Re-binding lb0 a second time +;; replaces that box with an identically-sized one: the old box's release +;; and the new box's allocation net to zero, so this second, self-paid +;; capture is the true zero-cost baseline (verified empirically: a single +;; capture reads a nonzero, non-scaling residual on every later read no +;; matter how many throw-away reads precede it; re-binding the same name +;; converges to exactly 0). +(set lb0 (get (.sys.mem) 'bytes-allocated)) +(set lb0 (get (.sys.mem) 'bytes-allocated)) +(map lq (til 200)) +(- (get (.sys.mem) 'bytes-allocated) lb0) -- 0 + +;; §2.2 integer overflow and division by zero are null, never undefined behaviour. +(set ad (datoms)) +(set ad (assert-fact ad 1 'v 1)) +(at (at (query ad (find ?y) (where (?e :v ?x) (= ?y (+ ?x 9223372036854775807)))) '?y) 0) -- 0Nl +(at (at (query ad (find ?y) (where (?e :v ?x) (= ?y (* ?x -9223372036854775807)))) '?y) 0) -- -9223372036854775807 +(at (at (query ad (find ?y) (where (?e :v ?x) (= ?y (/ ?x 0)))) '?y) 0) -- 0Nl +(at (at (query ad (find ?y) (where (?e :v ?x) (= ?y (- ?x 3)))) '?y) 0) -- -2 + +;; §1.5 a symbol value and an integer equal to its intern id are different values. +(set sd (datoms)) +(set sd (assert-fact sd 1 'name 'Alice)) +(set sid (get (pull sd 1) 'name)) +(set sd (assert-fact sd 2 'name sid)) +(count (query sd (find ?e) (where (?e :name 'Alice)))) -- 1 +(at (at (query sd (find ?e) (where (?e :name 'Alice))) '?e) 0) -- 1 +(count (query sd (find ?e) (where (?e :name sid)))) -- 1 +(at (at (query sd (find ?e) (where (?e :name sid))) '?e) 0) -- 2 +;; user-visible reads still return plain intern ids +(sym-name (at (at (query sd (find ?n) (where (1 :name ?n))) '?n) 0)) -- 'Alice +(sym-name (get (pull sd 1) 'name)) -- 'Alice +;; a "foo" STR literal means the symbol named "foo" (assert-fact only ever +;; stores an integer or a symbol), so it matches the SYM-tagged cell too. +(count (query sd (find ?e) (where (?e :name "Alice")))) -- 1 +(set sd (retract-fact sd 1 'name 'Alice)) +(count (query sd (find ?e) (where (?e :name 'Alice)))) -- 0 +(count sd) -- 1 + +;; §1.5 a hand-built datoms table whose v column is a genuine RAY_SYM +;; vector (not assert-fact's DATOM-tagged I64 encoding) must still match +;; a SYM/STR literal -- ray_query_fn tags column 2 the same way when +;; converting a RAY_SYM v column to I64. A *legacy* I64 v column holding +;; bare (untagged) sym ids stays deliberately unmatched by strict_tag: +;; that bare-integer ambiguity is exactly what tagging removes. +(set handbuilt (table ['e 'a 'v] (list [1 2] ['name 'name] ['Alice 'Bob]))) +(count (query handbuilt (find ?e) (where (?e :name 'Alice)))) -- 1 +(sym-name (at (at (query handbuilt (find ?v) (where (1 :name ?v))) '?v) 0)) -- 'Alice diff --git a/test/rfl/datalog/datalog_branch_cov.rfl b/test/rfl/datalog/datalog_branch_cov.rfl index 39c1626e1..a6cb342d2 100644 --- a/test/rfl/datalog/datalog_branch_cov.rfl +++ b/test/rfl/datalog/datalog_branch_cov.rfl @@ -117,14 +117,16 @@ (sum (at (query Db (find ?e ?y) (where (?e :val ?x) (= ?y (+ ?x 0.5)) (> ?y 20.0))) '?y)) -- 51.0 ;; ════════════════════════ integer division by zero in expressions ═════════════════════════ -;; Exercises the rd[r] != 0 ? ... : 0 branch in i64 binop path (line 748). -;; Division by 0 → result is 0 for each row; ?y = 0 for all 3 rows. +;; Exercises the (b == 0 || ...) ? NULL_I64 : a / b branch in the i64 binop path. +;; §2.2: division by 0 is null, matching the host `/`; ?y = 0Nl for all 3 rows, +;; and sum() over an all-null i64 column is null. (count (query Db (find ?e ?y) (where (?e :val ?x) (= ?y (/ ?x 0))))) -- 3 -(sum (at (query Db (find ?e ?y) (where (?e :val ?x) (= ?y (/ ?x 0)))) '?y)) -- 0 +(sum (at (query Db (find ?e ?y) (where (?e :val ?x) (= ?y (/ ?x 0)))) '?y)) -- 0Nl -;; Exercises the rd[r] != 0.0 ? ... : 0.0 branch in f64 binop path (line 725). +;; §2.2: f64 division by zero follows IEEE (matches the host `/`): ?x/0.0 -> +inf +;; for each row, and sum() of all-+inf collapses to NaN (formats as 0Nf). (count (query Db (find ?e ?y) (where (?e :val ?x) (= ?y (/ ?x 0.0))))) -- 3 -(sum (at (query Db (find ?e ?y) (where (?e :val ?x) (= ?y (/ ?x 0.0)))) '?y)) -- 0.0 +(sum (at (query Db (find ?e ?y) (where (?e :val ?x) (= ?y (/ ?x 0.0)))) '?y)) -- 0Nf ;; ════════════════════════ f64 subtraction, multiplication, division in expressions ═════════════════════════ ;; - ?x 0.5: {9.5, 19.5, 29.5}; > 10.0 keeps {19.5, 29.5} = 49.0. @@ -212,8 +214,9 @@ (count (query Empty (find ?n) (where (zero-count ?n)) (rules ((zero-count ?n) (count ?n empty_src))))) -- 1 ;; ════════════════════════ query with inline rules — body references unknown predicate ═════════════════════════ +;; nonexistent-rel resolves to no relation at all — admission error, not empty (audit §7.3). (set Db (datoms)) -(count (query Db (find ?x) (where (phantom ?x)) (rules ((phantom ?x) (nonexistent-rel ?x))))) -- 0 +(query Db (find ?x) (where (phantom ?x)) (rules ((phantom ?x) (nonexistent-rel ?x)))) !- domain ;; ════════════════════════ neg with no shared keys (n_keys==0) ═════════════════════════ (set Db (datoms)) @@ -366,12 +369,12 @@ (at (at (query Db (find ?s) (where (asum ?s)) (rules ((asum ?s) (sum ?s agg_env 1)))) '?s) 0) -- 100 ;; ════════════════════════ dl_find_rel returns -1 for unknown body pred ═════════════════════════ -;; Exercises line 1297 (rel_idx < 0 => return NULL) in dl_compile_rule. ;; When a positive body atom references a predicate unknown to the program, -;; compile_rule returns NULL silently (no eval_err, just 0 rows). +;; the admission check now rejects it up front (audit §7.3), instead of +;; compile_rule silently returning NULL (no eval_err, just 0 rows). (set Db (datoms)) (set Db (assert-fact Db 1 'tag 'x)) -(count (query Db (find ?e) (where (uses-unknown ?e)) (rules ((uses-unknown ?e) (no-such-pred ?e ?v))))) -- 0 +(query Db (find ?e) (where (uses-unknown ?e)) (rules ((uses-unknown ?e) (no-such-pred ?e ?v)))) !- domain ;; ════════════════════════ table_antijoin: left empty ═════════════════════════ ;; Exercises the ray_table_nrows(left)==0 early return in table_antijoin (line 2368). diff --git a/test/rfl/datalog/datalog_coverage.rfl b/test/rfl/datalog/datalog_coverage.rfl index c498f99a3..413b2b858 100644 --- a/test/rfl/datalog/datalog_coverage.rfl +++ b/test/rfl/datalog/datalog_coverage.rfl @@ -303,8 +303,9 @@ ;; body shape guards — non-list body clause (query Db (find ?e) (where 1)) !- type -;; reference to unknown predicate at eval time — empty result, not error -(count (query Db (find ?e) (where ('weird ?e)))) -- 0 +;; reference to unknown predicate at eval time is now an admission error, +;; not an empty result (audit §7.3). +(query Db (find ?e) (where ('weird ?e))) !- domain ;; ════════════════════════ empty-result schema preservation (4201-4211) ═════════════════════════ ;; Even when the result is empty, the schema must reflect the find vars. @@ -353,9 +354,10 @@ (asc (at qPairs '?l)) -- [1 2 3] (asc (at qPairs '?r)) -- [10 20 30] -;; reference relation with arity-mismatch — not registered, 0 rows. +;; reference relation with arity-mismatch — not registered, so `tri` is now +;; an unknown relation (admission error, not 0 rows; audit §7.3). (set tri (table ['a 'b 'c] (list [1] [2] [3]))) -(count (query Db2 (find ?x ?y) (where (tri ?x ?y)))) -- 0 +(query Db2 (find ?x ?y) (where (tri ?x ?y))) !- domain ;; env-backed table whose 2nd column is RAY_SYM (auto-converted to I64 via ;; ray_read_sym branch — lines 4120-4140). @@ -412,8 +414,11 @@ (count (query Edb (find ?e) (where (gi ?e)) (rules ((gi ?e) (?e :age (+ 10 20)))))) -- 1 ;; (first ['admin 'user]) → sym 'admin ; matches entity 1's role. (count (query Edb (find ?e) (where (gs ?e)) (rules ((gs ?e) (?e :role (first ['admin 'user])))))) -- 1 -;; evaluates to a float → unsupported constant type in body. -(query Edb (find ?e) (where (gb ?e)) (rules ((gb ?e) (?e :age (+ 1.0 2.0))))) !- type +;; evaluates to a float → F64 body constants are now supported (audit +;; §1.4, task 4): compares numerically against the I64 age column, and +;; 3.0 matches neither entity's age, so the result is empty rather than +;; an error. +(count (query Edb (find ?e) (where (gb ?e)) (rules ((gb ?e) (?e :age (+ 1.0 2.0)))))) -- 0 ;; ════════════════════════ recursive rule via inline rules (no globals) ═════════════════════════ ;; Chain 1→2→3→4: TC pairs = (1,2),(1,3),(1,4),(2,3),(2,4),(3,4) — 6 rows. diff --git a/test/rfl/group/distinct_zero_agg_vla.rfl b/test/rfl/group/distinct_zero_agg_vla.rfl new file mode 100644 index 000000000..41e0dac54 --- /dev/null +++ b/test/rfl/group/distinct_zero_agg_vla.rfl @@ -0,0 +1,20 @@ +;; distinct_zero_agg_vla.rfl — table `distinct` is a grouped plan with no +;; aggregates (#515). +;; +;; Regression: once the input is large enough to take the hash group path, +;; exec_group_run sized its agg result scratch as `agg_outs[n_aggs]` with +;; n_aggs == 0. A zero-length VLA is undefined behaviour; the release build +;; tolerated it and answered correctly, the sanitized debug build aborted with +;; "variable length array bound evaluates to non-positive value 0". The +;; reported shape is a STR key column at 100,000 rows / 9,000 distinct values. +(set N 100000) +(set x (til N)) +(set m (- x (* 9000 (div x 9000)))) +(set sk (map (fn [i] (concat "acct" (as 'str i))) (til 9000))) +(set s (at sk m)) +(count (distinct (table ['a] (list s)))) -- 9000 + +;; Same zero-aggregate path with a SYM key and with a two-column key. +(set ss (as 'sym s)) +(count (distinct (table ['a] (list ss)))) -- 9000 +(count (distinct (table ['a 'b] (list s (- x (* 7 (div x 7))))))) -- 63000 diff --git a/test/rfl/integration/attributes.rfl b/test/rfl/integration/attributes.rfl index 41adfd0b6..f111784d9 100644 --- a/test/rfl/integration/attributes.rfl +++ b/test/rfl/integration/attributes.rfl @@ -70,8 +70,10 @@ (.idx.has? (reverse (.attr.set 'grouped [1 1 2 3 3]))) -- false ;; concat of a sorted column with more data drops the marker (.attr.get (concat (.attr.set 'sorted [1 2 3]) [0 1])) -- (take ['a] 0) -;; concat of a grouped column drops the backing index -(.idx.has? (concat (.attr.set 'grouped [1 1 2 3 3]) [4 5])) -- false +;; concat of a grouped column carries the backing index when every appended +;; key is new (see ops/idx_find_in.rfl); a repeated key drops it +(.idx.has? (concat (.attr.set 'grouped [1 1 2 3 3]) [4 5])) -- true +(.idx.has? (concat (.attr.set 'grouped [1 1 2 3 3]) [3 4])) -- false ;; where-filtered selection off a sorted column drops the marker (.attr.get (at (.attr.set 'sorted [1 2 3 4 5]) (where [true false true false true]))) -- (take ['a] 0) ;; a plain rebind PRESERVES the marker (trivially-preserving) diff --git a/test/rfl/ops/i64_exact_ordering.rfl b/test/rfl/ops/i64_exact_ordering.rfl new file mode 100644 index 000000000..8b2fecdcf --- /dev/null +++ b/test/rfl/ops/i64_exact_ordering.rfl @@ -0,0 +1,76 @@ +;; Integers above 2^53 are ordered and combined exactly (issue #524). +;; +;; A double is exact only to 2^53. Atom ordering (<, >, <=, >= and the +;; dyadic min/max built on them) went through as_f64, and the integer-output +;; arms of the vector-with-vector kernel read each operand as a double before +;; the integer op — so the answer depended on the SHAPE of the operands: +;; right against a constant, wrong against a column. Every TIMESTAMP is such +;; an integer (nanoseconds, ~8.4e17, double spacing 128 ns). + +(set P53 9007199254740992) +(set Q (+ P53 1)) +(set P62 (* 2147483648 2147483648)) +(set R (concat (enlist (- P62 1)) (concat (enlist P62) (enlist (+ P62 1))))) +(set t0 2026.08.13D10:00:00.001) +(set C (concat (enlist t0) (concat (enlist (+ t0 1000000)) (enlist (+ t0 2000000))))) +(set D (+ C 1000000)) + +;; ── atoms: ordering agrees with == ────────────────────────────────────────── +(> Q P53) -- true +(< P53 Q) -- true +(>= P53 Q) -- false +(<= Q P53) -- false +(>= Q P53) -- true +(== Q P53) -- false +(min Q P53) -- P53 +(max P53 Q) -- Q +(> (enlist Q) P53) -- [true] +;; narrower integer atoms take the same exact path +(> Q (as 'i32 5)) -- true +(< (as 'i16 -5) Q) -- true +;; a float operand keeps the double compare (exact for these values) +(> 1.5 1) -- true +(< 1 1.5) -- true +(> true false) -- true + +;; ── vector with vector: each operand read exactly ─────────────────────────── +(> (take Q 3) (take P53 3)) -- [true true true] +(< (take P53 3) (take Q 3)) -- [true true true] +(>= (take P53 3) (take Q 3)) -- [false false false] +(== R (take P62 3)) -- [false true false] +(!= R (take P62 3)) -- [true false true] +(< R (take P62 3)) -- [true false false] +(> R (take P62 3)) -- [false false true] +(+ R (take 0 3)) -- R +(- R (take 0 3)) -- R +(* R (take 1 3)) -- R +(+ R (til 3)) -- (concat (enlist (- P62 1)) (concat (enlist (+ P62 1)) (enlist (+ P62 3)))) +(- R (til 3)) -- (concat (enlist (- P62 1)) (concat (enlist (- P62 1)) (enlist (- P62 1)))) +(% R (take 1000 3)) -- [903 904 905] +(min R (take P62 3)) -- (concat (enlist (- P62 1)) (concat (enlist P62) (enlist P62))) +(max R (take P62 3)) -- (concat (enlist P62) (concat (enlist P62) (enlist (+ P62 1)))) +(div R (take 1 3)) -- R +;; mixed widths: an I32 column against an I64 column stays exact +(+ (take Q 3) (as 'i32 [1 2 3])) -- (concat (enlist (+ Q 1)) (concat (enlist (+ Q 2)) (enlist (+ Q 3)))) +(> (take Q 3) (as 'i32 [1 2 3])) -- [true true true] + +;; ── timestamps: nanosecond arithmetic and ordering ────────────────────────── +(- D C) -- [1000000 1000000 1000000] +(> (take (+ t0 2) 3) (take (+ t0 1) 3)) -- [true true true] +(== (take (+ t0 1) 3) (take (+ t0 1) 3)) -- [true true true] +(!= (take (+ t0 2) 3) (take (+ t0 1) 3)) -- [true true true] +(> (+ t0 2) (+ t0 1)) -- true +(min (+ t0 2) (+ t0 1)) -- (+ t0 1) + +;; ── unchanged shapes stay exact: vector with atom, reductions ─────────────── +(> (take Q 3) P53) -- [true true true] +(> R P62) -- [false false true] +(+ R 0) -- R +(max R) -- (+ P62 1) +(- (+ t0 1000000) t0) -- 1000000 + +;; ── nulls and floats through the same arms are unchanged ──────────────────── +(+ [1 0N 3] [1 1 1]) -- [2 0N 4] +(> [1 0N 3] [0 0 0]) -- [true false true] +(+ [1.5 2.5] [1 1]) -- [2.5 3.5] +(> [1.5 2.5] [1 3]) -- [true false] diff --git a/test/rfl/ops/idx_find_in.rfl b/test/rfl/ops/idx_find_in.rfl new file mode 100644 index 000000000..be8884346 --- /dev/null +++ b/test/rfl/ops/idx_find_in.rfl @@ -0,0 +1,154 @@ +;; Vector-needle find / in / dict lookup against an attached hash index, the +;; STR hash attach, and the index carried across concat (issue #519). +;; +;; Every indexed answer is cross-checked against the same call on the plain +;; vector (drop-differential): positions, duplicates, misses → null. The +;; index is consulted by find / in / at directly on the vector, so no query +;; wrapper is needed to reach the routing site. + +;; ─────────────────────────── I64: find / in with a vector of needles ──────── +(set hi [10 20 30 10 50 10 70 10 90 100]) ;; 10 repeats: first at row 0 +(set gi (.attr.set 'grouped hi)) +(.attr.get gi) -- ['grouped] +(find gi [50 10 999 100 10]) -- [4 0 0N 9 0] +(find gi [50 10 999 100 10]) -- (find hi [50 10 999 100 10]) +(find gi [999]) -- [0N] +(find gi []) -- (find hi []) +(in [50 999 10] gi) -- [true false true] +(in [50 999 10] gi) -- (in [50 999 10] hi) +;; narrower needles probe the same keys; a float needle keeps the scan path +(find gi (as 'i32 [30 31])) -- (find hi (as 'i32 [30 31])) +(find gi [30.0 31.5]) -- (find hi [30.0 31.5]) +;; scalar find still answers through the index +(find gi 70) -- 6 +(find gi 71) -- 0N +;; unique marker on top of grouped: the same probes +(set ui (.attr.set 'unique (.attr.set 'grouped [5 6 7 8]))) +(.attr.get ui) -- ['unique 'grouped] +(find ui [8 5 9]) -- [3 0 0N] +(in [8 9] ui) -- [true false] + +;; ─────────────────────────── the needle side hashed when smaller ─────────── +;; no index: fewer needles than rows hashes the needles and scans once — the +;; answers (first occurrence, duplicates, misses, null needle) are unchanged +(set big (concat (til 1000) [7 7 7])) +(find big [7 999 1002 5000 7]) -- [7 999 0N 0N 7] +(find big [0N 3]) -- [0N 3] +(set bn (concat [1 0N 2] (til 500))) +(find bn [0N 2 499]) -- [1 2 502] +(in [7 5000 0] big) -- [true false true] +(in [0N 2] bn) -- [true true] + +;; ─────────────────────────── SYM: same domain and a different one ────────── +(set hs ['a 'b 'a 'c 'a 'b]) +(set gs (.attr.set 'grouped hs)) +(find gs ['c 'a 'z 'b]) -- [3 0 0N 1] +(find gs ['c 'a 'z 'b]) -- (find hs ['c 'a 'z 'b]) +(in ['z 'b] gs) -- [false true] +(find gs 'c) -- 3 +(find gs 'z) -- 0N +;; unique now admits SYM +(.attr.get (.attr.set 'unique ['x 'y 'z])) -- ['unique] +(.attr.set 'unique ['x 'y 'x]) !- domain +;; a splayed round trip puts the column in a FILE domain; the needles stay +;; runtime-domain — the probe translates them through the column's domain +(.sys.exec "rm -rf /tmp/rf-idx-find-sym") +(.db.splayed.set "/tmp/rf-idx-find-sym/" (table ['k 'v] (list gs [1 2 3 4 5 6]))) +(set ls (at (.db.splayed.get "/tmp/rf-idx-find-sym/") 'k)) +(.attr.get ls) -- ['grouped] +(find ls ['c 'a 'z 'b]) -- [3 0 0N 1] +(in ['z 'b 'a] ls) -- [false true true] +(find ls 'b) -- 1 + +;; ─────────────────────────── STR: the hash attach is admitted ────────────── +(set hstr ["alpha" "beta" "alpha" "gamma" "delta" "beta"]) +(set gstr (.attr.set 'grouped hstr)) +(.attr.get gstr) -- ['grouped] +(.idx.has? gstr) -- true +(at (.idx.info gstr) 'kind) -- 'hash +(at (.idx.info gstr) 'n_groups) -- 4 +(find gstr ["gamma" "alpha" "zeta" "delta" "beta"]) -- [3 0 0N 4 1] +(find gstr ["gamma" "alpha" "zeta" "delta" "beta"]) -- (find hstr ["gamma" "alpha" "zeta" "delta" "beta"]) +(in ["zeta" "beta" "delta"] gstr) -- [false true true] +(in ["zeta" "beta" "delta"] gstr) -- (in ["zeta" "beta" "delta"] hstr) +(find gstr "gamma") -- 3 +(find gstr "zeta") -- 0N +;; an empty string is the STR null: such a vector keeps the scan semantics +(find (.attr.set 'grouped ["a" "" "b"]) ["" "b" "c"]) -- (find ["a" "" "b"] ["" "b" "c"]) +;; the index rides the vector through ordinary reads +(at gstr 3) -- "gamma" +(count gstr) -- 6 +;; unique on STR: verified, then a marker on the hash +(set ustr (.attr.set 'unique (.attr.set 'grouped ["k1" "k2" "k3"]))) +(.attr.get ustr) -- ['unique 'grouped] +(.attr.set 'unique ["k1" "k2" "k1"]) !- domain +(.attr.get (.attr.set 'unique ["k1" "k2"])) -- ['unique] +;; long (out-of-line) strings hash and compare by their bytes too +(set lstr (.attr.set 'grouped (as 'str (+ 1000000000000000000 (til 300))))) +(find lstr (as 'str [1000000000000000299 1000000000000000000 1000000000000000300])) -- [299 0 0N] +;; a splayed round trip keeps the STR hash +(.sys.exec "rm -rf /tmp/rf-idx-find-str") +(.db.splayed.set "/tmp/rf-idx-find-str/" (table ['k 'v] (list gstr [1 2 3 4 5 6]))) +(set lstr2 (at (.db.splayed.get "/tmp/rf-idx-find-str/") 'k)) +(.attr.get lstr2) -- ['grouped] +(find lstr2 ["gamma" "alpha" "zeta" "delta" "beta"]) -- [3 0 0N 4 1] +(in ["zeta" "beta"] lstr2) -- [false true] + +;; ─────────────────────────── dict lookup through the keys' index ─────────── +(set d (dict gstr [1 2 3 4 5 6])) +(at d "gamma") -- 4 +(at d "zeta") -- 0N +(at d ["gamma" "alpha" "zeta" "beta"]) -- (list 4 1 0N 2) +(at d ["gamma" "alpha" "zeta" "beta"]) -- (at (dict hstr [1 2 3 4 5 6]) ["gamma" "alpha" "zeta" "beta"]) +(set di (dict gi (til 10))) +(at di [50 10 999 100]) -- (list 4 0 0N 9) +(at di [50 10 999 100]) -- (at (dict hi (til 10)) [50 10 999 100]) +(at di 70) -- 6 +(at di 71) -- 0N +;; a dict with list values gathers the same elements +(set dl (dict (.attr.set 'grouped [1 2 3]) (list "one" "two" "three"))) +(at dl [3 1 9]) -- (list "three" "one" 0N) + +;; ─────────────────────────── concat keeps the index for new keys ─────────── +(set c0 (.attr.set 'unique (.attr.set 'grouped [100 200 300]))) +(set c1 (concat c0 [400 500])) +(.attr.get c1) -- ['unique 'grouped] +(count c1) -- 5 +(find c1 [500 100 300 999]) -- [4 0 2 0N] +(find c1 [500 100 300 999]) -- (find [100 200 300 400 500] [500 100 300 999]) +(in [400 999] c1) -- [true false] +;; an atom appended is the same motion +(set c2 (concat c1 600)) +(.attr.get c2) -- ['unique 'grouped] +(find c2 [600 100]) -- [5 0] +;; a repeated key is not carried: the result is a plain vector, as before +(.attr.get (concat c0 [300 700])) -- (.attr.get [1 2]) +(find (concat c0 [300 700]) [300 700]) -- [2 4] +;; grouped without unique: new keys carry, a repeat drops +(.attr.get (concat gi [1 2 3])) -- ['grouped] +(find (concat gi [1 2 3]) [3 10 1]) -- [12 0 10] +(.attr.get (concat gi [10])) -- (.attr.get [1 2]) +;; many appends grow the bucket table past its load factor +(set cg (concat (.attr.set 'grouped (til 5)) (+ 5 (til 2000)))) +(.attr.get cg) -- ['grouped] +(at (.idx.info cg) 'n_groups) -- 2005 +(find cg [0 4 5 2004 2005]) -- [0 4 5 2004 0N] +(find cg [0 4 5 2004 2005]) -- (find (til 2005) [0 4 5 2004 2005]) +(sum (find cg (til 2005))) -- (sum (til 2005)) +;; STR and SYM appends carry too +(set cs (concat gstr ["epsilon"])) +(.attr.get cs) -- ['grouped] +(find cs ["epsilon" "alpha"]) -- [6 0] +(.attr.get (concat gstr ["alpha"])) -- (.attr.get [1 2]) +(set csy (concat gs ['d])) +(.attr.get csy) -- ['grouped] +(find csy ['d 'a 'z]) -- [6 0 0N] +;; a null appended leaves the result unindexed +(.attr.get (concat c0 [0N])) -- (.attr.get [1 2]) +(find (concat c0 [0N]) [0N 300]) -- [3 2] +;; the carried index persists like a built one +(.sys.exec "rm -rf /tmp/rf-idx-find-carry") +(.db.splayed.set "/tmp/rf-idx-find-carry/" (table ['k] (list c1))) +(.attr.get (at (.db.splayed.get "/tmp/rf-idx-find-carry/") 'k)) -- ['unique 'grouped] +(find (at (.db.splayed.get "/tmp/rf-idx-find-carry/") 'k) [500 999]) -- [4 0N] +(.sys.exec "rm -rf /tmp/rf-idx-find-sym /tmp/rf-idx-find-str /tmp/rf-idx-find-carry") diff --git a/test/rfl/ops/idxop_coverage.rfl b/test/rfl/ops/idxop_coverage.rfl index 94a15c4b4..b4542ba6e 100644 --- a/test/rfl/ops/idxop_coverage.rfl +++ b/test/rfl/ops/idxop_coverage.rfl @@ -262,9 +262,10 @@ (.idx.sort ['x 'y]) !- nyi (.idx.bloom ['p 'q]) !- nyi -;; ── string vec also unsupported in v1 ── +;; ── string vec: hash supported (byte-keyed, see ops/idx_find_in.rfl), the rest nyi ── (.idx.zone ["alpha" "beta"]) !- nyi -(.idx.hash ["a" "b"]) !- nyi +(.idx.has? (.idx.hash ["a" "b"])) -- true +(.idx.sort ["a" "b"]) !- nyi ;; ── non-vector input (atom): ray_is_vec -> false -> "type" error ── (.idx.zone 42) !- type diff --git a/test/rfl/system/load_errors.rfl b/test/rfl/system/load_errors.rfl new file mode 100644 index 000000000..f2fdcf822 --- /dev/null +++ b/test/rfl/system/load_errors.rfl @@ -0,0 +1,15 @@ +;; load_errors.rfl — a failing `load` names the file and the OS cause (#505). +;; +;; Regression: ray_load_file_fn returned a bare `io` for every failure, so +;; a missing dependency in a startup script printed `error: io`, which reads +;; like an IPC, journal or storage failure and sent diagnosis the wrong way. +;; The harness compares error codes only, so the message is checked on a +;; subprocess's stderr. +(load "missing/persistent_connection.rfl") !- io +(load "/") !- io +(.sys.exec "rm -rf /tmp/rfl_load_err && mkdir -p /tmp/rfl_load_err && printf '(load \"missing/persistent_connection.rfl\")\n' > /tmp/rfl_load_err/main.rfl") +(.sys.exec "./rayforce /tmp/rfl_load_err/main.rfl &1 | grep -q 'error: io: load \"missing/persistent_connection.rfl\": No such file or directory'") -- 0 +(.sys.exec "printf '(load \"/tmp/rfl_load_err\")\n' > /tmp/rfl_load_err/dir.rfl; ./rayforce /tmp/rfl_load_err/dir.rfl &1 | grep -q 'error: io: load \"/tmp/rfl_load_err\": is a directory'") -- 0 +;; a script that fails to load still exits non-zero +(.sys.exec "./rayforce /tmp/rfl_load_err/main.rfl /dev/null 2>&1; [ $? -ne 0 ]") -- 0 +(.sys.exec "rm -rf /tmp/rfl_load_err") diff --git a/test/rfl/system/load_home.rfl b/test/rfl/system/load_home.rfl new file mode 100644 index 000000000..4ce8575eb --- /dev/null +++ b/test/rfl/system/load_home.rfl @@ -0,0 +1,40 @@ +;; load_home.rfl — relative `load` paths fall back to RAYFORCE_HOME, and +;; (.sys.args) reports the file being evaluated as `source` (#506). +;; +;; Layout: a project at /tmp/rfl_lh/proj and a home at /tmp/rfl_lh/home. +;; proj/main.rfl loads "lib/a.rfl" (only in home) and "lib/b.rfl" +;; (in both: the working directory must win) +;; home/lib/a.rfl records its own `source`, then loads "lib/c.rfl" +;; home/lib/c.rfl records its `source` +;; proj/lib/b.rfl sets b_from 'proj; home/lib/b.rfl sets b_from 'home +;; Each case runs a subprocess from the project directory. +(.sys.exec "rm -rf /tmp/rfl_lh && mkdir -p /tmp/rfl_lh/proj/lib /tmp/rfl_lh/home/lib") +(.sys.exec "printf '%s\n' '(set a_src (at (.sys.args) (quote source)))' '(load \"lib/c.rfl\")' '(set a_src_after (at (.sys.args) (quote source)))' > /tmp/rfl_lh/home/lib/a.rfl") +(.sys.exec "printf '%s\n' '(set c_src (at (.sys.args) (quote source)))' > /tmp/rfl_lh/home/lib/c.rfl") +(.sys.exec "printf '%s\n' '(set b_from (quote home))' > /tmp/rfl_lh/home/lib/b.rfl") +(.sys.exec "printf '%s\n' '(set b_from (quote proj))' > /tmp/rfl_lh/proj/lib/b.rfl") +(.sys.exec "printf '%s\n' '(load \"lib/a.rfl\")' '(load \"lib/b.rfl\")' '(println (str-join (list a_src c_src a_src_after (as (quote str) b_from) (at (.sys.args) (quote source)) (at (.sys.args) (quote file))) \"|\"))' > /tmp/rfl_lh/proj/main.rfl") + +;; home fallback, nested load, source restored after a nested load, +;; working directory wins for b, top-level source == file +(.sys.exec "cd /tmp/rfl_lh/proj && RAYFORCE_HOME=/tmp/rfl_lh/home $OLDPWD/rayforce main.rfl &1 | grep -qx '/tmp/rfl_lh/home/lib/a.rfl|/tmp/rfl_lh/home/lib/c.rfl|/tmp/rfl_lh/home/lib/a.rfl|proj|main.rfl|main.rfl'") -- 0 + +;; a trailing slash on the home is fine +(.sys.exec "cd /tmp/rfl_lh/proj && RAYFORCE_HOME=/tmp/rfl_lh/home/ $OLDPWD/rayforce main.rfl &1 | grep -q '^/tmp/rfl_lh/home/lib/a.rfl|'") -- 0 + +;; without a home the same script fails, naming only the working-directory path +(.sys.exec "cd /tmp/rfl_lh/proj && $OLDPWD/rayforce main.rfl &1 | grep -q 'error: io: load \"lib/a.rfl\": No such file or directory$'") -- 0 + +;; missing in both places: both attempts are named +(.sys.exec "printf '(load \"lib/zz.rfl\")\n' > /tmp/rfl_lh/proj/miss.rfl; cd /tmp/rfl_lh/proj && RAYFORCE_HOME=/tmp/rfl_lh/home $OLDPWD/rayforce miss.rfl &1 | grep -q 'error: io: load \"lib/zz.rfl\": No such file or directory (also tried \"/tmp/rfl_lh/home/lib/zz.rfl\")'") -- 0 + +;; an absolute path never consults the home +(.sys.exec "printf '(load \"/tmp/rfl_lh/nowhere.rfl\")\n' > /tmp/rfl_lh/proj/abs.rfl; cd /tmp/rfl_lh/proj && RAYFORCE_HOME=/tmp/rfl_lh/home $OLDPWD/rayforce abs.rfl &1 | grep -q 'error: io: load \"/tmp/rfl_lh/nowhere.rfl\": No such file or directory$'") -- 0 + +;; under a pipe there is no file: source is empty, and so is file +(.sys.exec "printf '(println (count (at (.sys.args) (quote source))))\n' | ./rayforce -i 2>&1 | grep -qx 0") -- 0 + +;; in-process: this harness runs each .rfl through eval, not load, so +;; source is whatever the harness set — only the key's presence is pinned +(type (at (.sys.args) 'source)) -- 'str +(.sys.exec "rm -rf /tmp/rfl_lh") diff --git a/test/rfl/system/startup_script_fatal.rfl b/test/rfl/system/startup_script_fatal.rfl new file mode 100644 index 000000000..343738563 --- /dev/null +++ b/test/rfl/system/startup_script_fatal.rfl @@ -0,0 +1,14 @@ +;; startup_script_fatal.rfl — a failing startup script under -p is fatal +;; non-interactively (#507). +;; +;; Regression: -p opened the listener before the script, and when the +;; script failed the process printed the error and kept serving the port +;; with none of the script's definitions installed. A supervisor's port +;; check passed and Restart=on-failure never fired. +(.sys.exec "rm -rf /tmp/rfl_ssf && mkdir -p /tmp/rfl_ssf && printf '(load \"does-not-exist.rfl\")\n' > /tmp/rfl_ssf/bad.rfl && printf '(set ok 1)\n' > /tmp/rfl_ssf/good.rfl") +;; bad script: exits 1 within a second and leaves nothing listening +(.sys.exec "s=$(date +%s); ./rayforce -p 19969 /tmp/rfl_ssf/bad.rfl /tmp/rfl_ssf/out 2>&1; rc=$?; e=$(date +%s); grep -q 'error: io' /tmp/rfl_ssf/out && grep -q 'startup script /tmp/rfl_ssf/bad.rfl failed' /tmp/rfl_ssf/out && [ $rc -eq 1 ] && [ $((e-s)) -le 1 ]") -- 0 +(.sys.exec "bash -c '(echo > /dev/tcp/127.0.0.1/19969) 2>/dev/null' && exit 1; exit 0") -- 0 +;; good script: still serves after the script (killed by pid once up) +(.sys.exec "./rayforce -p 19969 /tmp/rfl_ssf/good.rfl /dev/null 2>&1 & echo $! > /tmp/rfl_ssf/pid; for i in $(seq 50); do bash -c '(echo > /dev/tcp/127.0.0.1/19969) 2>/dev/null' && exit 0; sleep 0.1; done; exit 1") -- 0 +(.sys.exec "kill $(cat /tmp/rfl_ssf/pid) 2>/dev/null; rm -rf /tmp/rfl_ssf; true") diff --git a/test/rfl/table/alter.rfl b/test/rfl/table/alter.rfl index ec68f0629..5500c0653 100644 --- a/test/rfl/table/alter.rfl +++ b/test/rfl/table/alter.rfl @@ -22,3 +22,56 @@ (set v [1h 2h 3h]) (alter 'v set 0 99h) v -- [99h 2h 3h] (set v ['a 'b 'c]) (alter 'v set 1 'X) v -- ['a 'X 'c] (set v [true false true]) (alter 'v set 0 false) v -- [false false true] + +;; ── a sole-owned target is amended in place, a shared one is not ──────── +;; alter set used to hand ray_cow a reference it had just retained, so the +;; `rc == 1` test inside could never be true and every write copied the whole +;; vector. Sole ownership is rc == 2 here — the binding's reference and +;; alter's own. What must not change is the observable part: a value another +;; binding can still see is copied before the write, so that binding keeps the +;; value it had. +(set AA [1 2 3 4]) +(set BB AA) +(alter 'AA set 0 99) +AA -- [99 2 3 4] +BB -- [1 2 3 4] + +(set CC (list 1 2 3)) +(set DD CC) +(alter 'CC set 1 88) +CC -- (list 1 88 3) +DD -- (list 1 2 3) + +;; sole owner: the amend lands and nothing else observes it +(set EE [10 20 30]) +(alter 'EE set 2 7) +EE -- [10 20 7] +(alter 'EE set [0 1] 5) +EE -- [5 5 7] + +;; a slice is not ours to write through, so it keeps taking the copy path +(set FF [1 2 3 4 5]) +(set GG (drop FF 2)) +(alter 'GG set 0 42) +GG -- [42 4 5] +FF -- [1 2 3 4 5] + +;; ── a dotted target keeps taking the copy ─────────────────────────────── +;; `ray_env_get` resolves `d.x` to the leaf inside the container, and that +;; leaf usually holds the only reference to itself — so an rc test on it says +;; nothing about whether the container is shared. Writing through it would be +;; seen by every alias of the dict, and env_set_dotted's COW-rebuild of the +;; chain cannot undo a write that already landed. +(set DA (dict ['x] (list (til 3)))) +(set DB DA) +(alter 'DA.x set 0 99) +DA.x -- [99 1 2] +DB.x -- [0 1 2] + +;; a table head is the same resolution, and keeps its previous behaviour: +;; env_set_dotted refuses it, so the amend is discarded rather than applied +(set TA (table [c] (list (til 3)))) +(set TB TA) +(alter 'TA.c set 0 77) +(at TA 'c) -- [0 1 2] +(at TB 'c) -- [0 1 2] diff --git a/test/rfl/table/delete.rfl b/test/rfl/table/delete.rfl new file mode 100644 index 000000000..c4a5cd313 --- /dev/null +++ b/test/rfl/table/delete.rfl @@ -0,0 +1,259 @@ +;; delete.rfl — (delete {from: … where: …}) removes the rows a predicate +;; matches. `from: 't` amends the named table in place and keeps its upsert +;; key map; `from: t` answers with a new table. Both forms evaluate the +;; predicate once and compact the same matched-row list, so they cannot +;; disagree about which rows go. +;; +;; NOTE ON THE TESTS: every case meant to exercise the IN-PLACE path builds +;; its columns with `til` or arithmetic, never from a literal vector. A +;; literal is held by the parse tree, so a table built from one has columns at +;; rc 2 and the gate declines to the copying form — which answers correctly, +;; but is not the path those cases are there to test. The same is true of +;; upsert's in-place path. + +;; ── functional form: a new table, the original untouched ──────────────── +(set dt (table [k v] (list (til 5) (* 10 (til 5))))) +(set dr (delete {from: dt where: (== k 2)})) +(at dr 'k) -- [0 1 3 4] +(at dr 'v) -- [0 10 30 40] +(at dt 'k) -- [0 1 2 3 4] +(count dt) -- 5 + +;; ── in-place form: the binding shrinks, the verb answers with the symbol ─ +(set du (table [k v] (list (til 5) (* 10 (til 5))))) +(delete {from: 'du where: (> k 2)}) -- 'du +(at du 'k) -- [0 1 2] +(at du 'v) -- [0 10 20] +(count du) -- 3 + +;; a leading run, a trailing run and an interior one all compact correctly +(set dl (table [k] (list (til 8)))) +(delete {from: 'dl where: (in k [0 1 4 7])}) +(at dl 'k) -- [2 3 5 6] + +;; ── no match leaves everything alone ──────────────────────────────────── +(set dn (table [k] (list (til 3)))) +(delete {from: 'dn where: (== k 99)}) -- 'dn +(at dn 'k) -- [0 1 2] +(count dn) -- 3 + +;; ── every row can go ──────────────────────────────────────────────────── +(set da (table [k] (list (til 4)))) +(delete {from: 'da where: (>= k 0)}) +(count da) -- 0 + +;; ── row order survives, so a sorted column stays sorted ───────────────── +(set ds (table [k] (list (til 6)))) +(delete {from: 'ds where: (== k 3)}) +(at ds 'k) -- [0 1 2 4 5] +(asc (at ds 'k)) -- [0 1 2 4 5] + +;; ── a string column: descriptors move, the pool they point into does not ─ +(set dstr (table [k s] (list (til 4) (map (fn [i] (concat "row" (as 'str i))) (til 4))))) +(delete {from: 'dstr where: (in k [1 2])}) +(at dstr 'k) -- [0 3] +(format "%s" (at dstr 's)) -- "[\"row0\" \"row3\"]s" + +;; ── a symbol column ───────────────────────────────────────────────────── +(set dsym (table [k s] (list (til 4) (as 'SYM (til 4))))) +(delete {from: 'dsym where: (== k 2)}) +(at dsym 'k) -- [0 1 3] +(format "%s" (at dsym 's)) -- "[0 1 3]s" + +;; ── the key map survives the delete: this is the point of doing it here ── +;; A batch upsert builds the map, the delete patches it, and the next batch +;; has to place both a surviving key (an update) and a deleted one (an append) +;; correctly. Against a map left describing the pre-delete rows, the +;; surviving keys point at the wrong rows and the deleted ones look present. +(set dm (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'dm 1 (table [k v] (list (til 10) (* 10 (til 10))))) +(count dm) -- 10 +(delete {from: 'dm where: (in k [3 7])}) +(count dm) -- 8 +(at dm 'k) -- [0 1 2 4 5 6 8 9] +(upsert 'dm 1 (table [k v] (list [5 3] [555 333]))) +(count dm) -- 9 +(at (at dm 'v) 4) -- 555 +(at (at dm 'k) 8) -- 3 +(at (at dm 'v) 8) -- 333 + +;; ── tombstones and probe chains at a size where collisions are certain ── +;; 200 keys, every third deleted, then all 200 upserted back: the survivors +;; must be found as updates and the deleted ones appended exactly once. A +;; cleared slot instead of a tombstone would truncate the chain it sits in and +;; the keys displaced past it would be appended a second time. +(set dc (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'dc 1 (table [k v] (list (til 200) (take [1] 200)))) +(count dc) -- 200 +(delete {from: 'dc where: (== 0 (% k 3))}) +(count dc) -- 133 +(upsert 'dc 1 (table [k v] (list (til 200) (take [2] 200)))) +(count dc) -- 200 +(sum (at dc 'v)) -- 400 +(count (distinct (at dc 'k))) -- 200 + +;; ── errors ────────────────────────────────────────────────────────────── +(set de (table [k] (list (til 3)))) +(delete {from: de}) !- domain +(delete {from: de where: (== k 1) by: k}) !- domain +(delete {where: (== k 1)}) !- domain +(delete {from: 'no_such_table_for_delete where: (== k 1)}) !- domain +(delete {from: 42 where: (== k 1)}) !- type +(delete de) !- type + + +;; ── edge cases of the map patch ───────────────────────────────────────── +;; The patch walks every row against the ascending deleted list, so a run of +;; adjacent deletions is handled by the same step as a scattered one: `ri` +;; advances per match and whether a gap follows is irrelevant. These pin +;; that, against an independent reference — `select` over the negated +;; predicate, which shares no code with the compaction. +;; +;; The follow-up upsert is deliberately TWO rows, one surviving key and one +;; deleted key. Upserting all N back instead exceeds the map's load factor, +;; which makes ukey_fits refuse and rebuild — and a rebuilt map hides +;; whatever the patch got wrong. A first version of these cases did exactly +;; that and passed with the patch sabotaged. + +;; a run at the start +(set e1 (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'e1 1 (table [k v] (list (til 12) (* 10 (til 12))))) +(delete {from: 'e1 where: (in k [0 1 2])}) +(at e1 'k) -- (at (select {from: (table [k] (list (til 12))) where: (not (in k [0 1 2]))}) 'k) +(at e1 'v) -- [30 40 50 60 70 80 90 100 110] +(upsert 'e1 1 (table [k v] (list [5 1] [55 11]))) +(count e1) -- 10 +(at (at e1 'v) 2) -- 55 +(at (at e1 'k) 9) -- 1 + +;; a run in the middle +(set e2 (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'e2 1 (table [k v] (list (til 12) (* 10 (til 12))))) +(delete {from: 'e2 where: (in k [4 5 6 7])}) +(at e2 'k) -- (at (select {from: (table [k] (list (til 12))) where: (not (in k [4 5 6 7]))}) 'k) +(upsert 'e2 1 (table [k v] (list [9 6] [99 66]))) +(count e2) -- 9 +(at (at e2 'v) 5) -- 99 +(at (at e2 'k) 8) -- 6 + +;; a run at the end +(set e3 (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'e3 1 (table [k v] (list (til 12) (* 10 (til 12))))) +(delete {from: 'e3 where: (>= k 9)}) +(at e3 'k) -- [0 1 2 3 4 5 6 7 8] +(upsert 'e3 1 (table [k v] (list [8 11] [88 111]))) +(count e3) -- 10 +(at (at e3 'v) 8) -- 88 +(at (at e3 'k) 9) -- 11 + +;; two separate runs +(set e4 (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'e4 1 (table [k v] (list (til 14) (* 10 (til 14))))) +(delete {from: 'e4 where: (in k [1 2 3 9 10])}) +(at e4 'k) -- (at (select {from: (table [k] (list (til 14))) where: (not (in k [1 2 3 9 10]))}) 'k) +(upsert 'e4 1 (table [k v] (list [11 2] [111 22]))) +(count e4) -- 10 +(at (at e4 'v) 6) -- 111 +(at (at e4 'k) 9) -- 2 + +;; scattered, every third row. NOT every second: deleting half or more trips +;; the `k * 2 >= nrows0` rule, which drops the map for the next upsert to +;; rebuild — so that shape exercises the rebuild, not the patch. +(set e5 (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'e5 1 (table [k v] (list (til 20) (* 10 (til 20))))) +(delete {from: 'e5 where: (== 0 (% k 3))}) +(at e5 'k) -- [1 2 4 5 7 8 10 11 13 14 16 17 19] +(upsert 'e5 1 (table [k v] (list [13 3] [133 33]))) +(count e5) -- 14 +(at (at e5 'v) 8) -- 133 +(at (at e5 'k) 13) -- 3 + +;; a single row, at each end and in the middle, three patches in a row +(set e6 (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'e6 1 (table [k v] (list (til 12) (* 10 (til 12))))) +(delete {from: 'e6 where: (== k 0)}) +(delete {from: 'e6 where: (== k 11)}) +(delete {from: 'e6 where: (== k 5)}) +(at e6 'k) -- [1 2 3 4 6 7 8 9 10] +(upsert 'e6 1 (table [k v] (list [7 5] [77 55]))) +(count e6) -- 10 +(at (at e6 'v) 5) -- 77 +(at (at e6 'k) 9) -- 5 + +;; repeated deletes with no upsert between them +(set e9 (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'e9 1 (table [k v] (list (til 20) (* 10 (til 20))))) +(delete {from: 'e9 where: (in k [0 1])}) +(delete {from: 'e9 where: (in k [18 19])}) +(delete {from: 'e9 where: (in k [9 10])}) +(at e9 'k) -- [2 3 4 5 6 7 8 11 12 13 14 15 16 17] +(upsert 'e9 1 (table [k v] (list [16 0] [166 0]))) +(count e9) -- 15 +(at (at e9 'v) 12) -- 166 +(at (at e9 'k) 14) -- 0 + +;; a one-row table, and refilling an emptied one +(set e7 (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'e7 1 (table [k v] (list (til 1) (til 1)))) +(delete {from: 'e7 where: (== k 0)}) +(count e7) -- 0 +(upsert 'e7 1 (table [k v] (list [0 1] [7 7]))) +(count e7) -- 2 +(at e7 'k) -- [0 1] + +(set e8 (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'e8 1 (table [k v] (list (til 9) (* 10 (til 9))))) +(delete {from: 'e8 where: (>= k 0)}) +(count e8) -- 0 +(upsert 'e8 1 (table [k v] (list (til 9) (take [7] 9)))) +(count e8) -- 9 +(count (distinct (at e8 'k))) -- 9 + +;; ── `from: 't` rebinds whether or not the gate held ───────────────────── +;; The gate can miss for reasons the caller cannot see — a column at rc 2 +;; because a literal holds it, a second binding on the table, an mmapped or +;; narrow-SYM column. The verb still promises the binding is amended and the +;; symbol comes back; returning the new table instead would leave the binding +;; with all its rows and hand back a value nobody asked for. + +;; literal columns: rc 2, so the copying form runs +(set rb (table [k v] (list [1 2 3 4] [10 20 30 40]))) +(delete {from: 'rb where: (> k 2)}) -- 'rb +(count rb) -- 2 +(at rb 'k) -- [1 2] + +;; a second binding on the table: the gate misses on the table's own rc +(set rc1 (table [k] (list (til 5)))) +(set rc2 rc1) +(delete {from: 'rc1 where: (== k 2)}) -- 'rc1 +(at rc1 'k) -- [0 1 3 4] +(at rc2 'k) -- [0 1 2 3 4] + +;; and the answer matches what the copying form gives for the same predicate +(set rb2 (table [k v] (list [1 2 3 4] [10 20 30 40]))) +(at (delete {from: rb2 where: (> k 2)}) 'k) -- [1 2] +(count rb2) -- 4 + +;; ── a parted table ────────────────────────────────────────────────────── +;; Its columns carry the RAY_PARTED_BASE wrapper and its partition key is +;; RAY_MAPCOMMON, neither of which describes a flat element the compaction +;; could move, so the table is flattened once at entry the way ray_update +;; does it. The in-place path declines a parted table anyway (upsert_col_ok +;; rejects the wrapper), so this only ever feeds the copying form — and with +;; `from: 'p` the binding comes back flat, which is worth knowing. +(.sys.exec "rm -rf /tmp/rfl_delpart") +(.db.splayed.set "/tmp/rfl_delpart/2024.01.01/t/" (table [k v] (list [1 2 3] [10 20 30]))) +(.db.splayed.set "/tmp/rfl_delpart/2024.01.02/t/" (table [k v] (list [4 5 6] [40 50 60]))) +(set dp (.db.parted.get "/tmp/rfl_delpart/" 't)) +(count dp) -- 6 +(at (delete {from: dp where: (in k [2 5])}) 'k) -- [1 3 4 6] +(count dp) -- 6 +(delete {from: 'dp where: (> k 4)}) -- 'dp +(at dp 'k) -- [1 2 3 4] +(at dp 'v) -- [10 20 30 40] +(.sys.exec "rm -rf /tmp/rfl_delpart") + +;; NOT covered: the guard that refuses a column carrying RAY_ATTR_SLICE. No +;; producer reachable from the language puts a slice into a table column — +;; drop/take/select/by all materialise — so the guard is defensive only and +;; cannot be exercised from a .rfl case. diff --git a/test/rfl/table/upsert_inplace.rfl b/test/rfl/table/upsert_inplace.rfl index af0da2a8f..77b9337a3 100644 --- a/test/rfl/table/upsert_inplace.rfl +++ b/test/rfl/table/upsert_inplace.rfl @@ -154,3 +154,159 @@ (at (at big 'sz) 2500) -- -2500 (at (at big 'sz) 7499) -- -7499 (sum (at big 'px)) -- 28121250 + +;; ── the key map now outlives the call, so what invalidates it matters ──── +;; A named table mutated in place keeps its key->row map between upserts +;; instead of rebuilding it over every existing row, which is what made a +;; sequence of batches quadratic in the table size. The cases below pin the +;; answers that a stale map would get wrong; they pass on either engine, and +;; their job is to fail if the map ever outlives what it describes. + +;; Repeated batches: the reused map must place every later key correctly and +;; still recognise a key from an earlier batch as an update, not an append. +(set s (table [k v] (list (take [0] 0) (take [0] 0)))) +(map (fn [i] (upsert 's 1 (table [k v] (list (+ (til 100) (* i 100)) (take [1] 100))))) (til 20)) +(count s) -- 2000 +(sum (at s 'v)) -- 2000 +(upsert 's 1 (table [k v] (list [0 999 1999 2000] [7 7 7 7]))) +(count s) -- 2001 +(at (at s 'v) 0) -- 7 +(at (at s 'v) 999) -- 7 +(at (at s 'v) 1999) -- 7 +(at (at s 'k) 2000) -- 2000 +(at (at s 'v) 2000) -- 7 + +;; An in-place where-update can rewrite a key cell without moving the row +;; count, which is exactly what the map's staleness check cannot see. Every +;; upsert here carries two rows on purpose: a one-row upsert never builds a +;; map at all, so a single-row batch would test nothing. Against a map left +;; behind by the update, key 99 is absent and appends a second copy of a key +;; the table already holds. +(set u (table [k v] (list [1 2 3 4] [10 20 30 40]))) +(upsert 'u 1 (table [k v] (list [5 6] [50 60]))) +(count u) -- 6 +(update {from: 'u k: 99 where: (== k 2)}) +(count u) -- 6 +(upsert 'u 1 (table [k v] (list [99 7] [990 70]))) +(count u) -- 7 +(at (at u 'v) 1) -- 990 +(at (at u 'k) 6) -- 7 + +;; An insert between upserts moves the row count, so the map must be rebuilt +;; rather than trusted: the inserted key is an update, not a duplicate. +(set n (table [k v] (list [1 2] [10 20]))) +(upsert 'n 1 (table [k v] (list [3 6] [30 60]))) +(insert 'n (list 4 40)) +(upsert 'n 1 (table [k v] (list [4 5] [444 50]))) +(count n) -- 6 +(at (at n 'v) 4) -- 444 + +;; The same table upserted on a different key width must not reuse a map +;; built for the other key. +(set w (table [a b v] (list [1 1 2] [1 2 1] [10 20 30]))) +(upsert 'w 2 (table [a b v] (list [1 3] [2 3] [200 330]))) +(count w) -- 4 +(at (at w 'v) 1) -- 200 +(upsert 'w 1 (table [a b v] (list [2] [9] [900]))) +(count w) -- 4 +(at (at w 'v) 2) -- 900 +;; with a one-column key `b` is no longer part of it, so the matched row +;; takes the batch's b as an ordinary non-key update +(at (at w 'b) 2) -- 9 + +;; A refused batch leaves the table untouched and the next one still lands +;; correctly. The refusal happens in the type check, before the map is built, +;; so this pins the observable behaviour rather than the map's own rollback — +;; that needs a mid-append failure, which RFL cannot provoke. +(set f (table [k v] (list [1 2] [10 20]))) +(upsert 'f 1 (table [k v] (list [3 4] [30 40]))) +(count f) -- 4 +(upsert 'f 1 (list [5 6] (list 50 'bad))) !- type +(count f) -- 4 +(upsert 'f 1 (table [k v] (list [5 3] [50 333]))) +(count f) -- 5 +(at (at f 'v) 2) -- 333 +(at (at f 'k) 4) -- 5 + +;; A single row rides the same map now, so it has to maintain it: an appended +;; row the map never learns about is invisible to the next batch, which then +;; appends a second copy of a key the table already holds. +(set x (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'x 1 (table [k v] (list [1 2 3] [10 20 30]))) +(upsert 'x 1 (table [k v] (list (enlist 4) (enlist 40)))) +(count x) -- 4 +(upsert 'x 1 (table [k v] (list (enlist 2) (enlist 222)))) +(count x) -- 4 +(at (at x 'v) 1) -- 222 +(upsert 'x 1 (table [k v] (list [4 5] [444 50]))) +(count x) -- 5 +(at (at x 'v) 3) -- 444 +(at (at x 'k) 4) -- 5 + +;; An update that writes no key column leaves the key->row mapping exactly as +;; it was, so the map is kept rather than dropped; one that writes a key +;; column still has to drop it, which the `u` case above pins. +(set q (table [k v] (list [1 2 3] [10 20 30]))) +(upsert 'q 1 (table [k v] (list [4 5] [40 50]))) +(count q) -- 5 +(update {from: 'q v: 99 where: (== k 2)}) +(count q) -- 5 +(at (at q 'v) 1) -- 99 +(upsert 'q 1 (table [k v] (list [2 6] [222 60]))) +(count q) -- 6 +(at (at q 'v) 1) -- 222 +(at (at q 'k) 5) -- 6 + +;; ── a key wider than the map's arm must drop the map, not skip it ─────── +;; RAY_UKEY_MAX_COLS is 8. A wider key gets no map, but an already attached +;; one cannot simply be left alone: the call still writes every non-key column +;; of a matched row in place, and those may be the attached map's key columns. +;; With no row appended the row count does not move either, so the staleness +;; check would accept it as fresh and the next upsert would answer from rows +;; that no longer hold the keys it recorded — appending a duplicate. +(set w9 (table [c1 c2 c3 c4 c5 c6 c7 c8 c9 key] (list (til 3) (til 3) (til 3) (til 3) (til 3) (til 3) (til 3) (til 3) (til 3) (* 10 (til 3))))) +(upsert 'w9 'key (table [key] (list [0 10]))) +(count w9) -- 3 +(upsert 'w9 9 (table [c1 c2 c3 c4 c5 c6 c7 c8 c9 key] (list (enlist 0) (enlist 0) (enlist 0) (enlist 0) (enlist 0) (enlist 0) (enlist 0) (enlist 0) (enlist 0) (enlist 999)))) +(count w9) -- 3 +(at w9 'key) -- [999 10 20] +(upsert 'w9 'key (table [key c1] (list (enlist 999) (enlist 777)))) +(count w9) -- 3 +(at w9 'c1) -- [777 1 2] + +;; ── .idx.drop on a table carrying the key map ─────────────────────────── +;; ray_index_drop COWs its target first, and ray_alloc_copy deliberately does +;; not carry a table's key map to the copy — so the copy has no index left to +;; detach. Reading it anyway dereferenced NULL. +(set idt (table [k v] (list (til 5) (* 2 (til 5))))) +(upsert 'idt 1 (table [k v] (list [5 6] [50 60]))) +(.idx.has? idt) -- true +(count (.idx.drop idt)) -- 7 +(count idt) -- 7 + +;; ── .mem.objsize counts a mapped table's columns, not just its map ────── +;; The HAS_INDEX arm returned early, which was harmless while only vectors +;; could carry an index; a table reported as nothing but its map came out +;; smaller than the same table without one. +(set osa (table [k v] (list (til 20000) (* 2 (til 20000))))) +(set osb (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'osb 1 (table [k v] (list (til 20000) (* 2 (til 20000))))) +(.idx.has? osb) -- true +(> (.mem.objsize osb) (.mem.objsize osa)) -- true + +;; ── a copied table does not carry the original's key map ──────────────── +;; ray_alloc_copy clears it deliberately: the map records the row count it +;; describes and upsert mutates it in place, so two tables sharing one would +;; each write their own count into it. The observable consequence is that a +;; second binding keeps its own rows — the second upsert here declines the +;; in-place path (the table is at rc 3) and works on a private copy. +(set cwA (table [k v] (list (take [0] 0) (take [0] 0)))) +(upsert 'cwA 1 (table [k v] (list (til 3) (* 10 (til 3))))) +(.idx.has? cwA) -- true +(set cwB cwA) +(upsert 'cwA 1 (table [k v] (list [3] [30]))) +(upsert 'cwB 1 (table [k v] (list [4] [40]))) +(at cwA 'k) -- [0 1 2 3] +(at cwB 'k) -- [0 1 2 4] +(at cwA 'v) -- [0 10 20 30] +(at cwB 'v) -- [0 10 20 40] diff --git a/test/test_datalog.c b/test/test_datalog.c index 70e66c3d5..d4cd9e448 100644 --- a/test/test_datalog.c +++ b/test/test_datalog.c @@ -36,6 +36,10 @@ #include /* abort in datalog_rf_setup */ #include +/* ray_error_msg() isn't in the public surface — src/ops/datalog.c + * itself reaches it the same way (see its own `extern` near the top). */ +extern const char* ray_error_msg(void); + /* Full-runtime fixtures use the public runtime API from . */ static void datalog_setup(void) { @@ -2014,6 +2018,40 @@ static test_result_t test_eval_surfaces_compile_failure(void) { PASS(); } +/* Admission errors: a `find` clause wider than DL_MAX_ARITY (16) must be + * rejected instead of silently truncated, and a body predicate that + * resolves to no relation at all (not an EDB, env-bound table, or rule + * head) must be an error instead of an empty result. Audit §1.6, §7.3. */ +static test_result_t test_query_admission_errors(void) { + ray_t* db = ray_eval_str( + "(do (set __qae_db (datoms)) (set __qae_db (assert-fact __qae_db 1 'a 1)))"); + TEST_ASSERT_NOT_NULL(db); + TEST_ASSERT_TRUE(!RAY_IS_ERR(db)); + ray_release(db); + + /* (a) 17 find variables exceeds DL_MAX_ARITY (16). */ + ray_t* r_wide = ray_eval_str( + "(query __qae_db (find ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n ?o ?p ?q) " + " (where (?a :a ?b)))"); + TEST_ASSERT_NOT_NULL(r_wide); + TEST_ASSERT_TRUE(RAY_IS_ERR(r_wide)); + const char* msg_wide = ray_error_msg(); + TEST_ASSERT_NOT_NULL(msg_wide); + TEST_ASSERT_TRUE(strstr(msg_wide, "find supports at most 16 variables") != NULL); + ray_error_free(r_wide); + + /* (b) unknown relation referenced in the body. */ + ray_t* r_unk = ray_eval_str("(query __qae_db (find ?x) (where (nosuch ?x)))"); + TEST_ASSERT_NOT_NULL(r_unk); + TEST_ASSERT_TRUE(RAY_IS_ERR(r_unk)); + const char* msg_unk = ray_error_msg(); + TEST_ASSERT_NOT_NULL(msg_unk); + TEST_ASSERT_TRUE(strstr(msg_unk, "unknown relation 'nosuch'") != NULL); + ray_error_free(r_unk); + + PASS(); +} + /* ray_release() is a deliberate no-op for RAY_ERROR objects, so callers * that claim to be "releasing" an error under the refcount API actually * leak the block. ray_error_free() is the escape hatch that calls @@ -2470,10 +2508,213 @@ static test_result_t test_edb_over_arity_domain_guard(void) { PASS(); } +/* Audit §1.1: p(X,Z) :- p(X,Y), p(Y,Z) over a 7-edge chain must produce the + * same 28 pairs as the linear formulation. The old fixpoint loop swapped the + * whole relation for its delta, so both body occurrences of `p` read the + * delta and old×new combinations were never joined. */ +static test_result_t test_nonlinear_closure_chain(void) { + int64_t src[7], dst[7]; + for (int i = 0; i < 7; i++) { src[i] = i + 1; dst[i] = i + 2; } + ray_t* c0 = ray_vec_from_raw(RAY_I64, src, 7); + ray_t* c1 = ray_vec_from_raw(RAY_I64, dst, 7); + ray_t* edge = ray_table_new(2); + edge = ray_table_add_col(edge, ray_sym_intern("edge__c0", 8), c0); + edge = ray_table_add_col(edge, ray_sym_intern("edge__c1", 8), c1); + + dl_program_t* prog = dl_program_new(); + TEST_ASSERT_NOT_NULL(prog); + TEST_ASSERT_EQ_I(dl_add_edb(prog, "edge", edge, 2), 0); + + dl_rule_t r1; /* p(X,Y) :- edge(X,Y) */ + dl_rule_init(&r1, "p", 2); + dl_rule_head_var(&r1, 0, 0); dl_rule_head_var(&r1, 1, 1); + int b = dl_rule_add_atom(&r1, "edge", 2); + dl_body_set_var(&r1, b, 0, 0); dl_body_set_var(&r1, b, 1, 1); + TEST_ASSERT_EQ_I(dl_add_rule(prog, &r1), 0); + + dl_rule_t r2; /* p(X,Z) :- p(X,Y), p(Y,Z) */ + dl_rule_init(&r2, "p", 2); + dl_rule_head_var(&r2, 0, 0); dl_rule_head_var(&r2, 1, 2); + int b1 = dl_rule_add_atom(&r2, "p", 2); + dl_body_set_var(&r2, b1, 0, 0); dl_body_set_var(&r2, b1, 1, 1); + int b2 = dl_rule_add_atom(&r2, "p", 2); + dl_body_set_var(&r2, b2, 0, 1); dl_body_set_var(&r2, b2, 1, 2); + TEST_ASSERT_EQ_I(dl_add_rule(prog, &r2), 1); + + TEST_ASSERT_EQ_I(dl_eval(prog), 0); + ray_t* out = dl_query(prog, "p"); + TEST_ASSERT_NOT_NULL(out); + TEST_ASSERT_EQ_I((int)ray_table_nrows(out), 28); + + dl_program_free(prog); + ray_release(edge); ray_release(c0); ray_release(c1); + PASS(); +} + +/* Audit §1.4: an I64 literal against an F64 EDB column must filter, not + * pass the whole table through. */ +static test_result_t test_const_filter_f64_column(void) { + int64_t ids[] = {1, 2, 3}; + double xs[] = {1.0, 2.0, 3.0}; + ray_t* c0 = ray_vec_from_raw(RAY_I64, ids, 3); + ray_t* c1 = ray_vec_from_raw(RAY_F64, xs, 3); + ray_t* pts = ray_table_new(2); + pts = ray_table_add_col(pts, ray_sym_intern("pts__c0", 7), c0); + pts = ray_table_add_col(pts, ray_sym_intern("pts__c1", 7), c1); + + dl_program_t* prog = dl_program_new(); + TEST_ASSERT_EQ_I(dl_add_edb(prog, "pts", pts, 2), 0); + dl_rule_t r; /* q(X) :- pts(X, 2) */ + dl_rule_init(&r, "q", 1); + dl_rule_head_var(&r, 0, 0); + int b = dl_rule_add_atom(&r, "pts", 2); + dl_body_set_var(&r, b, 0, 0); + dl_body_set_const_typed(&r, b, 1, 2, RAY_I64); + TEST_ASSERT_EQ_I(dl_add_rule(prog, &r), 0); + + /* q2(Y) :- pts(1.0, Y) — an F64 literal against the I64 id column + * (pos 0), exercising dl_col_eq_row's `col->type == RAY_I64 && + * const_type == RAY_F64` branch (`(double)cell == v`), which the + * first rule above never reaches (its F64 literal always targets + * the F64 column). */ + double one = 1.0; + int64_t one_bits; memcpy(&one_bits, &one, sizeof one_bits); + dl_rule_t r2; + dl_rule_init(&r2, "q2", 1); + dl_rule_head_var(&r2, 0, 0); + int b2 = dl_rule_add_atom(&r2, "pts", 2); + dl_body_set_const_typed(&r2, b2, 0, one_bits, RAY_F64); + dl_body_set_var(&r2, b2, 1, 0); + TEST_ASSERT_EQ_I(dl_add_rule(prog, &r2), 1); + + TEST_ASSERT_EQ_I(dl_eval(prog), 0); + ray_t* out = dl_query(prog, "q"); + TEST_ASSERT_NOT_NULL(out); + TEST_ASSERT_EQ_I((int)ray_table_nrows(out), 1); + TEST_ASSERT_EQ_I((int)((int64_t*)ray_data(ray_table_get_col_idx(out, 0)))[0], 2); + + ray_t* out2 = dl_query(prog, "q2"); + TEST_ASSERT_NOT_NULL(out2); + TEST_ASSERT_EQ_I((int)ray_table_nrows(out2), 1); + TEST_ASSERT_EQ_F(((double*)ray_data(ray_table_get_col_idx(out2, 0)))[0], 1.0, 1e-12); + + dl_program_free(prog); + ray_release(pts); ray_release(c0); ray_release(c1); + PASS(); +} + +/* Audit §1.4 (review follow-up): source provenance for a constant body + * slot must use the same type-aware equality as dl_filter_eq (an F64 + * literal against an I64 column), not a raw int64 bit-compare — see + * dl_build_source_prov's const-slot branch, which previously read + * `((int64_t*)ray_data(bcol))[br] != body->const_vals[c]` directly. */ +static test_result_t test_source_prov_f64_const_body_slot(void) { + int64_t e_vals[] = {1, 2, 3}; + int64_t k_vals[] = {7, 7, 9}; + ray_t* e_col = ray_vec_from_raw(RAY_I64, e_vals, 3); + ray_t* k_col = ray_vec_from_raw(RAY_I64, k_vals, 3); + TEST_ASSERT_NOT_NULL(e_col); + TEST_ASSERT_NOT_NULL(k_col); + + ray_t* kv = ray_table_new(2); + kv = ray_table_add_col(kv, ray_sym_intern("kv__c0", 6), e_col); + TEST_ASSERT_FALSE(RAY_IS_ERR(kv)); + kv = ray_table_add_col(kv, ray_sym_intern("kv__c1", 6), k_col); + TEST_ASSERT_FALSE(RAY_IS_ERR(kv)); + + dl_program_t* prog = dl_program_new(); + TEST_ASSERT_NOT_NULL(prog); + prog->flags |= DL_FLAG_PROVENANCE; + + int kv_idx = dl_add_edb(prog, "kv", kv, 2); + TEST_ASSERT_EQ_I(kv_idx, 0); + + /* hit(E) :- kv(E, 7.0) — F64 literal against the I64 k column. */ + double seven = 7.0; + int64_t seven_bits; memcpy(&seven_bits, &seven, sizeof seven_bits); + dl_rule_t rule; + dl_rule_init(&rule, "hit", 1); + dl_rule_head_var(&rule, 0, 0); + int body = dl_rule_add_atom(&rule, "kv", 2); + dl_body_set_var(&rule, body, 0, 0); /* E */ + dl_body_set_const_typed(&rule, body, 1, seven_bits, RAY_F64); /* constant 7.0 */ + rule.n_vars = 1; + TEST_ASSERT_EQ_I(dl_add_rule(prog, &rule), 0); + + TEST_ASSERT_EQ_I(dl_eval(prog), 0); + + ray_t* out = dl_query(prog, "hit"); + TEST_ASSERT_NOT_NULL(out); + TEST_ASSERT_EQ_I((int)ray_table_nrows(out), 2); + + ray_t* offsets = dl_get_provenance_src_offsets(prog, "hit"); + ray_t* data = dl_get_provenance_src_data(prog, "hit"); + TEST_ASSERT_NOT_NULL(offsets); + TEST_ASSERT_NOT_NULL(data); + TEST_ASSERT_EQ_I((int)ray_len(offsets), 3); + TEST_ASSERT_EQ_I((int)ray_len(data), 2); + int64_t* off = (int64_t*)ray_data(offsets); + TEST_ASSERT_EQ_I((int)off[0], 0); + TEST_ASSERT_EQ_I((int)off[1], 1); + TEST_ASSERT_EQ_I((int)off[2], 2); + /* Both refs must point at relation kv (idx 0), rows 0 and 1 — never row 2 + * (kv(3,9), which does not equal 7.0). Before routing through + * dl_col_eq_row, the raw int64 compare `9 != ` happened to + * still reject row 2, but rows 0/1 (`7 != `) would also have + * been wrongly rejected, leaving provenance empty. */ + int64_t* sd = (int64_t*)ray_data(data); + for (int i = 0; i < 2; i++) { + TEST_ASSERT_EQ_I((int)(sd[i] >> 32), kv_idx); + TEST_ASSERT_TRUE((sd[i] & 0xffffffff) != 2); + } + + dl_program_free(prog); + ray_release(kv); + ray_release(e_col); + ray_release(k_col); + PASS(); +} + +/* Audit §2.1: dl_add_rule deep-copies expression trees, so two programs can + * hold the same rule and each free its own copy; the caller frees the + * original. Under ASan a shared tree would double-free here. */ +static test_result_t test_rule_expr_ownership(void) { + dl_rule_t r; /* q(Y) :- p(X), Y = X + 1 */ + dl_rule_init(&r, "q", 1); + dl_rule_head_var(&r, 0, 1); + int b = dl_rule_add_atom(&r, "p", 1); + dl_body_set_var(&r, b, 0, 0); + dl_expr_t* e = dl_expr_binop(OP_ADD, dl_expr_var(0), dl_expr_const(1)); + TEST_ASSERT_TRUE(dl_rule_add_assign(&r, 1, OP_ADD, e) >= 0); + + int64_t v[] = {1}; + ray_t* c = ray_vec_from_raw(RAY_I64, v, 1); + ray_t* p = ray_table_new(1); + p = ray_table_add_col(p, ray_sym_intern("p__c0", 5), c); + + dl_program_t* a = dl_program_new(); + dl_program_t* bprog = dl_program_new(); + dl_add_edb(a, "p", p, 1); dl_add_edb(bprog, "p", p, 1); + TEST_ASSERT_EQ_I(dl_add_rule(a, &r), 0); + TEST_ASSERT_EQ_I(dl_add_rule(bprog, &r), 0); + TEST_ASSERT_TRUE(a->rules[0].body[1].assign_expr != r.body[1].assign_expr); + TEST_ASSERT_TRUE(a->rules[0].body[1].assign_expr != bprog->rules[0].body[1].assign_expr); + TEST_ASSERT_EQ_I(dl_eval(a), 0); + TEST_ASSERT_EQ_I((int)((int64_t*)ray_data(ray_table_get_col_idx(dl_query(a, "q"), 0)))[0], 2); + + dl_program_free(a); + dl_program_free(bprog); + dl_rule_free_exprs(&r); + TEST_ASSERT_TRUE(r.body[1].assign_expr == NULL); + ray_release(p); ray_release(c); + PASS(); +} + const test_entry_t datalog_entries[] = { { "datalog/source_provenance", test_source_provenance, datalog_setup, datalog_teardown }, { "datalog/source_prov_requires_flag", test_source_prov_requires_flag, datalog_setup, datalog_teardown }, { "datalog/source_prov_const_body_slot", test_source_prov_const_body_slot, datalog_setup, datalog_teardown }, + { "datalog/source_prov_f64_const_body_slot", test_source_prov_f64_const_body_slot, datalog_setup, datalog_teardown }, { "datalog/source_prov_buffer_grow", test_source_prov_buffer_grow, datalog_setup, datalog_teardown }, { "datalog/cmp_const_filter", test_cmp_const_filter, datalog_setup, datalog_teardown }, { "datalog/arith_assignment", test_arith_assignment, datalog_setup, datalog_teardown }, @@ -2517,6 +2758,7 @@ const test_entry_t datalog_entries[] = { { "datalog/env_bound_edb_auto_register", test_env_bound_edb_auto_register, datalog_rf_setup, datalog_rf_teardown }, { "datalog/env_bound_agg_auto_register", test_env_bound_agg_auto_register, datalog_rf_setup, datalog_rf_teardown }, { "datalog/eval_surfaces_compile_failure", test_eval_surfaces_compile_failure, datalog_rf_setup, datalog_rf_teardown }, + { "datalog/query_admission_errors", test_query_admission_errors, datalog_rf_setup, datalog_rf_teardown }, { "datalog/error_free_reclaims", test_error_free_reclaims, datalog_rf_setup, datalog_rf_teardown }, { "datalog/agg_scalar_f64", test_agg_scalar_f64, datalog_setup, datalog_teardown }, { "datalog/agg_scalar_f64_sum_empty", test_agg_scalar_f64_sum_empty, datalog_setup, datalog_teardown }, @@ -2534,6 +2776,9 @@ const test_entry_t datalog_entries[] = { { "datalog/rule_add_interval", test_rule_add_interval, datalog_setup, datalog_teardown }, { "datalog/rule_add_interval_overflow", test_rule_add_interval_overflow, datalog_setup, datalog_teardown }, { "datalog/edb_over_arity_domain_guard", test_edb_over_arity_domain_guard, datalog_setup, datalog_teardown }, + { "datalog/nonlinear_closure_chain", test_nonlinear_closure_chain, datalog_setup, datalog_teardown }, + { "datalog/const_filter_f64_column", test_const_filter_f64_column, datalog_setup, datalog_teardown }, + { "datalog/rule_expr_ownership", test_rule_expr_ownership, datalog_setup, datalog_teardown }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_heap.c b/test/test_heap.c index fffc1b929..afb6cb839 100644 --- a/test/test_heap.c +++ b/test/test_heap.c @@ -2668,11 +2668,157 @@ static test_result_t test_scratch_realloc_has_index_detach(void) { PASS(); } + +/* ---- Native footprint: ray_shallow_bytes / ray_retained_bytes ---------- * + * + * The contract (rayforce.h): shallow = own block + private storage only this + * value releases; retained = shallow of everything reachable through + * ownership edges, each block once. Pin the shapes a binding relies on: + * atoms, vectors, string pools, slices, lists (shared elements once), dicts + * and tables (columns not charged twice), an attached index, the null + * singleton, and a direct (mmap'd) block. */ + +static test_result_t test_footprint_atoms_and_vectors(void) { + TEST_ASSERT_EQ_U(ray_shallow_bytes(NULL), 0); + TEST_ASSERT_EQ_U(ray_retained_bytes(NULL), 0); + TEST_ASSERT_EQ_U(ray_shallow_bytes(RAY_NULL_OBJ), 0); + TEST_ASSERT_EQ_U(ray_retained_bytes(RAY_NULL_OBJ), 0); + + ray_t* a = ray_i64(7); + size_t sa = ray_shallow_bytes(a); + TEST_ASSERT_EQ_U(sa, BSIZEOF(a->order)); /* the whole buddy block */ + TEST_ASSERT_TRUE(sa >= 32 && (sa & (sa - 1)) == 0); + TEST_ASSERT_EQ_U(ray_retained_bytes(a), sa); + ray_release(a); + + /* Short string: SSO, one block. Long string: payload block added. */ + ray_t* s1 = ray_str("abc", 3); + TEST_ASSERT_EQ_U(ray_shallow_bytes(s1), BSIZEOF(s1->order)); + ray_t* s2 = ray_str("a string well past the inline limit", 35); + size_t ss2 = ray_shallow_bytes(s2); + TEST_ASSERT_TRUE(ss2 > BSIZEOF(s2->order)); + TEST_ASSERT_TRUE(ss2 >= BSIZEOF(s2->order) + 32 + 35); + TEST_ASSERT_EQ_U(ray_retained_bytes(s2), ss2); + ray_release(s1); ray_release(s2); + + ray_t* v = ray_vec_new(RAY_I64, 1000); + v->len = 1000; + size_t sv = ray_shallow_bytes(v); + TEST_ASSERT_TRUE(sv >= 32 + 1000 * 8); + TEST_ASSERT_EQ_U(sv, BSIZEOF(v->order)); + TEST_ASSERT_EQ_U(ray_retained_bytes(v), sv); + + /* A slice charges only its header; retained reaches the parent. */ + ray_t* sl = ray_vec_slice(v, 10, 100); + TEST_ASSERT_TRUE(sl->attrs & RAY_ATTR_SLICE); + size_t ssl = ray_shallow_bytes(sl); + TEST_ASSERT_EQ_U(ssl, BSIZEOF(sl->order)); + TEST_ASSERT_TRUE(ssl < sv); + TEST_ASSERT_EQ_U(ray_retained_bytes(sl), ssl + sv); + ray_release(sl); + ray_release(v); + + /* A string vector charges its pool. */ + ray_t* sv1 = ray_vec_new(RAY_STR, 0); + for (int i = 0; i < 64; i++) + sv1 = ray_str_vec_append(sv1, "twenty-four bytes long..", 24); + TEST_ASSERT_TRUE(sv1->str_pool != NULL); + size_t ssv = ray_shallow_bytes(sv1); + TEST_ASSERT_EQ_U(ssv, BSIZEOF(sv1->order) + BSIZEOF(sv1->str_pool->order)); + TEST_ASSERT_TRUE(ssv >= 32 + 64 * 16 + 64 * 24); + TEST_ASSERT_EQ_U(ray_retained_bytes(sv1), ssv); + ray_release(sv1); + PASS(); +} + +static test_result_t test_footprint_containers(void) { + ray_t* c0 = ray_vec_new(RAY_I64, 500); c0->len = 500; + ray_t* c1 = ray_vec_new(RAY_F64, 300); c1->len = 300; + size_t s0 = ray_shallow_bytes(c0), s1 = ray_shallow_bytes(c1); + + /* List: the list block only; retained adds each element once even when + * the same vector sits in two slots. */ + ray_t* l = ray_list_new(3); + ray_retain(c0); l = ray_list_append(l, c0); + ray_retain(c1); l = ray_list_append(l, c1); + ray_retain(c0); l = ray_list_append(l, c0); + TEST_ASSERT_EQ_U(ray_shallow_bytes(l), BSIZEOF(l->order)); + TEST_ASSERT_EQ_U(ray_retained_bytes(l), BSIZEOF(l->order) + s0 + s1); + + /* Table: shallow is the table block; retained is table + names + the + * column list + the columns — no column charged twice. */ + ray_t* t = ray_table_new(2); + t = ray_table_add_col(t, ray_sym_intern("a", 1), c0); /* consumes c0 */ + t = ray_table_add_col(t, ray_sym_intern("b", 1), c1); /* consumes c1 */ + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + size_t st = ray_shallow_bytes(t); + TEST_ASSERT_EQ_U(st, BSIZEOF(t->order)); + size_t rt = ray_retained_bytes(t); + TEST_ASSERT_TRUE(rt >= st + s0 + s1); + ray_t** slots = (ray_t**)ray_data(t); + TEST_ASSERT_EQ_U(rt, st + ray_retained_bytes(slots[0]) + ray_retained_bytes(slots[1])); + /* The list still holds c0/c1: their bytes appear in both walks, and the + * table walk did not count them twice. */ + TEST_ASSERT_EQ_U(ray_retained_bytes(l), BSIZEOF(l->order) + s0 + s1); + ray_release(l); + + /* Dict: same shape as a table (two slots). */ + ray_t* k = ray_vec_new(RAY_I64, 4); k->len = 4; + ray_t* vv = ray_vec_new(RAY_I64, 4); vv->len = 4; + size_t sk = ray_shallow_bytes(k), svv = ray_shallow_bytes(vv); + ray_t* d = ray_dict_new(k, vv); + TEST_ASSERT_EQ_U(ray_shallow_bytes(d), BSIZEOF(d->order)); + TEST_ASSERT_EQ_U(ray_retained_bytes(d), BSIZEOF(d->order) + sk + svv); + ray_release(d); + ray_release(t); + PASS(); +} + +static test_result_t test_footprint_index_and_direct(void) { + /* An attached hash index is private storage: shallow grows by the index + * block and its tables, and retained agrees. */ + ray_t* v = ray_vec_new(RAY_I64, 2000); + v->len = 2000; + for (int64_t i = 0; i < 2000; i++) ((int64_t*)ray_data(v))[i] = i % 97; + size_t plain = ray_shallow_bytes(v); + ray_t* r = ray_index_attach_hash(&v); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_TRUE(v->attrs & RAY_ATTR_HAS_INDEX); + size_t indexed = ray_shallow_bytes(v); + TEST_ASSERT_TRUE(indexed > plain); + TEST_ASSERT_EQ_U(indexed, plain + ray_shallow_bytes(v->index)); + TEST_ASSERT_EQ_U(ray_retained_bytes(v), indexed); + ray_t* kids[4]; + int k = ray_index_child_blocks(ray_index_payload(v->index), kids, 4); + TEST_ASSERT_EQ_I(k, 4); + size_t sum = BSIZEOF(v->index->order); + for (int i = 0; i < k; i++) sum += BSIZEOF(kids[i]->order); + TEST_ASSERT_EQ_U(ray_shallow_bytes(v->index), sum); + ray_release(v); + + /* A direct block (larger than the standard pool order) reports its exact + * page-rounded mapping, not a power of two. */ + size_t big = (size_t)40 << 20; + ray_t* d = ray_alloc(big); + TEST_ASSERT_TRUE(d && !RAY_IS_ERR(d)); + TEST_ASSERT_TRUE(ray_is_direct(d)); + size_t sd = ray_shallow_bytes(d); + TEST_ASSERT_TRUE(sd >= big + 32); + TEST_ASSERT_EQ_U(sd, ray_direct_map_size(d)); + TEST_ASSERT_EQ_U(sd & 4095, 0); + TEST_ASSERT_EQ_U(ray_retained_bytes(d), sd); + ray_free(d); + PASS(); +} + /* ---- Suite definition -------------------------------------------------- */ const test_entry_t heap_entries[] = { { "heap/slab_overflow", test_slab_overflow_falls_through, heap_setup, heap_teardown }, { "heap/multi_pool_growth", test_multi_pool_growth, heap_setup, heap_teardown }, + { "heap/footprint_atoms_vectors", test_footprint_atoms_and_vectors, heap_setup, heap_teardown }, + { "heap/footprint_containers", test_footprint_containers, heap_setup, heap_teardown }, + { "heap/footprint_index_direct", test_footprint_index_and_direct, heap_setup, heap_teardown }, { "heap/scratch_realloc_atom", test_scratch_realloc_atom, heap_setup, heap_teardown }, { "heap/scratch_realloc_vec_grow", test_scratch_realloc_vec_grow, heap_setup, heap_teardown }, { "heap/scratch_realloc_vec_shrink", test_scratch_realloc_vec_shrink, heap_setup, heap_teardown }, diff --git a/test/test_ipc.c b/test/test_ipc.c index 20e2e9b01..6312e6dca 100644 --- a/test/test_ipc.c +++ b/test/test_ipc.c @@ -1845,7 +1845,9 @@ static test_result_t test_ipc_hooks_lifecycle(void) { ray_sys_free(srv_vm); /* Read counters back through the global env. on.open + on.sync - * + on.close each fired exactly once. `_hook_sync_handle` records + * fired exactly once; on.close fired twice — once on the client for + * its own outbound handle (ray_ipc_close, #503) and once on the + * server for the inbound one. `_hook_sync_handle` records * `.ipc.handle` as seen INSIDE the sync hook — must equal the * legacy server's conn-array index (0 for the only active conn). */ int64_t sym_open = ray_sym_intern("_hook_open", strlen("_hook_open")); @@ -1859,7 +1861,7 @@ static test_result_t test_ipc_hooks_lifecycle(void) { ray_t* v_msg = ray_env_get(sym_msg); TEST_ASSERT_NOT_NULL(v_msg); TEST_ASSERT_EQ_I(v_open->i64, 1); - TEST_ASSERT_EQ_I(v_close->i64, 1); + TEST_ASSERT_EQ_I(v_close->i64, 2); TEST_ASSERT_EQ_I(v_msg->i64, 1); TEST_ASSERT_EQ_I(v_h->i64, 0); diff --git a/test/test_journal.c b/test/test_journal.c index f4b0e173b..8277a7290 100644 --- a/test/test_journal.c +++ b/test/test_journal.c @@ -982,6 +982,15 @@ static test_result_t test_journal_roll_twice(void) { ray_journal_validate(lpath, &chunks, NULL); TEST_ASSERT_EQ_I(chunks, 0); + /* Two rolls in one second must leave both archived segments intact. */ + char pattern[300]; + snprintf(pattern, sizeof(pattern), "%s.*.log", base); + glob_t archives; + memset(&archives, 0, sizeof(archives)); + TEST_ASSERT_EQ_I(glob(pattern, 0, NULL, &archives), 0); + TEST_ASSERT_EQ_U(archives.gl_pathc, 2); + globfree(&archives); + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); cleanup_base(base); PASS(); diff --git a/test/test_lang.c b/test/test_lang.c index 06fff1290..221036ae9 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -5055,7 +5055,8 @@ static test_result_t test_datalog_query_inline_rules(void) { TEST_ASSERT_EQ_I((int)ray_table_nrows(r_inline), 6); ray_release(r_inline); - /* Global foo rule — inline rules omit it; foo yields no rows */ + /* Global foo rule — inline rules omit it, so `foo` resolves to no + * relation at all: an unknown-relation error, not an empty result. */ ray_t* r_foo = ray_eval_str( "(do" " (set db (datoms))" @@ -5065,9 +5066,8 @@ static test_result_t test_datalog_query_inline_rules(void) { " (rules ((path ?x ?y) (?x :edge ?y)))))" ); TEST_ASSERT_TRUE(r_foo != NULL); - TEST_ASSERT_TRUE(!RAY_IS_ERR(r_foo)); - TEST_ASSERT_EQ_I((int)ray_table_nrows(r_foo), 0); - ray_release(r_foo); + TEST_ASSERT_TRUE(RAY_IS_ERR(r_foo)); + ray_error_free(r_foo); ray_t* r_global = ray_eval_str( "(do" diff --git a/test/test_mcast.c b/test/test_mcast.c index d2108a6ed..4475bafda 100644 --- a/test/test_mcast.c +++ b/test/test_mcast.c @@ -879,7 +879,10 @@ static test_result_t test_mcast_txlimit_overflow_disconnects(void) { ray_release(pub); TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_mc_count", 9, 1, 2000)); - TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_mc_close_count", 15, 1, 2000)); + /* Two closes: the server dropping h1 (inbound), and h1's own side + * seeing the EOF (outbound, #503) — the signal a subscriber needs + * to notice it was evicted and reconnect. */ + TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_mc_close_count", 15, 2, 2000)); ray_t* c = ray_env_get(ray_sym_intern("_mc_count", 9)); TEST_ASSERT_NOT_NULL(c); TEST_ASSERT_EQ_I(c->i64, 1); /* only h2 received it */ @@ -926,6 +929,114 @@ static test_result_t test_mcast_txlimit_overflow_disconnects(void) { PASS(); } +/* .ipc.on.close fires for outbound connections too (#503), once per + * established connection on any teardown: the peer's orderly close, a + * peer reset, and a local .ipc.close. .ipc.on.open stays inbound-only, + * and (.ipc.handle h) reports `inbound` so one handler can tell the two + * apart. The hook lambda is shared by the server thread (inbound + * closes) and the client poll (outbound closes), so it records the + * direction it saw rather than bare handle ids, which the two polls + * number independently. */ +static test_result_t test_ipc_outbound_close_hook(void) { + ray_t* r = ray_eval_str( + "(set _oc_in 0)" + "(set _oc_out 0)" + "(set _oc_open 0)" + "(set _oc_srv [])" + "(set .ipc.on.open (fn [h] (do (set _oc_open (+ _oc_open 1)) (set _oc_srv (concat _oc_srv h)))))" + "(set .ipc.on.close (fn [h] " + " (if (at (.ipc.handle h) 'inbound) (set _oc_in (+ _oc_in 1)) (set _oc_out (+ _oc_out 1)))))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + if (r != RAY_NULL_OBJ) ray_release(r); + + ray_poll_t* poll; + ray_vm_t* vm; + uint16_t port; + ray_thread_t tid; + test_result_t sr = start_server(&poll, &port, &vm, &tid); + if (sr.status != TEST_PASS) return sr; + + int64_t h1 = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); + int64_t h2 = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); + int64_t h3 = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); + int64_t hc = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); /* control */ + TEST_ASSERT((h1) >= (0) && (h2) >= (0) && (h3) >= (0) && (hc) >= (0), "connected"); + pump_client(); + + /* open fired once per inbound connection and never for an outbound one */ + ray_t* op = ray_env_get(ray_sym_intern("_oc_open", 8)); + TEST_ASSERT_NOT_NULL(op); + TEST_ASSERT_EQ_I(op->i64, 4); + + /* direction is visible on both sides */ + ray_t* msg = ray_str("(at (.ipc.handle (.ipc.handle)) 'inbound)", strlen("(at (.ipc.handle (.ipc.handle)) 'inbound)")); + ray_t* inb = ray_ipc_send(hc, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(inb); + TEST_ASSERT_FALSE(RAY_IS_ERR(inb)); + TEST_ASSERT_EQ_I(inb->type, -RAY_BOOL); + TEST_ASSERT_TRUE(inb->b8); + ray_release(inb); + { + ray_ipc_tx_info_t ti; + TEST_ASSERT_EQ_I(ray_ipc_tx_info(h1, &ti), RAY_OK); + TEST_ASSERT_FALSE(ti.inbound); + } + + ray_t* srv = ray_env_get(ray_sym_intern("_oc_srv", 7)); + TEST_ASSERT_NOT_NULL(srv); + TEST_ASSERT((ray_len(srv)) >= (3), "server-side handles captured"); + int64_t s1 = ((int64_t*)ray_data(srv))[0]; + int64_t s2 = ((int64_t*)ray_data(srv))[1]; + + /* A: the peer closes h1 in an orderly way (server-side .ipc.close) */ + char src[96]; + int n = snprintf(src, sizeof(src), "(.ipc.close %lld)", (long long)s1); + msg = ray_str(src, (size_t)n); + ray_t* cr = ray_ipc_send(hc, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(cr); + TEST_ASSERT_FALSE(RAY_IS_ERR(cr)); + ray_release(cr); + TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_oc_out", 7, 1, 1000)); + + /* B: the peer resets h2 (linger zero, then close → RST) */ +#ifndef RAY_OS_WINDOWS + { + ray_selector_t* ssel = ray_poll_get(poll, s2); + TEST_ASSERT_NOT_NULL(ssel); + struct linger lg = { 1, 0 }; + setsockopt((ray_sock_t)ssel->fd, SOL_SOCKET, SO_LINGER, &lg, sizeof(lg)); + } +#endif + n = snprintf(src, sizeof(src), "(.ipc.close %lld)", (long long)s2); + msg = ray_str(src, (size_t)n); + cr = ray_ipc_send(hc, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(cr); + TEST_ASSERT_FALSE(RAY_IS_ERR(cr)); + ray_release(cr); + TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_oc_out", 7, 2, 1000)); + + /* C: local close of h3 fires the hook too — one rule for any teardown */ + ray_ipc_close(h3); + TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_oc_out", 7, 3, 1000)); + + /* exactly once each; the inbound side saw its own three closes */ + ray_t* out = ray_env_get(ray_sym_intern("_oc_out", 7)); + TEST_ASSERT_NOT_NULL(out); + TEST_ASSERT_EQ_I(out->i64, 3); + sleep_ms(50); + ray_t* in = ray_env_get(ray_sym_intern("_oc_in", 6)); + TEST_ASSERT_NOT_NULL(in); + TEST_ASSERT((in->i64) >= (3), "inbound closes observed on the server"); + + ray_ipc_close(hc); + stop_server(poll, port, vm, tid); + PASS(); +} + static test_result_t test_mcast_failed_send_defers_close(void) { ray_t* r = ray_eval_str( "(set _mc_count 0)" @@ -1139,5 +1250,6 @@ const test_entry_t mcast_entries[] = { { "mcast/failed_send_defers_close", test_mcast_failed_send_defers_close, mcast_setup, mcast_teardown }, { "mcast/shared_frame_across_subs", test_mcast_shared_frame_across_subscribers, mcast_setup, mcast_teardown }, { "mcast/txlimit_overflow_disconnects", test_mcast_txlimit_overflow_disconnects, mcast_setup, mcast_teardown }, + { "ipc/outbound_close_hook", test_ipc_outbound_close_hook, mcast_setup, mcast_teardown }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_runtime.c b/test/test_runtime.c index 1a4049b4d..3c07b9914 100644 --- a/test/test_runtime.c +++ b/test/test_runtime.c @@ -595,15 +595,21 @@ static test_result_t test_build_sys_args_edges(void) { PASS(); } -/* .sys.args builtin: empty when unset; reflects stored dict when set */ +/* .sys.args builtin: only `source` when unset; reflects stored dict when set */ static test_result_t test_sys_args_builtin(void) { - /* unset → empty dict, never NULL */ + /* unset → a dict holding just `source` (empty here: ray_eval_str is + * no file, #506), never NULL */ ray_t* e = ray_eval_str("(.sys.args)"); TEST_ASSERT_NOT_NULL(e); TEST_ASSERT_FALSE(RAY_IS_ERR(e)); TEST_ASSERT_EQ_I(e->type, RAY_DICT); - TEST_ASSERT_EQ_I(ray_dict_len(e), 0); + TEST_ASSERT_EQ_I(ray_dict_len(e), 1); ray_release(e); + ray_t* src = ray_eval_str("(count (at (.sys.args) 'source))"); + TEST_ASSERT_NOT_NULL(src); + TEST_ASSERT_FALSE(RAY_IS_ERR(src)); + TEST_ASSERT_EQ_I(src->i64, 0); + ray_release(src); /* set, then read back through the builtin */ char* argv[] = { "rayforce", "-p", "5000", "--", "-opt", "123" }; diff --git a/test/test_text_null.c b/test/test_text_null.c new file mode 100644 index 000000000..53771e86a --- /dev/null +++ b/test/test_text_null.c @@ -0,0 +1,216 @@ +/* Canonical text nulls must not depend on the optional HAS_NULLS metadata. */ +#include "test.h" +#include "lang/eval.h" +#include "table/sym.h" +#include "vec/vec.h" +#include "ops/agg_engine.h" +#include "ops/idxop.h" +#include "ops/internal.h" +#include + +extern ray_runtime_t* __RUNTIME; +static void text_null_setup(void) { ray_runtime_create(0, NULL); } +static void text_null_teardown(void) { ray_runtime_destroy(__RUNTIME); } + +static test_result_t expect_int(const char* expr, int64_t expected) { + ray_t* r = ray_eval_str(expr); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r), "eval failed: %s", expr); + TEST_ASSERT_FMT(r->type == -RAY_I64 && r->i64 == expected, + "wrong integer result: %s (type=%d value=%lld expected=%lld)", expr, + r->type, (long long)r->i64, (long long)expected); + ray_release(r); + PASS(); +} + +static test_result_t text_null_operations(int8_t type) { + ray_t* v = ray_eval_str(type == RAY_SYM + ? "(as 'SYM (list \"\" \"beta\" \"alpha\" \"\"))" + : "(as 'STR (list \"\" \"beta\" \"alpha\" \"\"))"); + TEST_ASSERT(v && !RAY_IS_ERR(v), "text input"); + v->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + TEST_ASSERT(ray_vec_may_have_nulls(v), "text payload may contain nulls"); + TEST_ASSERT(ray_vec_is_null(v, 0) && ray_vec_is_null(v, 3), "empty payloads are null"); + TEST_ASSERT_EQ_I(ray_env_set(ray_sym_intern("text_input", 10), v), RAY_OK); + ray_t* slice = ray_vec_slice(v, 0, 3); + TEST_ASSERT(slice && !RAY_IS_ERR(slice), "text slice"); + TEST_ASSERT_EQ_I(ray_env_set(ray_sym_intern("text_slice", 10), slice), RAY_OK); + ray_release(slice); + ray_release(v); + + const struct { const char* expr; int64_t value; } checks[] = { + { "(sum (map nil? text_input))", 2 }, + { "(sum (map nil? text_slice))", 1 }, + { "(strlen (min text_slice))", 5 }, + { "(strlen (min text_input))", 5 }, + { "(strlen (max text_input))", 4 }, + { "(sum (map nil? (at text_input [3 1 0])))", 2 }, + { "(sum (map nil? (substr text_input 1 2)))", 2 }, + { "(count (distinct text_input))", 3 }, + { "(as 'I64 (nil? (at (asc text_input) 0)))", 1 }, + { "(as 'I64 (nil? (at (desc text_input) 3)))", 1 }, + { "(as 'I64 (nil? (min (at text_input [0 3]))))", 1 }, + { "(count (inner-join ['k] (table [k] (list text_input)) (table [k] (list text_input))))", 6 }, + { "(as 'I64 (nil? (at (at (select {from:(table [g v] (list [1 1] (at text_input [0 3]))) by:g m:(min v)}) 'm) 0)))", 1 }, + { "(count (select {from:(table [k v] (list text_input [1 2 3 4])) by:k s:(sum v)}))", 3 }, + { "(sum (at (select {from:(table [k v] (list text_input [1 2 3 4])) by:k s:(sum v)}) 's))", 10 }, + { "(sum (map nil? (at (select {from:(table [k v] (list text_input [1 2 3 4])) by:k s:(sum v)}) 'k)))", 1 }, + { "(count (select {from:(table [k] (list text_input)) where:(== k \"\")}))", 2 }, + { "(sum (map nil? (asc text_input)))", 2 }, + { "(sum (map nil? (desc text_input)))", 2 }, + { "(strlen (at (at (select {from:(table [g v] (list [1 1 1 1] text_input)) by:g m:(min v)}) 'm) 0))", 5 }, + { "(strlen (at (at (select {from:(table [g v] (list [1 1 1 1] text_input)) by:g f:(first v)}) 'f) 0))", 4 }, + { "(strlen (at (at (select {from:(table [g v] (list [1 1 1 1] text_input)) by:g l:(last v)}) 'l) 0))", 5 }, + }; + for (size_t i = 0; i < sizeof(checks) / sizeof(checks[0]); i++) { + test_result_t r = expect_int(checks[i].expr, checks[i].value); + if (r.status != TEST_PASS) return r; + } + PASS(); +} +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); } + +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 }; + for (size_t w = 0; w < sizeof(widths); w++) { + ray_t* v = ray_vec_new(RAY_SYM, 4); + TEST_ASSERT(v && !RAY_IS_ERR(v), "sym vector"); + v->len = 4; + v->attrs = widths[w]; + const int64_t ids[] = { 0, 1, 2, 0 }; + for (int i = 0; i < 4; i++) ray_write_sym(ray_data(v), i, ids[i], RAY_SYM, v->attrs); + for (int flagged = 0; flagged < 2; flagged++) { + if (flagged) v->attrs |= RAY_ATTR_HAS_NULLS; + dense_plan_t plan; + TEST_ASSERT(agg_dense_plan(&v, 1, NULL, 0, 4, &plan), "zero admits dense grouping"); + TEST_ASSERT(plan.ok, "dense plan valid"); + } + ray_release(v); + } + PASS(); +} + +static test_result_t test_dense_symbol_gap(void) { + /* Give the actual keys ids far from zero, as happens after importing + * earlier columns of a wide CSV. Exercise parallel, mixed signed keys, + * selection, and an all-empty input with both metadata states. */ + for (int i = 0; i < 5000; i++) { + char name[32]; + int n = snprintf(name, sizeof(name), "gap_padding_%d", i); + TEST_ASSERT(ray_sym_intern(name, (size_t)n) >= 0, "intern padding"); + } + ray_t* t = ray_eval_str( + "(table [k h v tm] (list (take [gap_a ' gap_b '] 70000) " + "(take (as 'I16 [-2 -2 3 3]) 70000) " + "(take [1.0 2.0 3.0 4.0] 70000) " + "(as 'TIME (take [100 200 300 400] 70000))))"); + TEST_ASSERT(t && !RAY_IS_ERR(t), "large grouped fixture"); + TEST_ASSERT_EQ_I(ray_env_set(ray_sym_intern("gap_t", 5), t), RAY_OK); + ray_t* key = ray_table_get_col(t, ray_sym_intern("k", 1)); + TEST_ASSERT(key && key->type == RAY_SYM, "sym key"); + const struct { const char* expr; int64_t value; } checks[] = { + { "(count (select {from:gap_t by:k s:(sum v) m:(max tm)}))", 3 }, + { "(count (select {from:gap_t by:[k h] s:(sum v) m:(max tm)}))", 4 }, + { "(count (select {from:gap_t by:k s:(sum v) m:(max tm) where:(== h -2)}))", 2 }, + { "(count (select {from:gap_t by:k s:(sum v) m:(max tm) where:(== k ')}))", 1 }, + { "(as 'I64 (sum (at (select {from:gap_t by:[k h] s:(sum v) m:(max tm)}) 's)))", 175000 }, + { "(as 'I64 (sum (at (select {from:gap_t by:k s:(sum v) m:(max tm) where:(== k ')}) 's)))", 105000 }, + { "(sum (map nil? (at (select {from:gap_t by:k s:(sum v) m:(max tm)}) 'k)))", 1 }, + }; + for (int flagged = 0; flagged < 2; flagged++) { + key->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + if (flagged) key->attrs |= RAY_ATTR_HAS_NULLS; + for (size_t i = 0; i < sizeof(checks) / sizeof(checks[0]); i++) { + test_result_t r = expect_int(checks[i].expr, checks[i].value); + if (r.status != TEST_PASS) { ray_release(t); return r; } + } + } + ray_release(t); + PASS(); +} + + +/* Assert admission as well as values: conservative text null gates must not + * silently turn indexed predicates or expression compilation into scans. */ +static test_result_t test_sym_hash_routes(void) { + for (int nullable = 0; nullable < 2; nullable++) { + for (int flagged = 0; flagged < 2; flagged++) { + ray_t* v = ray_eval_str(nullable ? "[' beta alpha ']" : "[alpha beta alpha alpha]"); + TEST_ASSERT(v && !RAY_IS_ERR(v), "symbol fixture"); + v->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + if (flagged) v->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* attached = ray_index_attach_hash(&v); + TEST_ASSERT(attached && !RAY_IS_ERR(attached), "hash attach"); + int64_t beta = ray_sym_intern("beta", 4); + TEST_ASSERT_EQ_I(ray_index_find_row(v, beta), 1); + TEST_ASSERT_EQ_I(ray_index_find_row(v, 0), -2); /* null scan fallback */ + ray_t* keys = ray_eval_str("[beta]"); + ray_t* sel = ray_index_in_rowsel(v, keys); + TEST_ASSERT(sel && !RAY_IS_ERR(sel), "nonnull IN uses index"); + ray_release(sel); + ray_idx_slice_t* slices = NULL; + ray_t* hdr = NULL; + TEST_ASSERT_EQ_I(ray_index_sym_slices(v, keys, &slices, &hdr), 1); + TEST_ASSERT_EQ_I(slices[0].n, 1); + ray_free(hdr); + ray_release(keys); + keys = ray_eval_str("[beta ']"); + TEST_ASSERT(ray_index_in_rowsel(v, keys) == NULL, "null IN falls back"); + TEST_ASSERT_EQ_I(ray_index_sym_slices(v, keys, &slices, &hdr), -1); + ray_release(keys); + + ray_t* tbl = ray_table_new(1); + tbl = ray_table_add_col(tbl, ray_sym_intern("k", 1), v); + ray_release(v); + for (int empty = 0; empty < 2; empty++) { + ray_graph_t* g = ray_graph_new(tbl); + ray_t* atom = ray_sym(empty ? 0 : beta); + ray_op_t* pred = ray_eq(g, ray_scan(g, "k"), ray_const_atom(g, atom)); + ray_release(atom); + ray_op_t* filter = ray_filter(g, ray_const_table(g, tbl), pred); + uint64_t before = ray_idx_hits[IDX_SITE_FILTER_HASH]; + ray_t* out = ray_execute(g, filter); + TEST_ASSERT(out && !RAY_IS_ERR(out), "indexed filter result"); + TEST_ASSERT_EQ_I(ray_table_nrows(out), empty ? (nullable ? 2 : 0) : 1); + if (!empty) + TEST_ASSERT(ray_idx_hits[IDX_SITE_FILTER_HASH] > before, "symbol filter uses hash index"); + ray_release(out); + ray_graph_free(g); + } + ray_release(tbl); + } + } + PASS(); +} + +static test_result_t test_sym_expr_admission(void) { + for (int nullable = 0; nullable < 2; nullable++) { + for (int flagged = 0; flagged < 2; flagged++) { + ray_t* v = ray_eval_str(nullable ? "[' beta alpha]" : "[alpha beta alpha]"); + TEST_ASSERT(v && !RAY_IS_ERR(v), "symbol fixture"); + v->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + if (flagged) v->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* tbl = ray_table_new(1); + tbl = ray_table_add_col(tbl, ray_sym_intern("k", 1), v); + ray_release(v); + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* pred = ray_eq(g, ray_scan(g, "k"), ray_const_str(g, "beta", 4)); + ray_expr_t expr; + TEST_ASSERT_EQ_I(expr_compile(g, tbl, pred, &expr), !nullable); + ray_graph_free(g); + ray_release(tbl); + } + } + PASS(); +} + +const test_entry_t text_null_entries[] = { + { "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 }, + { "text_null/str_without_flag", test_str_payload_nulls, text_null_setup, text_null_teardown }, + { "text_null/dense_symbol_gap", test_dense_symbol_gap, text_null_setup, text_null_teardown }, + { "text_null/dense_sym_zero", test_dense_sym_zero, text_null_setup, text_null_teardown }, + { NULL, NULL, NULL, NULL }, +};