radiance 1.14.0

New models and formats:
- libr3d: a kernel library for RDNA3 (gfx11) cards
- nomic-embed-text-v2-moe (the nomicbert plugin)
- Gemma 4 E2B with its per-layer MLP width, and Google's unmodified E2B/E4B directories in bf16
- DeepSeek-V4.1-Flash converted straight from its release: the Engram tables, the fused imatrix and
  rad-convert --chat-template for a release that ships no template
- GGUF Q8_0, Q4_K and Q6_K tensors import as their planes; rad-convert writes them without a recipe
- Qwen3.8-Flash-Next-FP8 converts and serves through qwen4exp_fp8

Speed:
- hc_read's decode kernels as one grid (34.7 -> 25.2 us at 4 rows) and its tiled up-mix pipelined
- gemm_fp8a8: the narrow form's scales staged through LDS (Flash-Next int8 at 32 rows 83.6 -> 68.3
  us), the gated three-tile form at 8 waves (gate_up at 48 rows 272.9 -> 180.6 us)
- Qwen3.8-27B: the delta net's out-projection read beside its decode recurrent update (x1 19.40 ->
  19.10 ms a step), and the verify's split-KV attention sized by context depth (x3 at 180K 42.4 ->
  40.3 ms a step)
- Hy-Memory (HYV3) decode: fused QK norm, RoPE and KV store, residual adds folded into the norms,
  coalesced one-token expert GEMMs
- spechub: the coupled verify walks the live candidates only (151 -> 31 us a launch)

Speculation:
- DFlash2: lossless coupled acceptance at T > 0 (--draft-coupling on)
- A block drafter's proposals verified as a tree, on by default for the Gemma 4 31B's DFlash2, with
  a block-16 tree that runs its short block under load

Features:
- Decode-hot residency: --draft-expert-placement host, --expert-profile, --expert-pin-top, and
  --expert-stats FILE for the routed experts each layer selects
- --ngram-placement ram=DIR: one n-gram table shared by engines on separate cards
- Prefix cache: --prefix-resume exact (default) resumes a hit on the cold run's own chunk grid, so it
  answers bit-identically; snapshots at a head other prompts share, from 528-token prompts, and for
  tip-only one drafter window below the tip; hits on models whose KV groups have different block
  sizes; the snapshot store keeps a floor of 8 ahead of --host-headroom-mib
- Typed tool-call argument tags; rad-chatparse --request renders and reads back one request as the
  server does
- MiniMax-H3: keyframes ride a latent upscale
- Gemma 3's fused all-reduce junction on the lossy wire

Fixes:
- A speculative step shorter than its band (an MTP step of 4 rows at gqa 8) no longer stops the
  engine with a scratch refusal at issue (#293)
- --p2p off: prefill back to 1.12.0's rate; 1.13.0's push check read a host-memory slot over the link
  twice (#323)
- A chat template that cannot render a conversation is refused at load, not mid-request
- imatrix entries found under llama.cpp's spelling; the W4A8 prefill's tail scale read; the GDN conv
  kernels on an f32 weight; dense integer rows at the group they compute (a Q8_0 weight at group 32)
- --expert-profile refuses a profile recorded on another model
- hc_read's one-grid wait traps past its deadline instead of reading a stale value

Changes: Plugin ABI 31, unchanged. RADIANCE_DRAFT_TREE, DFLASH2_TREE_NODES, DFLASH2_TREE_TEMP and
DFLASH_Q_TEMP are gone (trees run where the probe says they pay; temperatures 1.25 / 0.6).
This commit is contained in:
Deadcode committed 2026-10-29 12:04:24 +01:00
1 parent 481fcd5df0
commit 4a61d7296b
160 files changed
+8790 -6819

No files matched your search

+39 -12
View File
@@ -237,8 +237,8 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
RadModelMeta& m = out->m;
/* Nomic BERT states its geometry with n_layer, n_embd, n_head, n_inner, n_positions and
* moe_top_k. They are fallbacks in the same chain, so a config carrying both spellings keeps
* the HuggingFace one and every existing checkpoint reads byte for byte as before. */
* moe_top_k. They are the last fallbacks in each chain, so a config carrying both spellings
* reads the HuggingFace one. */
m.n_layers = gi("num_hidden_layers", gi("n_layer", 0));
m.n_embd = gi("hidden_size", gi("n_embd", 0));
m.n_head = gi("num_attention_heads", gi("n_head", 0));
@@ -274,18 +274,21 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4): the
* quant_method plus its fmt ("fp8_e4m3"), so the checkpoint, not a flag, distinguishes fp8 from
* bf16 releases.
* bf16 releases. transformers' fine-grained FP8 states no fmt (Qwen3.8-Flash-Next-FP8's config)
* and is always E4M3, so a bare "fp8" is "fp8_e4m3", as a release that states it is.
*
* A Gemma 4 E2B/E4B checkpoint states no quantization_config: it is the bf16 release that
* arch/gemma4_bf16 serves as compressed-tensors, which is what rad-convert's
* `--set quantization_config.quant_method=compressed-tensors` said by hand. Its per-layer
* embeddings or shared KV layers name the E form; arch/gemma4 serves only the 26B-A4B/31B shape
* and refuses those two keys, so the bare (gemma4, "") descriptor must not win. */
* A Gemma 4 E2B/E4B checkpoint states no quantization_config: it is a bf16 release that
* arch/gemma4_bf16 serves under "compressed-tensors", so it needs no
* `--set quantization_config.quant_method=compressed-tensors`. Its per-layer embeddings or shared
* KV layers name the E form; arch/gemma4 serves only the 26B-A4B/31B shape and refuses those two
* keys, so the bare (gemma4, "") descriptor must not win. */
std::string quant_descriptor(const MetaOwn& m) {
std::string q;
if (const char* qm = m.get("quantization_config.quant_method")) {
q = qm;
if (const char* fm = m.get("quantization_config.fmt")) { q += "_"; q += fm; }
const char* fm = m.get("quantization_config.fmt");
if (!fm && q == "fp8") fm = "e4m3";
if (fm) { q += "_"; q += fm; }
return q;
}
if (m.arch == "gemma4") {
@@ -2401,6 +2404,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
* RAD_MAP_COPY alternatives, first present wins (a tied lm_head is output.weight when
* shipped, else the embedding). */
const bool alternatives = maps.front()->mode == RAD_MAP_COPY && srcs.size() > 1;
/* Pieces whose scale is one `X.weight_scale` their shards share (below). */
bool shard_scaled = false;
for (const Src1& s1 : srcs) {
const SrcTensor* st = ck.find(s1.name);
/* An FP8 weight's scale plane: `X.weight_scale_inv` (block-scaled releases) or
@@ -2410,6 +2415,17 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
const SrcTensor* sc = st ? ck.find(std::string(s1.name) + "_scale_inv") : nullptr;
if (!sc && st && (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2))
sc = ck.find(std::string(s1.name) + "_scale");
/* A table split into shards, `X.shard_<i>.weight`, under one scale for all of them,
* `X.weight_scale` (Qwen3.8-Flash-Next-FP8's n-gram table). */
if (!sc && st && (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2)) {
const std::string n = s1.name;
const size_t at = n.rfind(".shard_");
const size_t end = n.size() >= 7 ? n.size() - 7 : 0;
if (at != std::string::npos && end > at + 7 && n.compare(end, 7, ".weight") == 0 &&
std::all_of(n.begin() + (long)at + 7, n.begin() + (long)end,
[](char c) { return c >= '0' && c <= '9'; }))
if ((sc = ck.find(n.substr(0, at) + ".weight_scale"))) shard_scaled = true;
}
/* A weight shipped in an imported form is read through that form's views. */
{
const SrcTensor *ic = nullptr, *is = nullptr;
@@ -2501,8 +2517,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
out->why = std::string("'") + p0.name + "' is a GGUF " +
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
/* Q8_0, Q4_K and Q6_K become their planes when every piece is of that type and they join
* along rows, so each row of the weight is one source row of blocks; the loader still
* refuses them, since the blocks interleave what the planes hold apart. */
* along rows, so each row of the weight is one source row of blocks. rad-convert imports
* them; the loader refuses them, since the blocks interleave what the planes hold apart. */
bool one_type = true;
for (const SrcTensor* pk : out->pieces) one_type = one_type && pk->ggml == p0.ggml;
RadEncoding enc;
@@ -2693,7 +2709,18 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
bad = true;
out->why = "its FP8 pieces are joined along a column, across their scale planes";
}
if (!bad) {
/* Shards under the one scale they share are one tensor with one scale, byte for byte:
* `fp8_e4m3*<s>[*x*]`. */
bool one_scale = !bad && shard_scaled && n_one == (int)out->pieces.size();
for (size_t k = 1; one_scale && k < out->scales.size(); ++k)
one_scale = out->scales[k] == out->scales[0];
if (one_scale) {
out->trivial = out->why.empty();
rad_enc_clear(&out->enc);
rad_enc_copy_str(out->enc.scheme, "affine");
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
rad_enc_add_plane(&out->enc, "scale", sdt, 0, 0);
} else if (!bad) {
out->trivial = out->why.empty() && n_one == 0;
/* A per-tensor scale is written once a row (ckpt_plane_rows). */
if (n_one) {
+2 -2
View File
@@ -63,13 +63,13 @@ inline void put_nibbles(uint8_t* row, const uint8_t* q, int n) {
row[k] = (uint8_t)((q[2 * k] & 15) | ((q[2 * k + 1] & 15) << 4));
}
/* Q4_K: value v is a nibble of qs[32*(v/64) + v%32], the low one for the first 32 of each 64. The
* 6-bit scale and min of sub-block j are get_scale_min_k4's. */
/* Q4_K: value v is a nibble of qs[32*(v/64) + v%32], the low one for the first 32 of each 64. */
inline uint32_t k_low4(const uint8_t* qs, int v) {
const uint8_t q = qs[32 * (v / 64) + v % 32];
return (uint32_t)((v % 64) < 32 ? q & 15 : q >> 4);
}
/* Q4_K: the 6-bit scale and min of sub-block j, as llama.cpp's get_scale_min_k4 unpacks them. */
inline void k4_scale_min(int j, const uint8_t* q, uint32_t* d, uint32_t* m) {
if (j < 4) {
*d = q[j] & 63u;
+15 -10
View File
@@ -14,6 +14,20 @@
namespace rad {
int table_copy_check(const uint8_t* src, int64_t n, const uint8_t* buf, std::string* why) {
if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
const int64_t probe = std::min<int64_t>(n, 4096);
bool same = std::memcmp(buf, src, (size_t)probe) == 0 &&
std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0;
for (int64_t o = 0; same && o + 4096 <= n; o += std::max<int64_t>(n / 64, 4096))
same = std::memcmp(buf + o, src + o, 4096) == 0;
if (!same) {
*why = "the copy does not match the container's mapping";
return RAD_E_IO;
}
return RAD_OK;
}
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
uint8_t* buf, std::string* why) {
if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
@@ -45,16 +59,7 @@ int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t
*why = fmt("reading the container failed (%s)", rad_strerror(err.load()));
return RAD_E_IO;
}
const int64_t probe = std::min<int64_t>(n, 4096);
bool same = std::memcmp(buf, src, (size_t)probe) == 0 &&
std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0;
for (int64_t o = 0; same && o + 4096 <= n; o += std::max<int64_t>(n / 64, 4096))
same = std::memcmp(buf + o, src + o, 4096) == 0;
if (!same) {
*why = "the copy does not match the container's mapping";
return RAD_E_IO;
}
return RAD_OK;
return table_copy_check(src, n, buf, why);
}
int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
+5
View File
@@ -32,6 +32,11 @@ int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
uint8_t* dst, std::string* why);
/* The check table_copy_fill ends with, on its own: samples of [buf, buf + n) against [src, src + n)
* (the first and last 4 KiB and 64 spread between). RAD_OK, or RAD_E_IO with `why`. For a copy
* another process filled. */
int table_copy_check(const uint8_t* src, int64_t n, const uint8_t* buf, std::string* why);
/* Unlock and unmap; a no-op for a copy never made. */
void table_copy_free(TableCopy* c);
+261
View File
@@ -0,0 +1,261 @@
/* table_share.cpp -- see table_share.h. */
#include "table_share.h"
#include "../rad_internal.h"
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <unistd.h>
#include <cerrno>
#include <climits>
#include <cstdlib>
#include <cstring>
namespace rad {
namespace {
constexpr char kMagic[8] = { 'R', 'A', 'D', 'N', 'G', 'R', 'M', '1' };
constexpr uint32_t kVersion = 1;
constexpr int64_t kHuge = (int64_t)2 << 20;
/* A leaving holder tries for LOCK_EX for about a second (table_share_close). */
constexpr int kLeaveTries = 10;
constexpr unsigned kLeaveWaitUs = 100 * 1000;
/* All integers host-endian: the file lives in a tmpfs, so it never leaves the machine. */
struct Header {
char magic[8];
uint32_t version;
uint32_t ready;
uint64_t bytes;
uint64_t filler_pid; /* for whoever reads the file by hand; nothing depends on it */
char id[24]; /* the 16 hex digits and a NUL */
};
static_assert(sizeof(Header) <= 4096, "the header must fit the first page");
enum class Seen { Fresh, Partial, Ready, Foreign };
std::string errno_text() { return std::strerror(errno); }
/* What the open data file holds. A fresh file and a half-filled one have a zero header; a header
* that is not this protocol's or not for this table is Foreign. */
Seen classify(int fd, const std::string& id, int64_t n, std::string* why) {
struct stat st{};
if (::fstat(fd, &st) != 0) {
*why = fmt("fstat: %s", errno_text().c_str());
return Seen::Foreign;
}
if (st.st_size == 0) return Seen::Fresh;
Header h{};
const ssize_t got = ::pread(fd, &h, sizeof h, 0);
if (got != (ssize_t)sizeof h) {
*why = fmt("its header is %lld bytes short", (long long)(sizeof h - (got < 0 ? 0 : got)));
return Seen::Foreign;
}
Header zero{};
if (std::memcmp(&h, &zero, sizeof h) == 0) return Seen::Partial;
if (std::memcmp(h.magic, kMagic, sizeof kMagic) != 0 || h.version != kVersion) {
*why = "it is not a table file of this version";
return Seen::Foreign;
}
if (h.bytes != (uint64_t)n || std::strncmp(h.id, id.c_str(), sizeof h.id) != 0) {
*why = fmt("it holds %s of table '%.16s', not %s of '%s'", humanb((int64_t)h.bytes).c_str(),
h.id, humanb(n).c_str(), id.c_str());
return Seen::Foreign;
}
if (!h.ready) return Seen::Partial;
if (st.st_size != table_share_file_bytes(n)) {
*why = fmt("it is marked ready but is %lld bytes long, not %lld", (long long)st.st_size,
(long long)table_share_file_bytes(n));
return Seen::Foreign;
}
return Seen::Ready;
}
std::string file_path(const std::string& dir, const std::string& id) {
const bool slash = !dir.empty() && dir.back() == '/';
return dir + (slash ? "" : "/") + "ngram-" + id + ".tab";
}
void fail(TableShare* s) {
if (s->lock_fd >= 0) ::close(s->lock_fd);
if (s->fd >= 0) ::close(s->fd);
*s = TableShare{};
}
} /* namespace */
int64_t table_share_file_bytes(int64_t n) {
return kTableShareHeader + ((n + kHuge - 1) & ~(kHuge - 1));
}
std::string table_share_id(const std::string& container_path, int64_t foff, int64_t n) {
char real[PATH_MAX];
const std::string path = ::realpath(container_path.c_str(), real) ? std::string(real)
: container_path;
struct stat st{};
if (::stat(path.c_str(), &st) != 0) return std::string();
uint64_t h = 1469598103934665603ull;
auto feed = [&](const void* p, size_t len) {
const unsigned char* b = static_cast<const unsigned char*>(p);
for (size_t i = 0; i < len; ++i) h = (h ^ b[i]) * 1099511628211ull;
};
const int64_t parts[] = { (int64_t)st.st_size, (int64_t)st.st_mtim.tv_sec,
(int64_t)st.st_mtim.tv_nsec, foff, n };
feed(path.data(), path.size());
feed(parts, sizeof parts);
return fmt("%016llx", (unsigned long long)h);
}
int table_share_open(const std::string& dir, const std::string& id, int64_t n, TableShare* out,
std::string* why) {
if (!out || !why || dir.empty() || id.empty() || n <= 0) return RAD_E_INVAL;
*out = TableShare{};
out->path = file_path(dir, id);
out->lock_path = out->path + ".lock";
/* A holder that left last deletes the file while we open it: its unlink comes with LOCK_EX, so
* once we hold LOCK_SH the link count says whether the file is still the one in the directory. */
for (;;) {
out->fd = ::open(out->path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
if (out->fd < 0) {
*why = fmt("opening %s: %s", out->path.c_str(), errno_text().c_str());
*out = TableShare{};
return RAD_E_IO;
}
if (::flock(out->fd, LOCK_SH) != 0) {
*why = fmt("locking %s: %s", out->path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
struct stat st{};
if (::fstat(out->fd, &st) != 0) {
*why = fmt("fstat %s: %s", out->path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
if (st.st_nlink > 0) {
struct statfs fs{};
if (::fstatfs(out->fd, &fs) == 0 && (long)fs.f_type != 0x01021994L &&
(long)fs.f_type != 0x858458f6L)
RAD_WARN("n-gram table share: %s is not on a tmpfs or ramfs, so the table is "
"written to its disk and held in the page cache", dir.c_str());
break;
}
::close(out->fd);
}
std::string seen_why;
Seen seen = classify(out->fd, id, n, &seen_why);
if (seen == Seen::Foreign) {
*why = fmt("%s exists, and %s", out->path.c_str(), seen_why.c_str());
fail(out);
return RAD_E_INVAL;
}
if (seen == Seen::Ready) {
out->ready = true;
return RAD_OK;
}
out->lock_fd = ::open(out->lock_path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
if (out->lock_fd < 0) {
*why = fmt("opening %s: %s", out->lock_path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
if (::flock(out->lock_fd, LOCK_EX) != 0) {
*why = fmt("locking %s: %s", out->lock_path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
/* The holder we waited for may have finished. */
seen = classify(out->fd, id, n, &seen_why);
if (seen == Seen::Foreign) {
*why = fmt("%s exists, and %s", out->path.c_str(), seen_why.c_str());
fail(out);
return RAD_E_INVAL;
}
if (seen == Seen::Ready) {
::close(out->lock_fd);
out->lock_fd = -1;
out->ready = true;
return RAD_OK;
}
if (::ftruncate(out->fd, table_share_file_bytes(n)) != 0) {
*why = fmt("sizing %s to %s: %s", out->path.c_str(),
humanb(table_share_file_bytes(n)).c_str(), errno_text().c_str());
fail(out);
return RAD_E_NOMEM;
}
out->filler = true;
return RAD_OK;
}
int table_share_mark_ready(TableShare* s, int64_t n, const std::string& id, std::string* why) {
if (!s || !why || s->fd < 0 || !s->filler || id.size() >= sizeof(Header::id))
return RAD_E_INVAL;
Header h{};
std::memcpy(h.magic, kMagic, sizeof kMagic);
h.version = kVersion;
h.ready = 1;
h.bytes = (uint64_t)n;
h.filler_pid = (uint64_t)::getpid();
std::memcpy(h.id, id.c_str(), id.size());
if (::pwrite(s->fd, &h, sizeof h, 0) != (ssize_t)sizeof h) {
*why = fmt("writing the header of %s: %s", s->path.c_str(), errno_text().c_str());
return RAD_E_IO;
}
if (s->lock_fd >= 0) {
::close(s->lock_fd);
s->lock_fd = -1;
}
s->ready = true;
return RAD_OK;
}
void table_share_close(TableShare* s) {
if (!s) return;
if (s->lock_fd >= 0) ::close(s->lock_fd);
if (s->fd >= 0) {
/* Engines stopped together (a compose recreate) leave together: one that tries while the
* other still holds LOCK_SH, unpinning the table, is not the last, and the other may be
* killed at the stop timeout before its own try, which leaves the table in the tmpfs. So
* this holder lets go of LOCK_SH and tries for a while. It holds no lock from here on
* until LOCK_EX is granted; a conversion would not keep it either, since a refused one
* has already dropped LOCK_SH (flock(2): not atomic). LOCK_EX may then come on a file
* another holder already deleted, with a new engine's file at its name, so only the file
* the name still points to is deleted. The lock file goes first: nobody gets past
* LOCK_SH on this file to use it, while a file made anew at the name the moment this one
* is gone could already have a filler on it. */
(void)::flock(s->fd, LOCK_UN);
for (int i = 0; i < kLeaveTries; ++i) {
if (::flock(s->fd, LOCK_EX | LOCK_NB) == 0) {
struct stat mine{}, named{};
if (::fstat(s->fd, &mine) == 0 && ::stat(s->path.c_str(), &named) == 0 &&
mine.st_dev == named.st_dev && mine.st_ino == named.st_ino) {
::unlink(s->lock_path.c_str());
::unlink(s->path.c_str());
}
break;
}
if (errno != EWOULDBLOCK && errno != EINTR) break;
if (i + 1 < kLeaveTries) ::usleep(kLeaveWaitUs);
}
::close(s->fd);
}
*s = TableShare{};
}
bool table_share_is_ready(const std::string& dir, const std::string& id, int64_t n) {
if (dir.empty() || id.empty() || n <= 0) return false;
const int fd = ::open(file_path(dir, id).c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) return false;
std::string why;
const bool ready = classify(fd, id, n, &why) == Seen::Ready;
::close(fd);
return ready;
}
} /* namespace rad */
+69
View File
@@ -0,0 +1,69 @@
/* table_share.h -- an n-gram table as a file in a tmpfs that engines on separate cards share
* (--ngram-placement ram=DIR). Each engine maps the file MAP_SHARED and pins it for its own cards,
* so the host holds one copy however many engines read it. This is the file protocol only; the
* mapping and the pinning are the device layer's (rad_dev_map_file).
*
* The file is `DIR/ngram-<id>.tab`: a header in its first 2 MiB, the table from kTableShareHeader
* on, so the table keeps the 2 MiB alignment the pinned ranges want. The id names the container
* and the table's place in it, so a file never serves another model.
*
* Every holder keeps LOCK_SH on the data file for its life, which counts the readers. The first
* engine to find the file unready takes the fill lock (LOCK_EX on `<file>.lock`, a file of its
* own so that a later engine arriving while the table is read never waits behind the readers),
* fills the table and marks it ready; an engine arriving meanwhile waits on the fill lock and then
* finds it ready. The holder that gets LOCK_EX on the data file when it leaves is the last, and
* deletes the file and the lock file; one that leaves while another still holds LOCK_SH waits a
* moment for it, since engines stopped together leave together. A holder that died took its locks
* with it: a half-filled file is filled again, a ready one is reused after the same sample check
* as a fresh copy. */
#pragma once
#include <cstdint>
#include <string>
namespace rad {
/* The table's offset in the file. */
constexpr int64_t kTableShareHeader = (int64_t)2 << 20;
/* The file's length for an n-byte table: the header, then the table rounded up to 2 MiB. */
int64_t table_share_file_bytes(int64_t n);
/* The smallest table worth a shared file. A file costs the header and the table's rounding to
* 2 MiB, up to 4 MiB beside the table, and a tmpfs entry that outlives a crash; a weight of a few
* bytes the gather reads beside the table (its one-element scale) would cost more that way than as
* a private copy in every engine. From 16 headers on the file's overhead is under an eighth of the
* table; a smaller one takes the private pinned copy. */
constexpr int64_t kTableShareMin = 16 * kTableShareHeader;
struct TableShare {
int fd = -1; /* the data file, LOCK_SH held until table_share_close */
int lock_fd = -1; /* the fill lock, held while `filler` and not yet marked ready */
std::string path, lock_path;
bool ready = false; /* the table in the file is complete */
bool filler = false; /* this holder fills it, then calls table_share_mark_ready */
};
/* FNV-1a 64 over the container's real path, size and mtime (to the nanosecond), the table's file
* offset and its length, as 16 hex digits; empty if the container cannot be stat'ed. */
std::string table_share_id(const std::string& container_path, int64_t foff, int64_t n);
/* Open or create DIR/ngram-<id>.tab for an n-byte table and take part in the protocol: afterwards
* `out->ready` (map it and check samples) or `out->filler` (map it, fill [kTableShareHeader, +n),
* mark it ready). RAD_E_INVAL if a file of that name does not hold a table of this id and length
* (another program's, or another version's; never overwritten, since a live engine may map it),
* RAD_E_IO if the directory or file cannot be used. `why` carries the reason. */
int table_share_open(const std::string& dir, const std::string& id, int64_t n, TableShare* out,
std::string* why);
/* The filler's table is complete: write the header, release the fill lock. */
int table_share_mark_ready(TableShare* s, int64_t n, const std::string& id, std::string* why);
/* Leave. The last holder deletes the file and its lock file; while another still holds the file,
* this waits up to about a second for it to leave first. Safe on a TableShare never opened. */
void table_share_close(TableShare* s);
/* Whether DIR/ngram-<id>.tab is a complete table of n bytes now, read from its header without
* taking part: for the placement decision, which must know before anything is pinned. */
bool table_share_is_ready(const std::string& dir, const std::string& id, int64_t n);
} /* namespace rad */