(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module type SEMANTICS = sig type collation val key : collation -> string -> string val numeric : string -> float option end module type S = sig type collation type t = Seek | Hash | Scan val pp : Format.formatter -> t -> unit val equal : t -> t -> bool val max_rewinds : int val index_equality_rows : int val choose : rewinds:int -> inner_rows:int -> seek_yield:int -> covering:bool -> seek:bool -> hash:bool -> t val count_bound : rewinds:int -> next:bool -> int type budget = { cells : int; bytes : int } val budget : budget val over : budget -> cells:int -> bytes:int -> bool val row_bytes : Catalog.Value.t list -> int type key = { outer : Catalog.Cursor.t; outer_key : int; inner_key : int; collation : collation option; nulls : bool; } val probe : ?collation:collation -> ?nulls:bool -> ?rest:key list -> outer:Catalog.Cursor.t -> outer_key:int -> inner:Catalog.Value.t list list -> inner_key:int -> unit -> Catalog.Cursor.t val ordered : ?collation:collation -> key:int option -> by:int list -> Catalog.Value.t list list -> Catalog.Value.t list list type seek_key = Bound of Catalog.Value.t | Column of Catalog.Cursor.t * int val seek : lookup:((string * Catalog.Value.t) list -> Catalog.Value.t list list option) -> scan:Catalog.Value.t list list Lazy.t -> (string * seek_key) list -> Catalog.Cursor.t end module Make (Sem : SEMANTICS) = struct module Cursor = Catalog.Cursor module Register = Catalog.Register module Value = Catalog.Value type collation = Sem.collation type t = Seek | Hash | Scan let pp ppf = function | Seek -> Format.pp_print_string ppf "seek" | Hash -> Format.pp_print_string ppf "hash" | Scan -> Format.pp_print_string ppf "scan" let equal a b = a = b type budget = { cells : int; bytes : int } (* The memory a join may hold, in cells and in payload bytes. A row count measures the wrong thing: a wide table and a table of blobs both cost far more than their row count says. Two million cells is a million rows at the two-column width, and the byte budget is that bound reached by payload. *) let budget = { cells = 2_000_000; bytes = 192 * 1024 * 1024 } let over b ~cells ~bytes = cells > b.cells || bytes > b.bytes let row_bytes row = List.fold_left (fun n -> function | Value.Text s | Value.Blob s -> n + String.length s | Value.Null | Value.Int _ | Value.Float _ -> n) 0 row (* The cost model. Both algorithms answer the same rows, so what separates them is what each pays to find them, in units of one row read through an index: - a seek pays a b-tree [descent] every time the loop rewinds it, then reads back the rows its key selects, and holds nothing; - a hash pays [build] per row of the inner relation -- one read, and the memory to hold it for the whole loop -- and answers each rewind with a bucket [probe], the rows already in hand. The rows a key selects are charged to the seek, which re-reads them from storage on every rewind. A covering index carries every column the query reads, so a row is in hand; a non-covering one pays a second [fetch] descent to get it: seek = rewinds * (descent + seek_yield * (1 + if covering then 0 else fetch)) hash = (inner_rows + 1) * build + rewinds * probe and the seek is cheaper exactly while rewinds * (descent + seek_yield * row - probe) <= (inner_rows + 1) * build. The [+ 1] is the table a hash builds, paid whether or not the relation has rows: an empty source is not free to hash, and a seek that holds nothing is still the better answer for one. Only the ratio of the constants matters. [build] prices memory, not time: a seek holds nothing where a hash holds the whole inner relation. [fetch] and [descent] separate what a descent costs from what the rows it hands back cost. *) let descent = 2 let fetch = 2 let probe = 1 let build = 12 (* sqlite3's own default where no ANALYZE data exists: an equality on a non-unique index selects about ten rows. It is the most a seek is assumed to read back per rewind, which is what {!count_bound} sizes for. *) let index_equality_rows = 10 (* How far the accumulated rewind estimate is worth tracking. Past this a loop is large enough that nothing tells it from a larger one, and saturating under-states the rewinds, which errs towards the seek -- the bounded error. *) let max_rewinds = 100_000 let row ~covering = if covering then 1 else 1 + fetch let excess ~seek_yield ~covering = descent + (seek_yield * row ~covering) - probe let choose ~rewinds ~inner_rows ~seek_yield ~covering ~seek ~hash = if seek && rewinds * excess ~seek_yield ~covering <= (inner_rows + 1) * build then Seek else if hash then Hash else if seek then Seek else Scan let count_bound ~rewinds ~next = let rewinds = max 1 rewinds in (* the fewest rows at which {!choose} already answers the seek, for the widest bucket a seek is assumed to read back and the dearest way of reading it: past it no further row can move the answer *) let want = rewinds * excess ~seek_yield:index_equality_rows ~covering:false in let decides = max 0 (((want + build - 1) / build) - 1) in (* and, where a source follows, far enough to estimate how often that one is rewound, a product that saturates at [max_rewinds] *) if next then max (max_rewinds / rewinds) decides else decides (* ---- Equi-join cursors --------------------------------------------------- The VM joins by rewinding the inner cursor once per outer row, so an inner cursor that rewinds onto only the rows carrying the outer's key turns that nested loop into a hash join, with no change to the VM. The two cursors are built together because the inner has to see where the outer stands. Hashing has to agree with the equality the engine applies afterwards, or a matching row would never be offered, and that equality is looser than structural equality on the stored value: - integers and reals compare across their types, so a numeric key is canonicalised to a float -- which can merge two distant int64s, but that only offers extra candidates, and the join predicate still runs on every one; - text compares under the comparison's collating sequence, so a text key is the bytes that sequence orders by ({!SEMANTICS.key}), and a NOCASE join buckets ["ABC"] with ["abc"]; - a numeric column coerces a text/blob operand by affinity, so [5] equals ['5']. A build-side text that spells a number is therefore filed under that number as well, and a probing text is looked up under both its own bytes and the number it spells. NULL equi-matches nothing and is left out of the table entirely, but under an IS key, whose NULL matches NULL, where it is filed under a key of its own. Every pair the engine's comparison accepts lands in one bucket; the extra candidates the coarseness offers cost a re-check, which the caller's join predicate runs anyway. *) type hash_key = Num of float | Str of string | Bytes of string | Null (* The hash of a number key: an integer-valued one hashes as that integer, so [0.0] and [-0.0], which compare equal, hash alike; any other through the runtime's hash, which hashes every NaN alike. *) let hash_number f = if Float.is_integer f && Float.abs f < 0x1p62 then int_of_float f else Hashtbl.hash f module Numbers = Hashtbl.Make (struct type t = float let equal = Float.equal let hash = hash_number end) module Keys = Hashtbl.Make (struct type t = hash_key let equal a b = match (a, b) with | Num x, Num y -> Float.equal x y | Str x, Str y | Bytes x, Bytes y -> String.equal x y | Null, Null -> true | (Num _ | Str _ | Bytes _ | Null), _ -> false let hash = function | Num f -> hash_number f | Str s -> Hashtbl.hash s | Bytes s -> Hashtbl.hash s lxor 1 | Null -> 0 end) (* SQLite's numeric affinity on a comparison's text/blob operand: the whole trimmed text read as a number, or [None] when it does not spell one (which leaves it text, and text never equals a number). *) let as_number = Sem.numeric (* The rows one key selects, in table order, with their places in the build side, by which two buckets merge back into table order. A build fills a bucket in arrays it doubles, its first [n] slots the rows so far, and cuts them to [n] once it is done. *) type bucket = { mutable places : int array; mutable rows : Value.t array array; mutable n : int; } let empty () = { places = [||]; rows = [||]; n = 0 } let one i row = { places = [| i |]; rows = [| row |]; n = 1 } let push b i row = if b.n = Array.length b.places then begin let size = max 4 (2 * b.n) in let places = Array.make size 0 and rows = Array.make size [||] in Array.blit b.places 0 places 0 b.n; Array.blit b.rows 0 rows 0 b.n; b.places <- places; b.rows <- rows end; b.places.(b.n) <- i; b.rows.(b.n) <- row; b.n <- b.n + 1 let cut b = if b.n < Array.length b.places then begin b.places <- Array.sub b.places 0 b.n; b.rows <- Array.sub b.rows 0 b.n end (* The build side of a probe: every inner row filed under the key(s) a matching outer value would look it up by, each key's rows held as the bucket a lookup answers, built once. *) type probe = { (* the rows keyed by a text, a blob or NULL *) keyed : bucket Keys.t; (* each number's rows: those keyed by it and the text/blob ones that spell it, which a numeric outer value coerces by affinity *) numbers : bucket Numbers.t; (* the column of a row its key is in *) key : int; collation : collation option; nulls : bool; } (* The bytes a text keys by under [collation]: its own where it has none. *) let text_key collation s = match collation with Some c -> Sem.key c s | None -> s let probe_of_rows ?collation ?(nulls = false) ~key (rows : Value.t array array) = let n = Array.length rows in let keyed = Keys.create 16 and numbers = Numbers.create (max 16 n) in let add_key k i row = match Keys.find keyed k with | b -> push b i row | exception Not_found -> Keys.add keyed k (one i row) in let add_number f i row = match Numbers.find numbers f with | b -> push b i row | exception Not_found -> Numbers.add numbers f (one i row) in let spelled s i row = match as_number s with Some f -> add_number f i row | None -> () in for i = 0 to n - 1 do let row = rows.(i) in match row.(key) with | Value.Null -> if nulls then add_key Null i row | Value.Int v -> add_number (Int64.to_float v) i row | Value.Float f -> add_number f i row | Value.Text s -> add_key (Str (text_key collation s)) i row; spelled s i row | Value.Blob s -> add_key (Bytes s) i row; spelled s i row done; Keys.iter (fun _ b -> cut b) keyed; Numbers.iter (fun _ b -> cut b) numbers; { keyed; numbers; key; collation; nulls } let rows_array rows = Array.of_list (List.map Array.of_list rows) let find p k = match Keys.find p.keyed k with b -> b | exception Not_found -> empty () (* The rows of [a] and [b], two buckets of one build side, in table order. *) let merge a b = let na = Array.length a.places and nb = Array.length b.places in if nb = 0 then a.rows else if na = 0 then b.rows else let rows = Array.make (na + nb) [||] in let i = ref 0 and j = ref 0 in for k = 0 to na + nb - 1 do if !j >= nb || (!i < na && a.places.(!i) < b.places.(!j)) then begin rows.(k) <- a.rows.(!i); incr i end else begin rows.(k) <- b.rows.(!j); incr j end done; rows (* A numeric outer value matches the numeric build keys equal to it, and the text/blob ones that spell it. *) let probe_number p f = match Numbers.find p.numbers f with | b -> b.rows | exception Not_found -> [||] (* The bucket of [p]'s numbers that holds the rows keyed by the number [f], the texts and blobs that spell it left out. *) let numeric p f = let b = empty () in (match Numbers.find p.numbers f with | all -> Array.iteri (fun i row -> match row.(p.key) with | Value.Int _ | Value.Float _ -> push b all.places.(i) row | Value.Null | Value.Text _ | Value.Blob _ -> ()) all.rows | exception Not_found -> ()); cut b; b (* A text/blob outer value matches the build keys of its own storage class -- collated for text, raw for a blob -- and, when it spells a number, the numeric build keys that number equals. *) let probe_string p key s = let hits = find p key in match as_number s with | Some f -> merge hits (numeric p f) | None -> hits.rows let probe_null p = if p.nulls then (find p Null).rows else [||] let probe_value p = function | Value.Null -> probe_null p | Value.Int n -> probe_number p (Int64.to_float n) | Value.Float f -> probe_number p f | Value.Text s -> probe_string p (Str (text_key p.collation s)) s | Value.Blob s -> probe_string p (Bytes s) s (* The same lookup straight off a register, so an outer row streaming through a cursor is probed without allocating a {!Value.t} for its key. *) let probe_mem p (m : Register.t) = match m.Register.kind with | Register.Null -> probe_null p | Register.Int -> probe_number p (float_of_int m.Register.i) | Register.Bigint -> probe_number p (Int64.to_float m.Register.big) | Register.Real -> probe_number p m.Register.r | Register.Text -> probe_string p (Str (text_key p.collation m.Register.s)) m.Register.s | Register.Blob -> probe_string p (Bytes m.Register.s) m.Register.s (* The key a row is filed under by {!probe_of_rows}, a text or a blob that spells a number aside: that one is filed under its number too. *) let filing collation = function | Value.Null -> Null | Value.Int n -> Num (Int64.to_float n) | Value.Float f -> Num f | Value.Text s -> Str (match collation with Some c -> Sem.key c s | None -> s) | Value.Blob s -> Bytes s let spells_number = function | Value.Text s | Value.Blob s -> Option.is_some (as_number s) | _ -> false (* The places of [n] rows, each group [group] puts them in sorted by [compare], the groups in the order of their first rows. *) let sorted_groups n ~group ~compare = let groups = Hashtbl.create n and firsts = ref [] in for i = n - 1 downto 0 do let g = group i in match Hashtbl.find_opt groups g with | Some places -> places := i :: !places | None -> Hashtbl.add groups g (ref [ i ]); firsts := g :: !firsts done; let places = Array.make n 0 and at = ref 0 in List.iter (fun g -> let group = Array.of_list !(Hashtbl.find groups g) in Array.stable_sort compare group; Array.blit group 0 places !at (Array.length group); at := !at + Array.length group) (List.rev !firsts); places (* The rows at the places [a] and [b] by their values in the columns [by] from the [i]th on, then by place. *) let rec compare_places by a b i = if i = Array.length by then Int.compare a b else match Value.compare by.(i).(a) by.(i).(b) with | 0 -> compare_places by a b (i + 1) | c -> c let ordered ?collation ~key ~by rows = match by with | [] -> rows | by -> let held = Array.of_list rows in let n = Array.length held in let column k = Array.map (fun row -> List.nth row k) held in let by = Array.of_list (List.map column by) in let compare a b = compare_places by a b 0 in let keys = Option.map column key in let places = match keys with | Some keys when not (Array.exists spells_number keys) -> (* each bucket a probe yields is one key's rows *) sorted_groups n ~group:(fun i -> filing collation keys.(i)) ~compare | _ -> (* a bucket of every row, or one a text or a blob spelling a number joins to its number's *) let places = Array.init n Fun.id in Array.stable_sort compare places; places in Array.fold_right (fun p acc -> held.(p) :: acc) places [] type key = { outer : Cursor.t; outer_key : int; inner_key : int; collation : collation option; nulls : bool; } (* One level of a multi-key probe: the rows every earlier key selected, in table order, hashed on this level's key the first time an outer row reaches it, with the level below memoised per outer value. Each level is the single-key probe, so every key keeps its own matching rules. *) type level = { rows : Value.t array array; mutable hashed : probe option; below : (Value.t, level) Hashtbl.t; } let level rows = { rows; hashed = None; below = Hashtbl.create 1 } let hashed l (k : key) = match l.hashed with | Some p -> p | None -> let p = probe_of_rows ?collation:k.collation ~nulls:k.nulls ~key:k.inner_key l.rows in l.hashed <- Some p; p (* The rows every key selects for where the outer cursors stand. NULL selects nothing but under an IS key. *) let rec lookup scratch l = function | [] -> l.rows | [ k ] -> k.outer.Cursor.column k.outer_key scratch; probe_mem (hashed l k) scratch | k :: rest -> ( k.outer.Cursor.column k.outer_key scratch; if Register.is_null scratch && not k.nulls then [||] else let v = Register.to_value scratch in match Hashtbl.find_opt l.below v with | Some sub -> lookup scratch sub rest | None -> let sub = level (probe_value (hashed l k) v) in Hashtbl.add l.below v sub; lookup scratch sub rest) (* The inner half alone, for a caller whose outer rows stream from a store rather than a list: the outer cursors are handed back untouched, and the inner reads where they stand through their own [column]. *) let probe ?collation ?(nulls = false) ?(rest = []) ~(outer : Cursor.t) ~outer_key ~inner ~inner_key () = let first = { outer; outer_key; inner_key; collation; nulls } in let keys = first :: rest in let top = level (rows_array inner) in (* the first key is hashed up front, as a single-key probe always was *) ignore (hashed top first); let scratch = Register.v () in let bucket = ref [||] and bidx = ref (-1) in let load () = bucket := lookup scratch top keys in let column j m = Register.set_value m !bucket.(!bidx).(j) in { Cursor.rewind = (fun () -> load (); bidx := 0; !bidx < Array.length !bucket); next = (fun () -> incr bidx; !bidx < Array.length !bucket); column; (* these rows are already materialised, so their identity is gone *) rowid = (fun () -> None); reader = Cursor.column_reader column; push = None; } type seek_key = Bound of Value.t | Column of Cursor.t * int let seek ~lookup ~scan keys = let scratch = Register.v () in let value = function | Bound v -> v | Column (c, j) -> c.Cursor.column j scratch; Register.to_value scratch in let whole = lazy (rows_array (Lazy.force scan)) in let rows = ref [||] and idx = ref 0 in let load () = let eqs = List.map (fun (col, k) -> (col, value k)) keys in rows := if List.exists (function _, Value.Null -> true | _ -> false) eqs then [||] else match lookup eqs with | Some found -> rows_array found | None -> Lazy.force whole in let column j m = Register.set_value m !rows.(!idx).(j) in { Cursor.rewind = (fun () -> load (); idx := 0; !idx < Array.length !rows); next = (fun () -> incr idx; !idx < Array.length !rows); column; (* a key selects rows, not their identity *) rowid = (fun () -> None); reader = Cursor.column_reader column; push = None; } end [@@inline]