Skip to content

v2.7.0 - #529

Merged
singaraiona merged 70 commits into
masterfrom
dev
Sep 14, 2026
Merged

v2.7.0#529
singaraiona merged 70 commits into
masterfrom
dev

Conversation

@singaraiona

Copy link
Copy Markdown
Collaborator

What & why

Checklist

  • PR targets dev (not master)
  • Commits follow Conventional Commits (feat: / fix: / perf: / docs: / …)
  • make builds cleanly (no new warnings)
  • make test passes; tests added/updated for behaviour changes

singaraiona and others added 30 commits September 10, 2026 12:14
…ion in .ipc.handle

.ipc.on.close fired for inbound connections only: ipc_on_close skipped
the hook when listener_id was -1, to keep a 1:1 pairing with
.ipc.on.open.  A receive-only client — every multicast subscriber —
therefore got no event when the peer closed or reset the connection,
or when the publisher evicted it for backlog overflow: the runtime saw
the EOF and deregistered the handle while the application kept a dead
integer, and the only timely workaround was a timer that pings and
catches the send failure.

The hook now fires for both directions, exactly once per established
connection on any teardown: the peer's close or reset, a socket error,
a local .ipc.close, or an eviction seen from the subscriber as EOF.
The guard is one line less; outbound connections are registered after
their handshake, so the completed-handshake condition already holds.
.ipc.on.open stays inbound-only (documented asymmetry, as q's .z.po /
.z.pc), and (.ipc.handle h) gains `inbound` so a single handler can
tell the direction — the hook fires before teardown, so the handle
still resolves inside it.  Reconnect belongs on a timer, not inside
the hook, which runs in the poller's deregister path.

One behaviour change for existing handlers: a server that also opens
outbound connections now sees their closes too; `inbound` is the
one-line branch for handlers that must distinguish.

Closes #503

Claude-Session: https://claude.ai/code/session_01J4QKJW3RbRP8TQoquJtARg
feat(ipc): fire .ipc.on.close for outbound connections, report direction in .ipc.handle
ray_load_file_fn returned a bare `io` for every failure — open, stat,
map — so a missing dependency in a startup script printed `error: io`,
which reads like an IPC, journal or storage failure and sends diagnosis
the wrong way.  Each failure now says which step failed on which file
and why: `error: io: load "missing/x.rfl": No such file or directory`,
`... : is a directory`, `... : cannot map N bytes: ...`.  Both the mmap
and the Windows fread branches.

Closes #505

Claude-Session: https://claude.ai/code/session_01J4QKJW3RbRP8TQoquJtARg
-p opened the listener before the script so the script could use it,
and when the script failed to parse or evaluate the process printed the
error and went on serving the port with none of the script's
definitions installed.  A supervisor's port check passed and
Restart=on-failure never fired; only an application-level query showed
an empty interpreter where the service should have been.

A non-interactive run now treats a failing startup script as fatal:
the diagnostic names the script and the listener, and the process
exits with the script's status through the normal teardown, which
closes the listener.  With -i the REPL stays up so the user can look
around, as before.  The listener still opens before the script.

Closes #507

Claude-Session: https://claude.ai/code/session_01J4QKJW3RbRP8TQoquJtARg
…n .sys.args

`load` resolved a relative path against the working directory only, so
a script invoked from its project root and from its own directory could
not both find a shared file, and piped or heredoc input — which has no
file of its own — had no anchor at all.  q answers this with QHOME.

A relative load path is now tried 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).  A
failure names every path tried.  The command-line script itself is not
subject to the fallback.

(.sys.args) gains `source`: 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; empty at the REPL, under a pipe, or in a hook or timer
outside any file.  `file` is the command line's script ($0); `source`
follows nested loads ($BASH_SOURCE).  The REPL's pseudo-file name is
now a shared constant so `source` can recognise it.

Closes #506

Claude-Session: https://claude.ai/code/session_01J4QKJW3RbRP8TQoquJtARg
feat(load): RAYFORCE_HOME fallback for relative paths, and source in .sys.args
fix(app): a failed startup script under -p is fatal when not interactive
fix(load): name the file and the OS cause when a script cannot be loaded
…building it

upsert_apply built its key->row map over every existing row on entry and
freed it on exit, so a sequence of bulk batches into one growing table cost
O(batches * rows) — the map rebuild, not the batch, dominated. A profile of a
filling table is almost entirely upsert_hash_row and upsert_map_put, both of
which only ever touch rows that were already there; the probe side of the
batch barely registers. The per-batch cost grew with the table.

The hot shape already requires a named table mutated in place, which means
the table object itself survives between calls, so the map can live on it.
RAY_IDX_UKEY is a new index kind holding the open-addressing slot array, the
key column positions and the row count it describes. It attaches to the
RAY_TABLE rather than to a column because the key spans several of them, and
rides the type-agnostic HAS_INDEX arms of retain/release, so it dies with the
table. It is runtime-only: serde masks attrs down to HAS_NULLS and col_save
strips HAS_INDEX, so it cannot reach a file. The arm is sized to the existing
hash arm so ray_index_t does not grow, which would have moved the on-disk
layout of persisted column indexes.

Maintenance is what upsert already does: a matched row updates non-key
columns only, so the mapping is untouched, and an appended row is one insert
the append path was already making. Capacity grows by doubling, so rebuilds
are amortized. Everything else starts cold and pays the old price once: a
table that is copied, a key wider than the arm holds, a map that could not be
allocated.

Staleness is caught by the recorded row count, and the in-place where-update
path drops the map explicitly — it can rewrite a key cell without moving the
row count, which is the one mutation the count cannot see. The tests cover
both, and were checked by removing each guard in turn.

Co-Authored-By: Claude Opus 5 <[email protected]>
… map

The map was built for batches only, so a single row still scanned the table
for its one key. The scan was the smaller half of the problem: the row it
appends moves the table's row count without the map learning about it, so the
next batch finds the map stale and rebuilds it over every row. One interleaved
single-row upsert per batch was enough to put the whole quadratic back, and a
feed of snapshots followed by individual updates is exactly that shape.

A single row now takes the same path when the table carries a map: it probes
instead of scanning, and its append enters the map like a batch's does. It
still never builds one from nothing — without a table to hang it on a map
costs the scan it would replace and is then discarded, so the scratch map
stays gated to batches.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ar recursion

Non-linear rules such as p(X,Z) :- p(X,Y), p(Y,Z) lost tuples because the
fixpoint loop swapped the whole relation for its delta, so every occurrence
of p read the delta. dl_compile_rule now takes a dl_delta_t naming the one
body position that reads the delta. Audit 2026-09-08 §1.1.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
(?x :edge ?x) bound ?x to the first column and ignored the second. Atoms are
now pre-filtered on col_i == col_j for every repeated variable, in positive
and negated literals. Audit 2026-09-08 §1.2.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
(not (1 :edge 2)) was skipped entirely because the antijoin only ran with at
least one join key. Audit 2026-09-08 §1.3.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
…es error

A constant against a non-I64/SYM column silently passed every row through.
F64 columns now compare numerically against I64 or F64 literals; any other
column type is a type error. Audit 2026-09-08 §1.4.

Also updates datalog_coverage.rfl:416, whose pre-existing assertion relied
on F64 body constants being unsupported (an error) -- they are now a
supported, numerically-compared case, so the assertion becomes a 0-row
match instead of a type error.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
…ow; add F64-vs-I64 coverage

Review follow-up on the typed constant filter fix:

- dl_build_source_prov's constant body-slot match used a raw int64
  bit-compare instead of dl_col_eq_row, so an F64 literal against an
  I64/F64 column (now reachable since F64 body constants are
  supported) could silently mismatch. Route it through dl_col_eq_row.
- Add missing positive-match coverage for "I64 column vs F64 literal"
  (dl_col_eq_row's (double)cell == v branch): an ints EDB table in
  audit_regressions.rfl, and a second rule in
  test_const_filter_f64_column.
- Add test_source_prov_f64_const_body_slot exercising DL_FLAG_PROVENANCE
  with an F64 constant against an I64 column.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
find with more than DL_MAX_ARITY variables silently truncated to 16 columns;
an unknown body predicate produced an empty result. Both are errors now.
Audit 2026-09-08 §1.6, §7.3.

Updated tests that relied on the old empty-result behavior for an unknown
body predicate: test/test_lang.c (test_datalog_query_inline_rules — global
`foo` rule omitted by an inline rules clause is now genuinely unknown),
test/rfl/datalog/datalog_coverage.rfl ('weird predicate and the arity-
mismatched `tri` env table), and test/rfl/datalog/datalog_branch_cov.rfl
(`nonexistent-rel` and `no-such-pred`). Added
test/test_datalog.c:datalog/query_admission_errors to assert the specific
error messages via ray_error_msg().

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
dl_expr nodes were never freed and rules were shallow-copied between the
global registry, temporary query programs and the synthetic query rule.
dl_add_rule now deep-clones, dl_program_free frees, and parse-time rules are
freed after registration. Removes the 384 B/query growth measured in the
audit (2026-09-08 §2.1).

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
Two throw-away (.sys.mem) reads now precede the lb0 baseline capture, per
controller ruling: each (get (.sys.mem) 'bytes-allocated)) call retains its
own boxed result (a fixed ~64 B cost unrelated to the datalog engine), so
the baseline and final reads must be taken via the same warmed path.
Verified this residual does not scale with iteration count (200 vs 400
iterations from the same warmed baseline both read 64) and is present with
zero datalog code involved, confirming it is not a per-query leak. The
assertion is kept at the strict `-- 0` rather than loosened.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
The controller's proposed "read lresid then lresid2" compensation
provably never converges: each stored residual variable pays the exact
same fixed box cost it tries to measure, so the discrepancy is invariant
at 64 bytes no matter how many residual reads are chained (verified both
algebraically and empirically). Any number of throw-away warm-up reads
before lb0 has the same problem, since lb0 itself is always the last
stored reference point and its own box is paid *after* its value is
captured.

The actual fix: re-bind lb0 a second time immediately after the first.
The second `(set lb0 ...)` releases the first box and allocates a new,
identically-sized one -- net zero -- so lb0's own footprint is already
paid before the true baseline value is captured. Verified this converges
to exactly 0 at both 200 and 400 cumulative iterations, and that the test
correctly reports the real ~76800 B growth when dl_rule_free_exprs(&qrule)
is temporarily disabled in ray_query_fn (reverted after verification, no
functional change to src/ops/datalog.c).

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
…ield 0Nl

Expression evaluation used raw signed C operators (UBSan: signed integer
overflow at datalog.c:771). Overflow, division by zero, INT64_MIN/-1 and
null operands now produce NULL_I64, matching the host language. F64 division
follows IEEE like the host `/`. Audit 2026-09-08 §2.2.

Also updates test/rfl/datalog/datalog_branch_cov.rfl's two pre-existing
division-by-zero assertions, which encoded the old (now-fixed) behavior
(i64 div-by-zero summing to 0, f64 div-by-zero summing to 0.0) and would
otherwise fail against the corrected semantics.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
…integers

assert-fact stored a symbol as its bare intern id. Symbols are now stored
with the existing DATOM SYM tag that dl_col_eq_row already understands;
query projection, pull and scan-eav strip the tag so user-visible values are
unchanged. Audit 2026-09-08 §1.5.

Two additional fixes in the same file were required to make this correct:

- dl_datom_untag gained a sign-bit guard (v >= 0) before treating a cell as
  tagged: a negative plain integer has every high bit set by sign
  extension and was spuriously matching DL_DATOM_TAG_MASK, corrupting
  ordinary negative arithmetic results in query projection.

- dl_col_eq_row/dl_filter_eq gained a strict_tag parameter, set only for
  the eav relation's v column (the only column any frontend ever tags).
  Without it, the existing bare-equality fast path let a plain (untagged)
  integer stored via assert-fact match a SYM/STR literal by numeric
  coincidence with its intern id -- exactly the ambiguity this fix removes
  -- while every other column (the eav "a" column and rule-derived
  relations) still needs that lenient compare since they are never tagged.
  dl_set_body_pos was also fixed to evaluate an unquoted bare symbol body
  literal (e.g. a bound host-language variable) via ray_eval instead of
  treating it as a literal symbol constant sharing the identifier's name,
  matching how quoting (ATTR_QUOTED) is used everywhere else in eval.

Also updated test/rfl/datalog/datalog_branch_cov.rfl's "string literal in
body position" case: a "foo" STR literal no longer matches a value stored
via a 'foo SYM literal, since a string and a symbol are now distinct
values in the v column, same as an integer and a symbol are.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
… too

Controller ruling on Task 8 (audit §1.5): assert-fact only ever stores an
integer or a symbol as a value, so a "foo" STR literal in a triple pattern
can only mean the symbol named "foo" -- the pre-existing dl_set_body_pos
comment already interns a STR literal as a sym for exactly this reason.
Audit §1.5 is about integers vs symbols, not strings vs symbols.

Under strict_tag, dl_col_eq_row now matches a RAY_STR literal against a
DL_DATOM_TAG_SYM-tagged cell by payload (as well as a STR-tagged one,
should a future frontend ever write that tag). RAY_SYM still matches only
a SYM-tagged cell, and RAY_I64 still matches only a genuinely untagged
cell numerically.

Reverted the datalog_branch_cov.rfl "string literal in body position"
expectation back to its original -- 1 / comment, and added an
audit_regressions.rfl assertion that (?e :name "Alice") still matches
while Alice's fact is present, before the retract-fact line.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
Two more paths mutate a named table in place, and both sent the next batch
back to rebuilding the map over every row — which is the cost the map exists
to avoid. Interleaving either one per batch restored the whole quadratic.

insert appends without consulting keys, so it moved the row count while the
map learned nothing; the map then no longer described the table and the next
upsert rebuilt it. Entering the appended rows costs what the append already
cost, and insert appends in ascending row order, so the map's "duplicates
answer lowest row first" invariant survives. A map that cannot take them is
dropped rather than left naming a shorter table.

The where-update path dropped the map unconditionally. Only a write into a
key column can invalidate it — and that is the one mutation the recorded row
count cannot see, since a cell rewrite leaves the count alone. Any other
column leaves the mapping exactly as it was, so the drop is now conditional
on the update's target columns, which that path already resolves.

Co-Authored-By: Claude Opus 5 <[email protected]>
…c audit #1.5 fixes

Reviewer follow-up on Task 8:

1. ray_query_fn's SYM->I64 conversion for the eav table's v column (and
   the equivalent env-bound EDB conversion, guarded to only fire when that
   table is registered as DL_EAV_PRED) now OR's in DL_DATOM_TAG_SYM when
   converting column 2. A RAY_SYM column can only ever hold a symbol, so
   this is unambiguous; without it, a hand-built or deserialized datoms
   table whose v column is a real symbol vector silently matched 0 rows
   under strict_tag. A legacy I64 v column with bare (untagged) sym ids
   stays deliberately unmatched -- that is the ambiguity §1.5 removes.
   Added an audit_regressions.rfl case covering this.

2. Documented the value-range limit next to the DL_DATOM_* constants: a
   positive I64 value >= 2^61 in the v column (or in any I64 result column
   dl_untag_i64_col touches) is masked on output, since only the top 3
   bits are reserved for the tag/sign-guard.

3. dl_untag_i64_col's pre-scan now applies the same v >= 0 guard as
   dl_datom_untag, so an all-plain-possibly-negative column takes the
   no-op retain path instead of needlessly allocating.

4. dl_set_body_pos's ray_eval fallback now accepts a -RAY_STR value the
   same way the literal STR branch does (intern as sym, const_type
   RAY_STR), so `(set s "Alice")` + `(where (?e :name s))` agrees with
   the inline literal `(where (?e :name "Alice"))`.

5. Added a one-line comment at the head-argument parse site noting that,
   unlike body positions, a head position always treats a bare symbol as
   a literal constant, never a bound-variable reference.

6. Introduced DL_EAV_PRED "eav" in datalog.h and used it at every
   strict_tag gate, both dl_rule_add_atom/dl_rule_add_neg triple-pattern
   sites, dl_add_edb's registration of the primary table, and the
   env-bound EDB predicate-name skip, so the "this predicate's v column
   may be DATOM-tagged" coupling is explicit and lives in one place.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
…act and limits

Removes the claim that whole Datalog queries receive predicate pushdown /
fusion / rule-level join ordering. Audit 2026-09-08 §3, §5.

Claude-Session: https://claude.ai/code/session_019RxzDYWuuTMBmo9H8qcno5
ray_alloc_copy memcpys the whole 32-byte header, so a copied table carried the
RAY_IDX_UKEY pointer and ray_retain_owned_refs took a reference to it. 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 recorded
count makes that safe today — the second table finds the map stale and rebuilds
— but the map is meant to belong to one table, and ray_table_add_col copies a
table whenever a column is added. A copy now starts without it.

Co-Authored-By: Claude Opus 5 <[email protected]>
fix(datalog): audit correctness fixes (recursion, negation, types, leak, arithmetic)
… (n_aggs == 0) is not UB

A table `distinct` is executed as a grouped plan with no aggregates. Once the
input is large enough to take the hash group path, exec_group_run declared
`agg_outs[n_aggs]` / `agg_cols[n_aggs]` with n_aggs == 0. A zero-length VLA
is undefined behaviour; the release build tolerated it and answered
correctly, the default sanitized debug build aborted with "variable length
array bound evaluates to non-positive value 0".

Size both VLAs by the existing vla_aggs (= max(n_aggs, 1)) guard that the
function already uses for its other agg scratch. Every loop over them is
bounded by n_aggs, so behaviour is unchanged. Adds a regression .rfl with
the reported STR-key shape plus SYM and two-column keys.

Closes #515

Claude-Session: https://claude.ai/code/session_01UQRURGab9d9Fjma6uekEzY
fix(group): table distinct declared zero-length agg VLAs on the hash path (#515)
alter set retained its target before handing it to ray_cow, so ray_cow's own
`rc == 1` test could never be true and the copy path fired on every call. A
one-element write copied the whole vector: the cost of an alter scaled with
the vector's length rather than with the write, and 200 single-element writes
into a 4M vector spent half a second copying 32 MB at a time.

The retain is not the bug — it is there because ray_cow releases its input,
and handing it a borrow would decrement the binding's own reference. What was
missing is that sole ownership after that retain is `rc == 2`, the binding's
reference and alter's, which is the condition upsert's in-place path already
uses. Test for it directly and skip the copy.

The 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,
so all three still take the old path.

Co-Authored-By: Claude Opus 5 <[email protected]>
singaraiona and others added 29 commits September 13, 2026 12:55
…lision

fix(journal): preserve archives when rolls share a timestamp
…int of a value, for foreign-runtime GC accounting

Closes #522.  A binding that wraps a ray_t* in a finalized object had no
supported way to tell its collector how much native memory the wrapper
keeps alive; the OCaml binding registered every wrapper with zero dependent
bytes, so short-lived batches never raised GC pressure and RSS grew to the
finalizer horizon.

Two public functions with defined ownership semantics:

  ray_shallow_bytes(v)  — what v's own release gives back: the block the
    allocator committed for it (buddy block = power of two, direct block =
    its exact page-rounded mapping) plus private storage no public API
    hands out on its own and only v releases: a long STR / GUID atom's
    payload, a STR vector's pool, an attached accelerator index with its
    tables, a file-mapped column's mapping.  List elements, table and dict
    slots, lambda parts and a slice's parent are values in their own right
    and are NOT charged — a table and its separately wrapped columns are
    never counted twice.  Non-owning values (null / OOM singletons, arena
    values, borrowed blocks, a mapping-passenger index, the pool block
    inside a column's region) report 0.

  ray_retained_bytes(v) — shallow bytes of v and of everything reachable
    through ownership edges, each distinct block counted once (pointer set
    off-heap via ray_sys_alloc, so measuring never touches the heap).

Both are read-only mirrors of ray_release_owned_refs and of ray_free's
mapping arithmetic.  ray_index_child_blocks enumerates an index's payload
vectors for the walk (the same set retain/release visit).

Tests (test_heap.c): atoms incl. SSO vs out-of-line strings, vectors,
slices (header only; retained reaches the parent), STR pools, lists with a
shared element counted once, tables and dicts (columns not charged twice),
an attached hash index, and a 40 MB direct block reporting its page-rounded
mapping.  Documented in docs/c-api/core.md.

Claude-Session: https://claude.ai/code/session_017fCcYRuzNagw6nmLqZ9zbU
Groundwork for an in-place delete, which has to vacate the entries of the
rows it removes. Clearing a slot is not an option: the map is open addressing
with linear probing, so a hole in the middle of a chain ends the walk early
and orphans every entry displaced past it. A vacated entry becomes
UKEY_SLOT_TOMB and probing walks over it.

put keeps taking the first genuinely empty slot rather than reusing a
tombstone. Reuse would place a later row ahead of an earlier one in its
chain, which changes which of two duplicate keys a keyed upsert updates —
the map's one behavioural promise beyond finding a match at all.

Tombstones are counted because they hold a slot without being a row: a load
test that ignored them would let the array fill completely, and the free-slot
scan in put would then not terminate. kci narrows to int16 to keep the arm
inside the hash arm's 64 bytes, which the static assert pins — ray_index_t is
stored inline in persisted column files and must not grow.

Nothing creates a tombstone yet, so this changes no behaviour.

Co-Authored-By: Claude Opus 5 <[email protected]>
Removing rows meant `(set t (select {from: t where: <negated>}))`, which binds
a new table — and a fresh table starts without the upsert key map, so the next
batch rebuilt it over every row. On a 245k-row book the filter was a fifth of
a reset's cost and re-earning the map was the rest.

`(delete {from: 't where: P})` compacts the named table in place and patches
the map instead of discarding it. `(delete {from: t where: P})` answers with a
new table. Both evaluate P 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, which would be a second
expression to keep in step.

Compaction is a memmove of the runs between 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 no column needs a
per-cell path, and a boxed column only releases the cells it drops first. Row
order survives, so a sorted column stays sorted; an attached accelerator index
does not, and is dropped.

The map is patched, not rebuilt: 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 shifts. Entries naming a deleted row become
tombstones. An old-to-new row map is built in one pass so each slot costs O(1)
— asking a binary search per slot instead cost log(k) on every slot of the
capacity and dominated the patch. A large deletion is handed to the next
upsert instead, which rebuilds and reclaims the tombstones.

`where:` is required: a delete without one would empty the table, which is too
easy to reach by leaving a clause out.

The in-place gate is read before the predicate runs, because evaluating it
binds the table's columns into a query scope and the reference counts are only
quiet enough to test beforehand.

Co-Authored-By: Claude Opus 5 <[email protected]>
The in-place test reads the reference count of what ray_env_get returned, and
for a dotted name that is the leaf living inside the container — the vector in
a dict's vals list, or a table's column. That leaf usually holds the only
reference to itself, so it passes an rc test that says nothing about whether
the CONTAINER is shared:

  (set d (dict ['x] (list (til 3))))
  (set e d)
  (alter 'd.x set 0 99)
  e.x        ;; [0 1 2] before, [99 1 2] after

env_set_dotted COW-rebuilds the dict chain afterwards, but it cannot undo a
write that already landed in the shared leaf. The copy is what made this safe.
A table head is the same resolution and changed behaviour too: env_set_dotted
refuses it, so the amend used to be discarded, and in place it reached the
live column of the table and of every alias.

Exclude a dotted name from the fast path. The tests covered flat names only,
which is why nothing caught it.

Co-Authored-By: Claude Opus 5 <[email protected]>
…e misses

`from: 't` promises the binding is amended and the symbol comes back. The gate
can miss for reasons the caller cannot see — a column at rc 2 because a
literal in the parse tree holds it, a second binding on the table, an mmapped
or narrow-SYM column — and the copying form then returned the new table
without rebinding, so the binding kept all its rows and the caller got a value
it did not ask for. Every sibling verb rebinds on this path.

Two shapes the copying form also had no backstop for. A parted table's columns
carry the RAY_PARTED_BASE wrapper, which describes no flat element the
compaction could move; flatten once at entry, as ray_update does. A slice
column is a header-only view whose ray_data resolves 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, and the copying form now
refuses rather than corrupt a buffer somebody else owns.

Co-Authored-By: Claude Opus 5 <[email protected]>
…y_range as int64, not double

Closes #524.  A double is exact only to 2^53.  Two paths turned an i64 into
a double before an integer operation, so above 2^53 distinct integers
merged — and every TIMESTAMP (nanoseconds, ~8.4e17, double spacing 128 ns)
is such an integer:

  * ray_gt_fn / ray_lt_fn / ray_gte_fn / ray_lte_fn ended in
    `as_f64(a) OP as_f64(b)` for every numeric pair, integers included,
    while ray_eq_fn already compared integers as int64 — so two atoms could
    differ under == and be neither > nor < each other, and the dyadic
    min/max built on <=/>= returned the wrong operand.
  * The integer-output arms of binary_range (I64/TIMESTAMP, I32/DATE/TIME,
    I16, U8 — ADD SUB MUL DIV MOD MIN2 MAX2) and the integer-family BOOL arm
    read their operands through LV_READ/RV_READ, which widen to double, and
    cast back: each operand rounded to the nearest double before an exact
    integer op.  The exact readers (LV_READ_I64/RV_READ_I64) existed and
    were used only by OP_IDIV.

cmp.c: when both atoms are integer-family (I64/I32/I16/U8) the four
orderings compare as_i64; float, BOOL and char pairs keep the double
compare (their values are exact in a double).  expr.c: LV_INT/RV_INT read
exactly when both operands are integer-family (src_is_i64_all, loop
invariant) and keep the truncating double read for a float operand; every
integer-output arm and the integer BOOL arm use them.  The IDIV double
kernels and AND/OR truthiness (a nonzero test) are unchanged.  Vector-with-
atom comparisons, reductions and the constant folder were already exact.

Measured on 20 M-row I64 vector pairs (release): add 35 -> 30 ms, gt
17 -> 14 ms, sub/eq unchanged — the round trip through double is gone.

Test: test/rfl/ops/i64_exact_ordering.rfl — the issue's table (atoms,
vector-with-vector arithmetic and comparisons at 2^53 and 2^62, timestamp
differences and ordering) plus mixed widths, nulls and floats through the
same arms.

Claude-Session: https://claude.ai/code/session_017fCcYRuzNagw6nmLqZ9zbU
**A key wider than the map's arm left a stale map attached.** Above
RAY_UKEY_MAX_COLS the whole ukey block was skipped, so an already attached map
was neither refreshed nor dropped. 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 ukey_fits accepted
the map as fresh on the next call and a keyed upsert appended a duplicate key.
Drop the map instead of skipping.

**`.idx.drop` on a table carrying the map dereferenced NULL.** 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, and
reading it anyway crashed. Before the map a table never carried HAS_INDEX and
this was a no-op; return early when the index is already gone.

**`.mem.objsize` reported a mapped table as nothing but its map.** The
HAS_INDEX arm returns before the TABLE arm, which was harmless while only
vectors could carry an index. A 20k-row table measured 320 KB without the map
and 524 KB with it — the map alone, both columns skipped. Fall through for a
table.

Each fix has a regression case, and each was checked by putting the fault back.

Co-Authored-By: Claude Opus 5 <[email protected]>
fix(cmp, expr): order integer atoms and run the integer arms of binary_range as int64, not double
The footprint accounting added to dev walks an index's child blocks through a
fifth switch over ray_idx_kind_t, which this branch's new kind did not answer.
-Werror=switch caught it in the PR's merge-result build; a local build of the
branch alone does not see the new function at all.

Co-Authored-By: Claude Opus 5 <[email protected]>
The fix that clears it in ray_alloc_copy had no case of its own. What is
observable is that a second binding keeps its own rows: the upsert declines
the in-place path at rc 3 and works on a private copy, which must not inherit
a map describing rows it does not have.

Co-Authored-By: Claude Opus 5 <[email protected]>
The flatten-at-entry arm had no case. Both forms are pinned, including that
`from: 'p` rebinds the name to the flattened table — a behaviour change worth
having written down rather than discovered.

The slice guard next to it stays uncovered and says so: no producer reachable
from the language puts a slice into a table column, so it is defensive only.

Co-Authored-By: Claude Opus 5 <[email protected]>
feat(query): delete, an in-place row removal that keeps the key map
perf(alter): amend a sole-owned value in place instead of copying it
perf(query): keep the keyed-upsert key map on the table instead of rebuilding it
…the next release PR is up to date with its base
@singaraiona
singaraiona merged commit 78cc90d into master Sep 14, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants