]> git.hungrycats.org Git - bees/log
bees
5 weeks agoconfig: do not resolve a pinned version through newer schemas next
Zygo Blaxell [Sat, 10 Oct 2026 18:59:20 +0000 (14:59 -0400)]
config: do not resolve a pinned version through newer schemas

version_chain() consulted a version's ancestors and then its
descendants, so a key the selected version did not define resolved to
the value a newer schema introduced it with.  A configuration pinned to
an old version then changes behaviour whenever a newer schema adds an
option, which is what pinning is meant to prevent.

Resolve a version through itself and its ancestors only, and drop
next_version(), which only the descendant walk used.  Every key the code
reads must now be defined in the oldest schema; version 1 gained the
two it was missing in the previous commit, and test_builtin_versions()
already fails if any version cannot resolve a key another version
defines.

Update the version_chain(), config.version and --show-builtin-config
descriptions to match, and say in the version 1 file comment that new
options get a key there too, at the value that keeps v0.11 behaviour.

Assisted-by: Claude-Code:claude-opus-5-5
5 weeks agoconfig-v1: define the keys version 2 added, at their v0.11 values
Zygo Blaxell [Sat, 10 Oct 2026 18:59:14 +0000 (14:59 -0400)]
config-v1: define the keys version 2 added, at their v0.11 values

Version 2 added thread.workaround-clone-logical-ino and
resolve.commit-root, and version 1 has neither.  A configuration pinned
to version 1 or v0.11 finds them only by reading forward into version
2, so it gets version 2's defaults (auto and yes) instead of v0.11
behaviour.

v0.11 did not serialize dedupe against LOGICAL_INO, and it resolved
references against the live tree.  Give version 1 both keys with those
values (no and no).  Version 2 already states its own defaults, so it
is unaffected.

Assisted-by: Claude-Code:claude-opus-5-5
5 weeks agofd: delete Fd::operator bool so "if (fd)" fails to compile
Zygo Blaxell [Sat, 10 Oct 2026 18:50:13 +0000 (14:50 -0400)]
fd: delete Fd::operator bool so "if (fd)" fails to compile

Fd has operator int() and operator!(), but no operator bool.  In a
boolean context such as "if (fd)", "fd && x" or "fd ? a : b", the
compiler converts through operator int, and an empty Fd is -1, which
is true.  "!fd" works, which makes the positive form look safe when it
is not.  Several such tests have crept in.

Declare an explicit, deleted operator bool.  An explicit conversion is
only considered in boolean contexts, where it is an exact match and
wins over operator int, so those uses now fail to compile.  Conversions
to int are unaffected.  Test an Fd with "!!fd" or "!fd".

Assisted-by: Claude-Code:claude-opus-5-5
5 weeks agotest: fix always-true Fd check in rm_rf
Zygo Blaxell [Sat, 10 Oct 2026 18:50:13 +0000 (14:50 -0400)]
test: fix always-true Fd check in rm_rf

"if (dir)" converts the Fd to int, so a failed open (-1) is true and
fdopendir(dup(-1)) runs.  Use "!!dir".

The test came in with commit
54d1cb5b63c7aad574a684a81440f0adccbc4fdf
("fd: add safer_path_walk for safer multi-component traversal").

Assisted-by: Claude-Code:claude-opus-5-5
5 weeks agohash: test m_fd with !! before the close-time fsync
Zygo Blaxell [Sat, 10 Oct 2026 18:50:13 +0000 (14:50 -0400)]
hash: test m_fd with !! before the close-time fsync

"m_close_fsync && m_fd" converts the Fd to int, so an empty Fd (-1)
passes the test and bees_fsync(-1) runs on close.  Use "!!m_fd".

The test came in with commit
937af86331421ac58eeef089d5ab1623edc5b1e0
("state: add persistent state config and memory-only hash table").

Assisted-by: Claude-Code:claude-opus-5-5
5 weeks agofdcache: skip the NOCOW check when open_root_ino fails
Zygo Blaxell [Sat, 10 Oct 2026 18:50:13 +0000 (14:50 -0400)]
fdcache: skip the NOCOW check when open_root_ino fails

Fd converts to int, and an empty Fd is -1, so "new_fd && !allow_nocow"
is true even when open_root_ino() returned no file.  The NOCOW check
then calls ioctl_iflags_get(-1), which throws EBADF instead of letting
the empty Fd fall through as a failed open.

Test the Fd with "!!new_fd".  The bug came in with commit
1be459412c17caf276f415fed24cc6a76bfc400e
("fdcache: consolidate root/inode opens into BeesFdCache").

Assisted-by: Claude-Code:claude-opus-5-5
6 weeks agoconfig: default workaround-clone-logical-ino to auto
Zygo Blaxell [Thu, 24 Sep 2026 02:22:25 +0000 (22:22 -0400)]
config: default workaround-clone-logical-ino to auto

With resolve.commit-root defaulting to yes, "auto" keeps the
clone/LOGICAL_INO serialization exactly as long as it can matter:  until
the kernel has shown it walks the commit root.  On kernels without the
COMMIT_ROOT flag, and with resolve.commit-root = no, it behaves as "yes".

Assisted-by: Claude-Code:claude-opus-5-5
6 weeks agothread: add workaround-clone-logical-ino = auto
Zygo Blaxell [Thu, 24 Sep 2026 02:12:49 +0000 (22:12 -0400)]
thread: add workaround-clone-logical-ino = auto

The clone/LOGICAL_INO kernel bug needs LOGICAL_INO walking the same live
trees that dedupe is modifying.  A LOGICAL_INO call with the COMMIT_ROOT
flag walks the commit root instead, so once the kernel has shown it
honours the flag the serialization only costs throughput.

Add an "auto" value.  It starts serialized like "yes", and logical_ino()
switches locking off once resolve.commit-root = yes and a call with the
flag has succeeded (commit_root_confirmed()).  The serialization stays
if resolve.commit-root = no, while support is unknown, and when the
kernel is proven not to support the flag.

The option is now loaded by BeesContext next to resolve.commit-root,
since logical_ino() needs the mode, instead of being applied once in
bees_main.  The kind table entry becomes Kind_Free because the value is
no longer a plain boolean.  The default stays "yes".

Assisted-by: Claude-Code:claude-opus-5-5
6 weeks agocrucible: report when COMMIT_ROOT support has been confirmed
Zygo Blaxell [Thu, 24 Sep 2026 02:11:14 +0000 (22:11 -0400)]
crucible: report when COMMIT_ROOT support has been confirmed

commit_root_supported() stays true while support is unknown, which is
what callers need when deciding whether to keep setting the flag.  A
caller that wants to relax something only once the kernel has actually
walked a commit root needs the stronger answer.

Add commit_root_confirmed(), true once a call with the flag has
succeeded.  Make the probe state atomic, since other threads now read
it.

Assisted-by: Claude-Code:claude-opus-5-5
6 weeks agomultilock: allow locking to be switched off at runtime
Zygo Blaxell [Thu, 24 Sep 2026 02:10:47 +0000 (22:10 -0400)]
multilock: allow locking to be switched off at runtime

enable_locking() was only called once, before any worker thread started,
so a plain bool was enough.  Deciding at runtime whether the
clone/LOGICAL_INO serialization is still needed means flipping it while
other threads are in get_lock().

Make the flag atomic and document what a change affects:  only later
get_lock() calls.  Held handles still release through put_lock(), and
threads already waiting are still granted as the holders drain.

Assisted-by: Claude-Code:claude-opus-5-5
6 weeks agothread: add workaround-clone-logical-ino config option
Zygo Blaxell [Wed, 24 Jun 2026 15:16:56 +0000 (11:16 -0400)]
thread: add workaround-clone-logical-ino config option

The dedupe (clone) ioctl and LOGICAL_INO must not run concurrently on
some kernels, so bees serializes them through MultiLocker.  This was
hardcoded on via MultiLocker::enable_locking(true) in bees_main.

Expose the behaviour as a boolean [thread] option,
workaround-clone-logical-ino, defaulting to yes (the prior hardcoded
behaviour).  When set to no, locking is disabled and any thread may run
either operation at any time, which is faster but unsafe on affected
kernels.  bees_main now passes the configured value straight to
enable_locking().

The option is consumed once at startup and handed to a static method, so
it needs no member in BeesContext or BeesRoots.  Document it in the
built-in config and docs/config-file.md.

Assisted-by: Claude-Code:claude-opus-4-8
6 weeks agocontext: describe the tightened COMMIT_ROOT support probe
Zygo Blaxell [Wed, 23 Sep 2026 18:37:34 +0000 (14:37 -0400)]
context: describe the tightened COMMIT_ROOT support probe

The comment said the kernel rejects the flag "once"; libcrucible now
confirms the rejection by repeating the call without the flag before it
stops setting it.

Assisted-by: Claude-Code:claude-opus-5-5
6 weeks agocrucible: prove COMMIT_ROOT is unsupported before dropping it
Zygo Blaxell [Wed, 23 Sep 2026 18:37:34 +0000 (14:37 -0400)]
crucible: prove COMMIT_ROOT is unsupported before dropping it

LOGICAL_INO_V2 returns EINVAL for any bad argument, not only for an
unknown flag bit.  Treating the first EINVAL with the COMMIT_ROOT flag
as proof the kernel lacks it would drop the flag for the rest of the
process whenever the first resolve happened to have bad arguments for
some other reason.

Track support as unknown, supported, or unsupported.  A successful call
with the flag proves support.  While support is unknown, a call with the
flag that fails with EINVAL is repeated without the flag, and only the
success of that repeat proves the flag unsupported.  If the repeat also
fails, the answer stays unknown and the next call probes again.  Once
support is proven, an EINVAL with the flag is returned as is.

Assisted-by: Claude-Code:claude-opus-5-5
6 weeks agoconfig: default resolve.commit-root to yes
Zygo Blaxell [Wed, 23 Sep 2026 03:49:23 +0000 (23:49 -0400)]
config: default resolve.commit-root to yes

The LOGICAL_INO_V2 commit-root flag is in the upstream kernel now, under
the same name, so the case for holding a tree mod log sequence across
every resolve by default is gone.  The kernel-side cost of a live-root
walk is paid by everything else running on the filesystem, not by bees,
and it is largest on exactly the heavily shared extents bees spends its
time resolving.

The staleness a commit-root answer carries is one transaction of other
writers' changes, which bees already tolerates as churn.  The one case
where a stale list did real damage -- an extent that had just served as
a dedupe source being re-planned as a destination from a list missing
the references that dedupe created -- was a planner defect, not a
property of the flag, and the earlier measurements that showed the
commit-root arm recovering less space were taken with that defect in
place.  Drop that claim from the docs rather than carry a number that
no longer describes the option.

Kernels without the flag still reject it once and bees falls back to
live-root walks, so the new default costs nothing where it cannot help.

Assisted-by: Claude-Code:claude-fable-5-1
6 weeks agoconfig: add resolve.commit-root, defaulting to off
Zygo Blaxell [Sun, 20 Sep 2026 03:35:05 +0000 (23:35 -0400)]
config: add resolve.commit-root, defaulting to off

LOGICAL_INO can resolve against the commit roots instead of the live
tree.  The kernel-side argument for doing so is that a live-root walk
holds a tree mod log sequence number for the duration of the walk, which
makes every node-level tree change anywhere on the filesystem allocate
unreclaimable slab until the walk finishes, and puts the walk in
contention with the commit thread for tree locks and delayed ref head
mutexes.  The walks that run long enough for this to matter are exactly
the walks of heavily shared extents, which is what bees spends its time
resolving:  four walkers on a 32047-way shared block group have been
observed stalled for over an hour with 13.6 GiB of 16 GiB in
unreclaimable slab.

Make it a configuration key rather than a decision baked into the
source, and default it to off.  The cost of a commit-root answer is that
it can be up to one transaction stale, and a reference list that is
stale is a reference list bees plans against and then finds incomplete.

Measured on a mixed real-data corpus, asking for the commit root
recovered 58.17 GiB where a live-root walk recovered 60.73 GiB, and took
3.45 hours to converge against 2.62.  Each individual resolve was
substantially cheaper -- 1.12 ms per walk against 2.08, and 28% less
total time in the ioctl -- but the arm executed 61% more destination
plans to land slightly fewer dedupe hits.  Its verification failure rate
was 3.95% against 0.54%.

A single-threaded run on a synthetic corpus separates the two more
sharply, because bees is the only mutator and every verification failure
is therefore a planning defect.  Across four commit-root runs the
failure count ranged from 28 to 43 and the space recovered from 1.37 to
2.04 GiB; the live-root arm on the same corpus failed zero verifications
and recovered 4.44 GiB.  The ranges do not overlap.  Note that a
single-threaded run is not deterministic:  transid boundaries follow the
kernel commit timer against wall clock, so where a dedupe lands relative
to a commit still moves between runs.

The kernel-side argument is about what bees does to concurrent balance
and snapshot-delete work, not about what bees does for itself, and it is
not visible in bees' own numbers.  An operator weighing those against
each other can now do it without rebuilding.

Log once, at warning level, if the kernel turns out not to implement the
flag, so the log distinguishes "asked for the commit root" from "asked,
was refused, and is walking live roots after all".

The stored value is an optional<bool> with no default, so a path that
reaches logical_ino() without set_config() having run throws instead of
quietly picking a side.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agocrucible: support LOGICAL_INO_V2 commit-root resolution
Zygo Blaxell [Sat, 19 Sep 2026 08:09:05 +0000 (04:09 -0400)]
crucible: support LOGICAL_INO_V2 commit-root resolution

The live-root backref walk attaches to the running transaction and holds
a tree mod log sequence number for the duration of the walk.  While any
sequence is live, every node-level tree change anywhere in the filesystem
is recorded in the tree mod log, which is allocated from unreclaimable
slab and trimmed only below the oldest live sequence.  A walk of a
heavily shared block group can therefore hold the log open long enough
for it to consume most of a machine's memory, while the walking threads
sit behind the commit thread.

BTRFS_LOGICAL_INO_ARGS_COMMIT_ROOT asks for the answer as of the last
committed transaction instead.  No sequence is taken, so nothing is
logged, and the walk does not contend with the commit thread for tree
locks or delayed ref head mutexes.  The results are otherwise identical,
up to one transaction stale.

Kernels without the flag reject it with EINVAL before starting the walk,
exactly as they reject any undefined flag bit, so do_ioctl_nothrow()
retries once without it and remembers not to set it again for the life
of the process.  Callers can therefore set the flag unconditionally;
commit_root_supported() only reports whether a rejection has happened.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agofs: make FILE_EXTENT_SAME failures self-describing
Zygo Blaxell [Sun, 24 May 2026 19:09:18 +0000 (15:09 -0400)]
fs: make FILE_EXTENT_SAME failures self-describing

The old error dumped the raw btrfs_ioctl_same_args struct after the
source path.  With long backup-snapshot pathnames the line was
truncated before the destination offset, so the log rarely contained
enough to understand or reproduce the failure.

Emit the parameters of dedupe_file_range directly: the src file and
offset, the length, and every dst file and offset.  That is the full
set of inputs needed to replay the ioctl by hand.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agolog: clear the output stream error state after each line
Zygo Blaxell [Mon, 31 Aug 2026 20:31:06 +0000 (16:31 -0400)]
log: clear the output stream error state after each line

A failed write to the log destination latches badbit on the output
stream, and ostream discards every subsequent insertion for as long as
it stays set.  Nothing in bees ever checks or clears it, so a single
transient write error silences the daemon permanently: it keeps
scanning, deduping and updating its status file, but never writes
another log line, and exits 0 at the end as if nothing happened.

This is not hypothetical.  A test run logging to a virtiofs mount
stopped emitting after five minutes and stayed silent for the next
half hour while continuing to work normally; strace confirmed the
process had stopped issuing writes to the log fd entirely.  The same
binary and configuration logging to local disk ran past that point and
kept going.

The line that hit the error is lost either way, and retrying it risks
blocking behind a destination that is still broken, so drop it and
reset the state instead.  One bad write then costs one line rather
than the remainder of the run.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agotask: let the TaskState instance registry outlive static destruction
Zygo Blaxell [Mon, 31 Aug 2026 07:17:31 +0000 (03:17 -0400)]
task: let the TaskState instance registry outlive static destruction

~TaskState() takes s_instance_mutex, asserts on s_instance_map[m_id] and
erases from it.  Both were ordinary file-scope statics, so both are
destroyed when main() returns -- and a TaskState can be destroyed long
after that, by a thread that has no idea main() is gone.

TaskConsumer threads are detached and never joined.  TaskMasterState is
owned by shared_ptrs those threads hold, so whichever thread drops the
last reference runs ~TaskMasterState, and with it the destructors of
every TaskState still queued.  That thread is routinely a consumer, not
main.  Instrumented runs show the ordering directly:

    tid=2146948  ~TaskMaster           <- on a consumer thread
    tid=2146940  STATIC_DTORS_BEGIN    <- main starts static destruction
    tid=2146948  ~TaskState            <- 3.4 us later, touches the map

A destroyed std::map is worse than stale.  erase() frees nodes its own
destructor already freed, and operator[] inserts into freed storage, so
the failure is a heap-use-after-free or a double-free rather than a
missing entry -- which is what AddressSanitizer reports, always in a
worker thread, always after the last test has passed.

Make the mutex and the map references to deliberately leaked objects.
Nothing frees them, so nothing can use them after they are freed.  Every
call site is unchanged, and the cost is one pointer load where there was
none: holding them behind a shared_ptr would give the same lifetime
guarantee, but would put atomic refcount traffic on TaskState
construction and destruction, which is the one path a task system cannot
afford it on.  s_instance_count needs no such treatment and gets a
static_assert saying why: it is trivially destructible, so its storage
stays valid and nothing is freed.

Leaking at exit costs nothing here.  The daemon does not run destructors
at all -- BeesContext::stop_running() ends in _exit(EXIT_SUCCESS), "skip
all destructors, do not pass GO" -- so this only ever mattered to
programs that return from main(), which is to say the test suite.

Measured with an AddressSanitizer build of test-bees-borrower under
8-way concurrent load, which is what the race needs (it does not
reproduce serially): 47 reports in 3000 runs before, 0 in 3000 after.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agodocs: say what --show-builtin-config resolves
Zygo Blaxell [Mon, 31 Aug 2026 01:56:54 +0000 (21:56 -0400)]
docs: say what --show-builtin-config resolves

The description said the command writes "the built-in configuration for
VERSION", which reads as the contents of the schema file with that name.
It is not: a schema states only the keys it changes, so the command
flattens the whole inheritance chain and prints what the version resolves
to.

The distinction is the one a reader is most likely to get wrong, because
the surprising half looks like a bug -- asking for version 1 lists
options version 1 has never heard of.  Say why that is right (a daemon
pinned to that version resolves them too), and say what happens where the
versions disagree (the selected version's value wins), with the concrete
case.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agoconfig: stop the config dump repeating section comments on keys
Zygo Blaxell [Mon, 31 Aug 2026 01:55:54 +0000 (21:55 -0400)]
config: stop the config dump repeating section comments on keys

Innie::get_comment() answers "what documents this key", and falls back to
the section's comment for a key that has none of its own.  That is right
for a lookup and wrong for the dump, which writes section comments in
their own place: a key with no comment was handed its section's, so the
paragraph appeared twice, once above the [section] header and again above
the key, with the key reading as if the text described it.

    # Built-in domain; same 64-bit keys as bees v0.11.  function has no
    # default, so each [hash.NAME] sets its own: crc64, cityhash, ...

    [hash.crc64]

    # Built-in domain; same 64-bit keys as bees v0.11.  function has no
    # default, so each [hash.NAME] sets its own: crc64, cityhash, ...

    function = crc64

Skip a key comment that is the section comment already written.  Both the
key walk and the section walk climb the same default-section chain and
consult the same fallback layers, so equality is what "this key had
nothing of its own" looks like from here.

The key is left with the indent comment Innie::set() seeds it with, which
is what an uncommented key is supposed to look like on the way out.

hash.crc64.function is the only key either schema defines with a section
comment and no comment of its own, so it is the only line that changes in
--show-builtin-config for both versions.  This is the mirror image of the
masking case in test-innie-comment: there the fallback wrongly wins, here
it wrongly fires.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agotest: point the innie comment regression at its real source
Zygo Blaxell [Mon, 31 Aug 2026 00:49:25 +0000 (20:49 -0400)]
test: point the innie comment regression at its real source

The regression case names the integration test it was captured from, and
that test is called 11-show-config.  The embedded config's own header
comment named a dump mode that no longer exists.

Both are prose in a test that still exercises the same masking bug; this
just makes the trail back to the integration case land somewhere.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agoconfig: remove the last of the untrusted local-config machinery
Zygo Blaxell [Mon, 31 Aug 2026 00:50:52 +0000 (20:50 -0400)]
config: remove the last of the untrusted local-config machinery

Support for an untrusted local config file was removed, but three pieces
of it stayed behind because nothing referred to them by that name any
more.

BeesStringFile::allow_symlink() has no callers.  It existed so the
untrusted local-config reader could opt out of the resolve-beneath-dirfd
open and follow a symlink on the target filesystem; with that reader
gone, m_allow_symlink is set at construction and never changed, and the
bees_openat2() branch it guards is unreachable.  Delete the flag, the
setter, and the branch.  The surviving open is the one that was actually
running, so behaviour is unchanged.  The path-components check keeps its
THROW_CHECK and gets a comment saying what it is really for -- the
atomic rename in write() renames within m_dir_fd, and a name with a
slash in it would name some other directory.

The local-config-filename load site says only "now we can load local
configuration data", which does not explain why the absolute-path rule
below it exists.  Say it: a config file living on the filesystem being
deduplicated is writable by whoever controls that filesystem, and every
knob in it -- thread counts, transid lag, hash table size -- is a way to
make the daemon behave badly.  ${ROOT} is how to opt back in on purpose.

Finally, point the config-file documentation at --show-config, which is
how an operator answers "what did it actually load", and fix the startup
log line that labelled path.reports with the old plural section name.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agotest: keep kinds for option names the schemas no longer define
Zygo Blaxell [Mon, 31 Aug 2026 01:09:34 +0000 (21:09 -0400)]
test: keep kinds for option names the schemas no longer define

The kind table is required to be exhaustive: an option with no kind
fails, so that coverage cannot shrink by accident.  That makes the table
a hard dependency on which options exist, and options get renamed --
candidate-max became candidate-max-count, candidate-pool-max became
candidate-max-bytes, and the neighbor-*-max pair was dropped outright.

A table that tracked only the schemas in this build would fail on any
tree whose schemas differ: a development branch carrying newer options,
or a bisect landing between a rename and this test.  The failure would
name a real option and a real value, and mean nothing.

Keep the retired names.  The table is a dictionary from option name to
kind, not a census of what is currently defined, and an entry nothing
looks up costs nothing.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agoconfig: align the config header prose with what the code does
Zygo Blaxell [Mon, 31 Aug 2026 00:46:32 +0000 (20:46 -0400)]
config: align the config header prose with what the code does

Four comments in bees-config.h were written before the schema versions
inherited from one another and no longer describe the code under them.
m_builtin is not "compiled-in defaults" any more -- it holds the one
selected version and is kept for its origin label, with the rest of the
chain hanging off m_innie.  set_version_defaults accepts release aliases
as well as CURRENT and STABLE.  innie() had picked up a description of
the only caller that existed when it was added.  And version_chain's note
about the two walk directions read as if the ordering were a preference
rather than the fact that the two sets cannot overlap.

No behaviour change; this is the prose catching up.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agotest: check every schema version still parses
Zygo Blaxell [Mon, 31 Aug 2026 00:45:09 +0000 (20:45 -0400)]
test: check every schema version still parses

A released schema version is frozen, so its values stop tracking the
parsers that read them.  Tighten bees_parse_size and a literal written for
an earlier release can quietly stop being accepted, with nothing to notice
until a daemon that pinned that version fails to start -- on whichever
option happened to be read first, which says nothing about the real
problem.  Chaining guarantees an option is present; it says nothing about
whether the value is still valid.

Check both properties for every registered version.  Every option any
version defines has to resolve from every version, and every value has to
parse as the kind that option is declared to have.

Kinds are keyed by option name, since an option means the same thing in
each section it appears in, with full section.key overriding the two
places that is not true.  The table has to be exhaustive: an option
without a kind fails the test rather than going unchecked, because
coverage that shrinks silently is worse than none.

Substitution variables are resolved against the filesystem at startup and
a unit test has none, so the test substitutes stand-in values instead of
skipping those options.  They are the most complex expressions in the
schema -- state.hash.size and thread.thread-max among them -- and are
exactly the ones worth parsing.

config-parse now links the version objects; without them nothing is
registered and the test would pass while checking nothing.
BeesConfig::registered_versions() exposes the list, so the test covers
whatever a build registers rather than a copy of it that can drift.

Verified by mutation: misclassifying an option's kind, or dropping one
from the table, each fail with the version, option and value named.

Assisted-by: Claude-Code:claude-opus-5
6 weeks agotest: cover ceil(), bees_parse_size_double(), and the thread-max shape
Zygo Blaxell [Mon, 31 Aug 2026 00:43:35 +0000 (20:43 -0400)]
test: cover ceil(), bees_parse_size_double(), and the thread-max shape

Add expect_size()/expect_size_double() helpers to config-parse and
exercise the size-expression grammar, which was previously untested here.
Cover the ceil() function (rounding up, one-argument arity, missing-paren
rejection), the default thread-max shape max(1, ceil(...)), and the double
variant that loadavg-target relies on -- including the contrast that the
integer bees_parse_size() truncates "0.5" to 0 while
bees_parse_size_double() preserves it.  The ${...} substitutions need a
live filesystem and are left to the integration tests; these cases use
literal operands.

Assisted-by: Claude-Code:claude-opus-4-8
Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: correct the Register documentation
Zygo Blaxell [Mon, 31 Aug 2026 00:43:08 +0000 (20:43 -0400)]
config: correct the Register documentation

The Register doc block still described the two-argument form the type no
longer has.  It showed a registration without a previous version, said
nothing about the inheritance edge being recorded, and claimed a
duplicate registration is silently ignored -- which stopped being true
when that case was made to abort before main().

Documentation that describes an older signature is worse than none: it
reads as current, and the thing it promises about duplicates is the
opposite of what the code now does.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: write down version 2's delta discipline
Zygo Blaxell [Mon, 31 Aug 2026 00:42:45 +0000 (20:42 -0400)]
config: write down version 2's delta discipline

Version 2 states only what it changes from version 1; everything else
resolves along the inheritance chain.  Nothing in the file said so, which
left the next person adding an option no way to tell whether to edit the
value in version 1 or state a new one here -- and one of those silently
changes what an already-deployed installation resolves to the next time
it upgrades, which is the one thing versioning the schema exists to
prevent.

Write the rule down where the mistake would be made: what belongs here,
what does not, and the case that is easy to get wrong.  A key whose value
matches version 1 but whose comment does not still belongs here, because
the comment is part of what a schema states and is what --show-config
hands the operator.

Version 2 currently states one key, its own version number, which is what
a delta over a schema it does not yet differ from looks like.  The
trailing comment at the registration shrinks to a pointer, since the file
comment now says all of it in one place.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: add --show-builtin-config and --show-config
Zygo Blaxell [Mon, 31 Aug 2026 00:42:14 +0000 (20:42 -0400)]
config: add --show-builtin-config and --show-config

There was no way to ask a bees build what configuration it would actually
use.  The built-in schema is only readable by reading the source of the
version files, and the merged view -- builtin under global under local
under argv, with ${VAR} expanded and one schema chained onto another --
exists only inside a running daemon.  An operator debugging a config
problem had to infer the answer from behaviour.

Add two options that print it.  --show-builtin-config VERSION resolves a
schema version and writes what it resolves to; --show-config ROOT_PATH
loads configuration for a real filesystem and writes the merged result.
Both write to stdout and exit without starting deduplication.

The builtin form reads nothing at all: no filesystem, no config file, no
environment.  That is what makes it usable offline, and it is why
--config and --option are now recorded during option parsing and applied
afterwards rather than acted on as getopt_long reaches them.  Option
order belongs to the caller, so applied inline, --config f.conf
--show-builtin-config 2 would have read f.conf before the early exit ran,
and the command would be lying about what it loaded.

The output is INI, and carries the highest-priority non-blank comment for
each key along with the value, so what it prints is also documentation
for what it prints.  A builtin version is dumped through the same builder
as the merged view, because with inheritance in play the text a version
registered is no longer the same thing as what that version resolves to.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoreporter: add stateful delta-counts and delta-rates tokens
Zygo Blaxell [Sun, 30 Aug 2026 07:00:13 +0000 (03:00 -0400)]
reporter: add stateful delta-counts and delta-rates tokens

The totals and rates tokens report since startup, which flattens out: an
hour into a run, a burst of activity moves the cumulative numbers so
little that the report stops answering "what is bees doing now".

Add delta-counts and delta-rates, which report the change in the event
counters since that token last rendered.  Each report builds its own
token objects, so two reports at different intervals each see the delta
over their own interval rather than fighting over one shared snapshot.
delta-rates divides by the measured elapsed time rather than the
configured interval, so a report that ran late reports the rate it
actually observed.

Assisted-by: Claude-Code:claude-opus-4-8
Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoreporter: model content tokens as BeesReportToken objects
Zygo Blaxell [Wed, 17 Jun 2026 04:50:42 +0000 (00:50 -0400)]
reporter: model content tokens as BeesReportToken objects

write_report rendered tokens via a string switch evaluated on every write.
That has no place for a token to keep state, which the upcoming delta-count
and delta-rate tokens need, and re-parses the token names on every cycle.

Introduce a BeesReportToken hierarchy.  FunctionToken wraps a closure for the
stateless majority (totals, rates, threads, progress, workers, queue, idle,
tasks, hashtable); PlaceholderToken renders the not-implemented line for an
unknown name, preserving graceful degradation of a newer config on an older
binary.  make_token is the name->object factory; add_report builds each
report's token vector once, fresh per report, so a future stateful token
keeps state independent of other reports rendering the same token.
write_report just calls render() down the vector.

No output change: the token bodies are the former switch arms verbatim.

Assisted-by: Claude-Code:claude-opus-4-8
Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: expose occupancy histogram as a reporter token
Zygo Blaxell [Sun, 30 Aug 2026 06:57:49 +0000 (02:57 -0400)]
hash: expose occupancy histogram as a reporter token

Extract the page-occupancy histogram rendering out of prefetch_loop into
BeesHashTable::print_occupancy(), which sums the per-extent fragments and
draws the threshold-doubling graph.  prefetch_loop now calls it where it
used to build the histogram inline, with identical output.

Add a "hashtable" reporter content token that renders the same histogram, so
the occupancy graph can be produced by the reporter rather than only by the
prefetch thread's stats file.  The token reads the hash table through the
context and is skipped when none exists.  Document the token in the config
schema and config-file.md (which also gains the previously undocumented
"idle" token).

Assisted-by: Claude-Code:claude-opus-4-8
Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoreporter: add ${HOME} report filename prefix for $BEESHOME
Zygo Blaxell [Sun, 30 Aug 2026 06:31:09 +0000 (02:31 -0400)]
reporter: add ${HOME} report filename prefix for $BEESHOME

A report filename resolves against path.reports, or against the mount
namespace root when it begins with '/'.  Neither reaches $BEESHOME, so
the one file bees has always written there -- beesstats.txt -- cannot be
expressed as a report at all.

Add a ${HOME} prefix that binds the report to the open path.home
directory fd.  It is deliberately not a substitution variable: expanding
it to a path would re-walk a directory that may have moved since startup
and lose the open-fd guarantee, while binding the fd bees already holds
matches what the legacy beesstats.txt write did exactly.  The prefix is
stripped before subst(), so ${UUID} and friends still expand in the
remainder.

A ${HOME} report is disabled with a log line rather than failed when
path.home is unavailable -- state.persistent = no leaves no home
directory to write into, and that is a configuration bees supports.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: remove untrusted local-config support
Zygo Blaxell [Sun, 30 Aug 2026 05:51:50 +0000 (01:51 -0400)]
config: remove untrusted local-config support

"config: disable untrusted configuration files" made a relative
config.local-config-filename a hard configuration error, so a local
config file loaded from a non-absolute path can no longer exist.  What
was left behind is the machinery that used to police such a file: two
merged views, a get_trusted() that reads one of them, and the comments
and documentation describing which sections an untrusted file could
not reach.

The residue is not inert.  m_local_trusted is initialised false and
never assigned, so m_trusted never gains the local config as a
fallback, and every get_trusted() key -- path.home, path.reports,
state.persistent, state.create, and all of [report.*] -- silently
ignores the operator's per-filesystem config file.  A setting the
operator can see in --show-config is not the setting bees uses.

Remove the distinction:

  - bees-config.h/.cc: m_trusted, m_untrusted and m_local_trusted
    collapse into one m_innie chaining argv -> local -> global ->
    builtin, and get_trusted() goes away.
  - bees-context.cc, bees.cc: the eleven get_trusted() call sites
    become get(), so the local config reaches those keys.
  - bees-usage.cc: --write-trusted-config and --write-untrusted-config
    described the two views.  The implementation was removed,
    so passing one is an unrecognised-option error.
  - bees-config-v1.cc: local-config-filename's comment, the [path] and
    [report.*] section headers, and tempfile.dir each described the
    restrictions on an untrusted file.
  - docs/config-file.md, docs/config-format.md: the relative/absolute
    trust split, and the security notes built around it, replaced by
    why the path has to be absolute.  Every key a local file can set
    is a control surface, not just the ones naming a path, so
    restricting sections was never the real defence -- requiring an
    absolute path is.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: boot defaults from CURRENT rather than STABLE
Zygo Blaxell [Sat, 29 Aug 2026 18:39:47 +0000 (14:39 -0400)]
config: boot defaults from CURRENT rather than STABLE

Which version a build uses when nothing has selected one was STABLE, the
most recently released schema.  That is the wrong answer for it.  A build
defaults to the schema it was written around, and between releases that
is the one under development, not the one the last release shipped.
Booting from STABLE makes every default a development branch changes
inert unless a config file opts in, which is backwards: the departures
are the point of a development branch.

Boot from CURRENT instead.  This needs no notion of whether the build is
a tagged release: at a release the two constants name the same schema, so
a release build boots the released defaults by the same rule, and they
part company again only as development resumes.

Nothing changes today, because the two schemas are still identical.  It
matters from the first key version 2 adds, and selecting version 1 keeps
working because a version resolves through its chain.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: say version 1 is being frozen, not that it is frozen
Zygo Blaxell [Sat, 29 Aug 2026 18:39:47 +0000 (14:39 -0400)]
config: say version 1 is being frozen, not that it is frozen

The banner on version 1 claimed two things that are not yet true.  It
said FROZEN, when the release that would freeze it has not happened: the
schema is being frozen, and settling what it says -- wording that
describes a feature since removed, a default that turns out not to match
the release it stands for -- is what freezing consists of.  Declaring it
finished discourages exactly the corrections this stage is for.

It also called version 1 the schema v0.11 shipped.  v0.11 had no
configuration file at all; the INI schema has never been released.
Version 1 is a statement about how v0.11 behaved, expressed as defaults,
so that an installation upgrading from it keeps the behaviour it had.
That is a claim about behaviour, and it can be got wrong and corrected,
which the old wording left no room for.

Say both plainly, and say what changes at the release: after it, an
installation's defaults resolve through this file, and editing a value
changes what it gets on its next upgrade.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: resolve defaults through the schema version chain
Zygo Blaxell [Sat, 29 Aug 2026 18:38:41 +0000 (14:38 -0400)]
config: resolve defaults through the schema version chain

A version resolves to exactly the keys its own file defines, so selecting
an older one is a way to fail at startup rather than a way to pin
behaviour.  The two schemas here are still identical, so nothing breaks
yet; the moment version 2 gains a key version 1 lacks, selecting version
1 would throw NotFoundException on whichever key was looked up first,
which says nothing about the real problem.

Resolve a version against a chain instead: the version itself, then its
ancestors nearest-first, then its descendants nearest-first.  The two
directions answer different questions over disjoint sets of versions, so
one order serves both.

Ancestors are what let a schema state only the keys it changes, rather
than restating every key it inherited.  Descendants are what let a
selected version keep working as the code grows past it: a key added
afterwards resolves to the value it was introduced with.  Ancestors are
consulted first so a later schema cannot reach back and change a value
the selected version already inherited.

Three ways of writing the edges wrongly are caught where they are
resolved rather than left to surface as a missing key or a hang: an edge
naming an unregistered version, an edge naming a tracking alias, and two
schemas inheriting from the same one.  A cycle is caught by the walk.

The alias entries in s_defaults go away with this.  Every consumer
resolves names through version_aliases() now, and the entries were copies
sharing a rep with their target, which set_default() would have rejected
as a fallback loop had one ever reached a chain.  Dropping them also ends
a latent failure where constructing a second BeesConfig threw on
re-inserting an alias that was already there.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: declare each schema's inheritance edge at registration
Zygo Blaxell [Sat, 29 Aug 2026 18:37:33 +0000 (14:37 -0400)]
config: declare each schema's inheritance edge at registration

Which schema a version builds on is real structure, but nothing recorded
it: the only thing relating version 2 to version 1 was that 2 sorts after
1, which is a fact about how the versions are named rather than about how
they relate.  Deriving an order from names also quietly requires every
name to be a number, and to sort correctly, neither of which the config
file's version syntax promises.

Have Register take the version it inherits from, alongside the text.
Adding a schema stays a one-file change, and it is a change that cannot
forget to say where the schema came from.

The edge is stored exactly as written and resolved later.  A Register
runs before main(), and initialization order across translation units is
unspecified, so the version an edge names may not have registered yet.

Two build errors that used to be invisible now abort instead: a version
registered twice, silently dropped by map::insert, and a version
registered under a name that is already an alias, which left that name
meaning two different things depending on the reader.

Nothing reads the edges yet; this only records them.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: separate frozen version aliases from tracking ones
Zygo Blaxell [Sat, 29 Aug 2026 18:36:56 +0000 (14:36 -0400)]
config: separate frozen version aliases from tracking ones

The alias table maps every name to a version string, which makes two
quite different kinds of name look identical at the point of use.
STABLE and CURRENT resolve through build constants, so what they name
changes when a constant is bumped; v0.11 names one fixed schema and will
go on naming it however far development moves ahead.

That difference does not matter while a name is only ever a choice a
person makes in a config file.  It starts to matter as soon as a name can
be stored in structure that outlives the build that read it -- a schema's
inheritance edge, for one, where an edge written as CURRENT would
silently re-parent itself when the constant moved, and become a self-edge
once CURRENT reached that schema.

Record the distinction in the table rather than leaving it to be
rediscovered.  No behaviour changes.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig v2: put the section comments back
Zygo Blaxell [Mon, 31 Aug 2026 00:06:14 +0000 (20:06 -0400)]
config v2: put the section comments back

Comments in front of a section header are part of the section header.

Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: fork schema version 2, begin freezing version 1
Zygo Blaxell [Sat, 29 Aug 2026 02:21:29 +0000 (22:21 -0400)]
config: fork schema version 2, begin freezing version 1

Config schema version 1 is the set of defaults that reproduce how bees
v0.11 behaved.  That release shipped no configuration file, so version 1
is a statement about its behaviour rather than anything it published, and
installations upgrading from it resolve their defaults through version 1.
Editing it is therefore not a local change once a release has gone out:
every default touched there silently changes what an already-deployed
installation gets on its next upgrade, which is precisely what versioning
the schema exists to prevent.  Version 1 has nevertheless been the only
schema, so it has also been where new development lands.

Split the two roles.  bees-config-v2.cc is forked from version 1 and
becomes the schema under development; version 1 keeps the values it has
and gains a banner saying so.

CURRENT now resolves to 2, so it names the development schema as
documented.  STABLE stays at 1: version 1 remains fully compatible for as
long as version 2 defines no key that version 1 lacks, and it is the
schema that stands for the most recent release.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: resolve version aliases through one table, add v0.11
Zygo Blaxell [Sat, 29 Aug 2026 02:18:33 +0000 (22:18 -0400)]
config: resolve version aliases through one table, add v0.11

The names accepted by config.version were spelled out inline where the
defaults map is built, which works only as long as there is exactly one
place that has to know what a name means.  Collect them into
version_aliases() instead, and drive the alias entries in s_defaults from
it, so a name resolves the same way everywhere by construction.

Two kinds of name now live in that table.  STABLE and CURRENT track this
build and resolve through s_stable_version and s_current_version, so they
name a different schema as those constants move.  A release alias names a
frozen schema directly and goes on naming it however far development
moves ahead.

Add v0.11 as the first release alias.  That release shipped no
configuration file at all, so version 1 is not a schema v0.11 published:
it is the set of defaults that reproduce how v0.11 behaved.  The alias
selects version 1 and will keep selecting it after CURRENT has advanced
past it, which is what lets an installation pin the defaults of a release
it has already been running rather than a version number it has to look
up.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agousage: convert .txt+generator to a plain .cc raw-string literal
Zygo Blaxell [Sun, 26 Apr 2026 20:28:42 +0000 (16:28 -0400)]
usage: convert .txt+generator to a plain .cc raw-string literal

The previous approach generated bees-usage.c from bees-usage.txt via a
make rule using sed.  That added a generated C file to the build, which
did not survive 'git clean' without first re-running make.  It also
made the usage text invisible to grep and git log -p without escaping.

Replace bees-usage.txt + the make generator rule with a plain .cc file
containing a single raw-string literal assigned to BEES_USAGE.  The
file follows the same pattern as bees-config-v1.cc and compiles via the
existing %.cc pattern rule in src/Makefile without special treatment.

No behaviour change: the string stored in BEES_USAGE is identical to
the previous generated output.  The --help output is byte-identical.

Assisted-by: Claude-Code:claude-sonnet-4-6
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodocs: replace the known-broken flag table with tested-toolchain facts
Zygo Blaxell [Mon, 24 Aug 2026 20:43:40 +0000 (16:43 -0400)]
docs: replace the known-broken flag table with tested-toolchain facts

The table steered packagers away from -flto because BEESTRACE built its
std::function from a lambda that captured nothing whenever the trace
message was a plain string literal.  GCC read the resulting empty
_Any_data union as uninitialized, and -Werror turned the false positive
into a build failure on GCC 12 and 14.  BEESTRACE now init-captures
__FUNCTION__, so the closure is never empty and the warning no longer
fires; both -flto rows describe a problem that no longer exists.

The -D_GLIBCXX_ASSERTIONS row was never traced to a specific bug, only
to "possibly in libstdc++", and no reproducer survives.  Drop it along
with the rest rather than leave a claim in the install instructions that
nobody can check.

Replace it with what is actually true now.  `make build-check' builds
bees and runs its unit tests with GCC and with clang, each with -flto,
so record clang alongside GCC as a tested compiler, say that -flto is
tested, and name the check.

Keep the note that bees builds with -Wall -Wextra -Werror -O3 and no
other flags, and say why it matters: -Werror is what turns a new warning
into a failed build, which is the part packagers need to know.

Document the one way an LTO build reliably goes wrong: overriding CXX
without CC.  LTO leaves compiler-specific intermediate code in the
object files and the linker can only read the form matching the plugin
it loaded, so a mixed pair fails with "plugin needed to handle lto
object" and undefined references.  bees compiles C as well as C++, which
is enough for a half-overridden toolchain to break the link -- and the
error names neither the compilers nor the flag that caused it.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agobuild: rebuild bees and its tests when localconf changes
Zygo Blaxell [Mon, 24 Aug 2026 20:42:54 +0000 (16:42 -0400)]
build: rebuild bees and its tests when localconf changes

Same fix as the lib commit "crucible: rebuild when localconf changes",
applied to src/Makefile and test/Makefile: ../localconf overrides CC,
CXX and CCFLAGS but was not a prerequisite of anything built with them,
so editing it recompiled nothing and left the tree able to link objects
from two compilers.

Both files gain BUILD_CONF and use it wherever ../makeflags appeared in a
prerequisite list, including the link rules in test/Makefile, and the
.dep rules that previously depended on neither file.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agocrucible: rebuild when localconf changes
Zygo Blaxell [Mon, 24 Aug 2026 19:20:33 +0000 (15:20 -0400)]
crucible: rebuild when localconf changes

The object and dependency rules named ../makeflags as a prerequisite but
not ../localconf, even though localconf is -include'd right after it and
overrides the same variables -- CC, CXX and CCFLAGS.  Editing localconf
therefore recompiled nothing.

Objects record nothing about the compiler that produced them, so a
toolchain switch made in localconf leaves the tree holding a mix of two
compilers' output.  Under -flto that surfaces at link time as "plugin
needed to handle lto object", which names neither localconf nor the
compilers, and is a poor clue to what actually happened.

Add localconf to the prerequisites via BUILD_CONF.  It is optional and
has no rule to create it, so $(wildcard) names it only when it exists; an
unconditional prerequisite would make its absence an error on a clean
checkout, which is presumably why it was left out to begin with.

Include the .dep rules, which previously depended on neither file.
Generated dependencies name the compiler's own header paths, and they are
pulled in with `include' rather than `-include', so a dep left pointing
at a header the new toolchain does not ship does not merely miss a
rebuild: it stops the build with "No rule to make target".

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoscripts: add build-check for toolchains the default build skips
Zygo Blaxell [Mon, 24 Aug 2026 19:20:07 +0000 (15:20 -0400)]
scripts: add build-check for toolchains the default build skips

The default build is whatever makeflags and a developer's localconf say,
which is one compiler and no -flto.  Distributions build with LTO, and
bees has been broken by it before: BEESTRACE used to construct its
std::function from a lambda that captured nothing, which GCC 12 and 14
read as an uninitialized _Any_data under -flto, and -Werror turned the
false positive into a build failure.  Nothing catches a regression there
unless something builds it on purpose.

Add scripts/build-check, which builds and runs the unit tests for a list
of toolchain and flag combinations, and a `make build-check' target to
invoke it.  The default list is clang and gcc, both with -flto.  Both are
worth covering because they fail in different places: GCC's breakage was
a compile-time diagnostic, while a half-overridden toolchain fails at
link time with "plugin needed to handle lto object" -- easy to hit by
accident, since a localconf that sets only CXX leaves CC as the system cc.

Each combination is built in its own scratch tree under .build-check,
populated from git ls-files so only sources are copied.  Object files
record nothing about the compiler that produced them, so building two
toolchains in one tree would silently mix them; a separate tree also
leaves the working tree's incremental build alone.  BEES_VERSION is
passed in explicitly because the scratch tree has no .git of its own but
sits inside one, so scripts/bees-version would otherwise describe the
enclosing repository.

A combination that passes has its tree deleted, since it is tens of
megabytes of objects nobody will read again.  A failing one is kept, so
the failure can be reproduced by hand where it happened.  Logs are kept
either way.

Verified that both default combinations pass, that a deliberately
mismatched cc/clang++ combination fails and is reported by name with a
non-zero exit, and that successful trees are cleaned up.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoroots: checkpoint on content change, not a dirty counter
Zygo Blaxell [Mon, 24 Aug 2026 17:18:33 +0000 (13:18 -0400)]
roots: checkpoint on content change, not a dirty counter

snapshot_point() gated the checkpoint write on a generation counter pair,
m_crawl_dirty/m_crawl_clean, bumped only by BeesCrawl::set_state() (via
crawl_state_set_dirty()), crawl_state_erase(), insert_root(), and
insert_extent_crawler().

In extent scan mode the crawl position never passes through set_state().
find_next_extent() and scan_one_ref() advance the cursor exclusively with
hold_state(), and the value snapshot_point() serialises is
get_state_begin() -- the ProgressTracker low-water mark, which advances as
holders retire.  Holder retirement is deliberately decoupled from
BeesRoots::m_mutex, so it cannot bump a counter guarded by that mutex.
The counter therefore tracked a different quantity than the one being
written, and snapshot_point() logged "Nothing to save" and returned even
though the position had moved.

The only remaining dirty events in extent scan mode were tier insertion at
startup and restart_crawl() at the end of a pass.  beespoint.ini was thus
rewritten roughly once per scan pass, and every restart resumed from the
last pass boundary, discarding all progress since.

The end-of-pass trigger made sense when a scan task began and ended within
a short interval.  It no longer holds: resolving lock contention can keep
a task open for days.

Replace the counter pair with m_point_saved, the serialised INI of the
last checkpoint written (immediate mode) or enqueued (deferred mode).
snapshot_point() now builds ini_string first and returns early only when
it is byte-identical.  Comparing the bytes that would be written against
the bytes that were cannot drift out of sync the way a side counter can,
and it is self-correcting: a new progress path changes the serialised
state without having to remember to signal anything.  At one serialisation
per checkpoint interval the cost is immaterial.

m_point_saved is updated after a successful write in immediate mode, so a
throw leaves it stale and the next tick retries.  In deferred mode it is
updated at enqueue, because the pending queue already owns the write
obligation and retries on failure; re-enqueueing an identical copy would
only create an entry for the coalescer to discard.

Under state.point.defer this restores continuous occupancy of the pending
queue, which was previously fed only at pass boundaries.  In the steady
state one entry is queued and one written per checkpoint interval, with a
depth of roughly (hash table sweep time / checkpoint interval).  Each
entry carries its own writeback_count, so an older entry becomes safe to
write sooner, and flush_pending_checkpoints() always writes the most
advanced position that is currently safe.

The writeback thread's idle status note now reports that queue depth
instead of the removed dirty/clean flag, so the backlog is visible in
BEESSTATUS.  It is read under m_mutex before m_stop_mutex is acquired,
introducing no new lock nesting.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: merge in one pass when new buckets divide old
Zygo Blaxell [Tue, 25 Aug 2026 02:26:08 +0000 (22:26 -0400)]
hash: merge in one pass when new buckets divide old

Commit "hash: resize in one pass when no buckets merge" made the
divisible grow a single sequential pass, and left the shrink on the
c_cells_per_bucket-pass loop, saying a single-pass merge "needs somewhere
to keep each cell's LRU rank".  That is not so.  A cell's rank is its
position in its bucket, which costs no storage at all, and recording one
rank per cell would need ~1 GiB of side table for a 16 GiB hash table --
prohibitive, and unnecessary.

The rank is only unrecoverable in a source-major traversal.  Walking old
buckets in file order and pushing each into its destination interleaves
two old buckets into one new one, after which a destination cell's
position no longer says which rank it arrived with, so a third old
bucket cannot be merged correctly.  That is a property of the traversal
order, not of the data.

Visit in destination order instead.  Gather the merge_width old buckets
that feed one new bucket and merge them by array index: each source is
still in pure rank order, so position is the merge key and nothing has
to be stored per cell.

The gather is whole extents rather than scattered buckets.  New bucket n
is fed by old buckets n + j * new_buckets, and new_buckets is a whole
number of extents because new_size is, so new extent e is fed by old
extents e + j * new_extents -- merge_width contiguous extents, with
every old extent read by exactly one new extent.  The same reasoning
puts old bucket n + j * new_buckets at the same offset within its extent
as new bucket n, so one index reaches all merge_width of them.

Reads drop from c_cells_per_bucket * old_extents to old_extents.  Shrink
was the worse case for the old loop, because the table it read 256 times
was the larger one.

The push order is the same subsequence the cell-pass loop produces for
each new bucket -- LRU-oldest rank first, and within a rank, descending
old extent index -- so the output is bit-identical, whatever
push_front_in_range() does with duplicates and evictions.  Cells are
still addressed by hash rather than by the gathered index, so a cell
that is not in the bucket its hash names still lands in the right place.

The gather buffer is merge_width extents, so it is capped at 1024 (128
MiB, a 1024:1 shrink); a ratio past that keeps the cell-pass loop, as do
non-divisible resizes in either direction.

Verified against a pre-change binary on a 16M table seeded by real
dedupe traffic, comparing beeshash.dat byte for byte, with the
pre-change binary run twice per case to prove the comparison is
measuring the resize:

  16M -> 8M   2-way merge, new path       identical, 0.388s -> 0.015s
  16M -> 4M   4-way merge, new path       identical, 0.485s -> 0.015s
  16M -> 12M  non-divisible, fallback     identical, 0.400s -> 0.387s
  16M -> 32M  divisible grow, unchanged   identical, 0.006s -> 0.006s

The two unchanged timings confirm the new branch does not capture cases
it should not.  Timings are with the table in page cache, so they show
only the CPU cost of the extra passes; the read-count reduction is what
matters once the old table no longer fits.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodocs, bees.h: stop describing the deleted hash_prefetch thread
Zygo Blaxell [Sun, 23 Aug 2026 18:58:49 +0000 (14:58 -0400)]
docs, bees.h: stop describing the deleted hash_prefetch thread

Commit "hash: delete the prefetch thread; beesstats becomes a report"
deleted the prefetch thread and turned beesstats.txt into a report, but
three places still describe it as running: the BeesHashTable constructor
and start_threads() doc comments, which promise to start "writeback and
prefetch" threads when start_threads() now starts only the writeback
thread, and docs/wrong.md, which lists hash_prefetch in its example
thread dump and in the table of thread names of note.

An operator reading wrong.md to interpret a THREADS report would look
for a thread that cannot appear.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: drop the stale lazy-fetch note from push_front_in_range
Zygo Blaxell [Sun, 23 Aug 2026 18:53:52 +0000 (14:53 -0400)]
hash: drop the stale lazy-fetch note from push_front_in_range

The comment justified calling push_front_in_range() directly by saying
it avoids "the live mmap's lazy-fetch path (which would read from the
*old* m_fd into the *new* mapping and corrupt it)".  There is no such
path any more.  prepare() loads the whole table before any worker can
look one up, so nothing in BeesHashTable reads from the file on access;
grep finds no fetch of any kind in bees-hash.cc.

State what the function actually skips.  push_front_hash_addr() wraps
two things around the bucket mutation, and resize_into_mapping() wants
neither: the per-extent lock, which is pointless single-threaded at
startup, and set_extent_dirty_locked(), which would mark every extent
of a table it is about to write out itself and leave the writeback
thread to rewrite all of it.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: resize into the real mapping instead of a heap buffer
Zygo Blaxell [Sun, 23 Aug 2026 18:15:02 +0000 (14:15 -0400)]
hash: resize into the real mapping instead of a heap buffer

resize_file() built the new table in a vector<uint8_t> and reinvented
the union aliasing over it, reinterpret_casting the buffer to Bucket and
Extent the way m_bucket_ptr and m_extent_ptr already alias the mmap.
That buffer was ordinary heap: no MADV_HUGEPAGE, no MADV_DONTFORK, no
MADV_DONTDUMP, and no mlock, because prepare() did not map or lock
anything until after the resize had finished.

So the most memory-intensive phase of startup ran in the one region that
was not protected.  Redistributing cells scatters writes across the
whole new table while the old file streams through the page cache, and
with multiple gigabytes of unlocked anonymous memory competing with that
stream, the host swaps.

Map first, then fill.  prepare() now decides whether this startup is a
resize, sets m_size to the requested size, calls mmap_and_size_metadata()
and the new mlock_mapping() helper, and only then hands off to
resize_into_mapping(), which writes through m_bucket_ptr and reads back
through m_extent_ptr.  The redistribution runs in memory that is locked,
huge-page advised, and excluded from fork and core dumps, and there is no
second copy of the table anywhere.

resize_file(new_size) becomes resize_into_mapping(old_size): the new size
is already m_size by the time it runs, so the only thing it needs told is
where to read from.  It no longer sets m_size, and checks the reopened
file against it instead.

Fold the per-extent histogram seeding into the write-out loop, which
touches each extent anyway, so the resize path does not need a second
sequential walk of the mapping.  Retitle the mmap log line, which
reported the mapping size under "opened hash table filename" while the
file on disk was still the old size.

Verified against the pre-change binary by resizing one populated table
and comparing beeshash.dat: identical for 2x, 3x and 1.5x grows and for
2x and 1.5x shrinks, covering both the one-pass and merging paths and
the resize-down case where the mapping is smaller than the file read.
Startup log order is now mapping, mlock, resize, write, where it was
resize, write, mapping, mlock.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: resize in one pass when no buckets merge
Zygo Blaxell [Sun, 23 Aug 2026 17:14:47 +0000 (13:14 -0400)]
hash: resize in one pass when no buckets merge

Resizing walked the old table c_cells_per_bucket (256) times, once per
cell position, so that cells from old buckets merging into one new
bucket interleave by LRU rank instead of one bucket evicting another.
That cost is only necessary when merging actually happens.

A cell is placed at hash % new_buckets and lived at hash % old_buckets.
If old_buckets divides new_buckets, hash % new_buckets == n implies
hash % old_buckets == n % old_buckets, so every cell in new bucket n
comes from exactly one old bucket and no merging occurs.  That covers
every integer-factor grow, including the doubling an operator gets from
asking for twice as much hash table.

With nothing to interleave, one sequential pass over the old table
produces bit-identical output.  Detect the divisible case and take it.

The difference is not academic.  A real 8G to 16G resize logged:

  Resizing hash table: 19423/16777216 (0%), 210.11 sec elapsed,
      181278 sec remaining

256 passes over 8G is 2 TiB of reads.  Once the old table no longer fits
in the page cache every pass after the first comes from disk, which measured
~12 MB/s and put the finish 50 hours out, with the estimate still climbing as
the 16G destination evicted what remained of the source.  One pass reads 8 GiB.

Verified end to end by resizing one populated 128M table with the
pre-change and post-change binaries and comparing beeshash.dat:
identical for a 2x grow and a 3x grow (fast path taken), and identical
for a 1.5x grow, where 49152 % 32768 != 0 keeps the merging path and
confirms it is unchanged.

Shrinks and non-divisible grows still make 256 passes.  Shrink is the
worse case, since the table being read 256 times is the larger one; it
needs a rank-aware single-pass merge, which needs somewhere to keep each
cell's LRU rank, and is left for later.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: log startup progress instead of publishing thread notes
Zygo Blaxell [Sun, 23 Aug 2026 07:27:23 +0000 (03:27 -0400)]
hash: log startup progress instead of publishing thread notes

Every BEESNOTE between BeesHashTable construction and the end of
prepare() is write-only.  bees_main() calls start_hash_writeback(),
which runs start_threads() -> prepare() and therefore the whole table
load and any resize, at bees.cc:587.  BeesContext::start(), at
bees.cc:600, is what creates the threads that read thread status:
show_progress() at bees-context.cc:1301 and the reporter at 1305.
Those are the only two readers of BeesNote::get_status(), so until
start() runs a note updates a map nobody reads.  Notes are not part of
the exception trace either; that is BEESTRACE.

Getting reports running earlier is not a cheap fix.  They would have to
be hardened against a hash table that is not yet loaded, which is the
whole reason the notes exist in this path.  A log message costs nothing
and is visible immediately, because the log queue replays once config is
applied.

Drop the notes that duplicate an adjacent log line: creating and
truncating a new table, mlock, allocating the resize buffer, and the
resize fsync.  Drop the per-iteration notes for loading an extent, the
resize cell-pass, and the resize write; BeesProgressLogger already
reports all three at BEES_HASH_PROGRESS_INTERVAL, and one log line per
iteration would be millions of lines on a multi-gigabyte table.

Convert the one note with no log counterpart, the hash table open, to
BEESLOGDEBUG.  It is the last thing to happen before the "does not exist
and state.create = no" throw, so it is worth having on a channel that
something reads.

Keep the notes in the writeback loop, print_occupancy, and the stop
paths.  Those run when the reporter is alive; BeesContext::stop() tears
the reporter down after the hash table, not before.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: report progress while loading and resizing the table
Zygo Blaxell [Sat, 22 Aug 2026 23:04:31 +0000 (19:04 -0400)]
hash: report progress while loading and resizing the table

Loading or resizing a multi-gigabyte hash table happens in the main
thread at startup, before the status file exists and before any worker
runs.  On an 8G-to-16G resize that is over half an hour during which the
log shows a single line at the start and nothing else, so an operator
has no way to distinguish slow progress from a hang.

Add BeesProgressLogger, a rate-limited reporter that emits one debug
line every BEES_HASH_PROGRESS_INTERVAL (15) seconds with the completed unit
count, the percentage, elapsed time, and a linear estimate of the time
remaining, plus one summary line when the operation ends.  The interval
timer starts at construction, so short operations stay silent.

Report progress from the three loops that dominate startup:

  - the per-extent load in prepare()
  - the cell-pass scan of the old table in resize_file(), whose unit
    count is cells-per-bucket times old extents, all units equal cost
  - the write of the new table in resize_file()

Also time the zero-filled allocation of the new table and the fsync of
the temp file, both of which are single blocking calls with no interior
progress to report.

Write the new table one Extent at a time, matching the unit prepare()
reads it in, and view the staging buffer through an Extent alias the way
the mmap'd table is viewed through m_extent_ptr.  Writing it in one call
is not an option any more: pwrite_or_die() rejects a request above
max_transfer_size(), which any table worth resizing exceeds.  Extents
are also what gives the write something to report, one update per Extent
rather than one for the whole table.  open_file() already requires the
table size to be an exact multiple of one Extent, so the loop needs no
partial tail case; assert that invariant where the buffer is allocated.

Durability is unchanged: it comes from the fsync and rename, not from
the size of any one write.  Record why that fsync, unlike the writeback
and close ones, is not gated by a config knob.

The constant is named for the hash table rather than progress in
general: an unrelated BEES_PROGRESS_INTERVAL used to pace the hourly
show_progress dump before that moved into [report.*], and branches
that still carry the old one must not collide with this.

Assisted-by: Claude-Code:claude-opus-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: remove dead verify_cell_range and debug scaffolding
Zygo Blaxell [Wed, 17 Jun 2026 01:51:02 +0000 (21:51 -0400)]
hash: remove dead verify_cell_range and debug scaffolding

verify_cell_range and dump_bucket_locked guarded against hash table
corruption from bees bugs fixed long ago.  The periodic survey was the last
live caller of verify_cell_range; it dropped that call when it switched to
summing per-extent occupancy fragments, leaving the function referenced only
from #if 0 blocks.

Delete verify_cell_range, dump_bucket_locked, and the VERIFY_CLEARS_BUGS
flag, along with the three disabled call sites in erase_hash_addr,
push_front_hash_addr and push_random_hash_addr.  The push_random case_cond
variable existed solely to label cases in that disabled diagnostic, so it
goes too; the goto targets that drove the control flow remain.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: fix beesstats.txt write guard for inert home_fd
Zygo Blaxell [Mon, 27 Apr 2026 20:08:51 +0000 (16:08 -0400)]
hash: fix beesstats.txt write guard for inert home_fd

The hash-prefetch loop in BeesHashTable::prefetch_loop() guards the
on-disk stats-file write with `if (m_ctx->home_fd())`, intending to
skip the write when paths.home is unavailable (state.persistent=no
with the directory missing).  The guard never worked: crucible's Fd
exposes `operator int() const` (returns -1 when empty) and
`bool operator!() const` but no `operator bool()`, so `if (fd)` falls
through to the int conversion and `if (-1)` is unconditionally truthy.

Use `!!m_ctx->home_fd()` to force the operator! path, matching the
existing project idiom.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: let's not have multiple temporary file extensions
Zygo Blaxell [Sat, 22 Aug 2026 19:12:40 +0000 (15:12 -0400)]
hash: let's not have multiple temporary file extensions

'rm -f *.tmp' should always suffice.

Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: derive the occupancy survey from per-extent fragments
Zygo Blaxell [Wed, 17 Jun 2026 00:42:32 +0000 (20:42 -0400)]
hash: derive the occupancy survey from per-extent fragments

The prefetch-thread survey walked every cell of the table each interval to
build the page-occupancy histogram, counting both occupancy and a per-cell
type breakdown (compressed / unaligned_eof / toxic).  With 256 cells per
bucket that is a full-table scan under per-extent locks every hour, and the
type breakdown reads v1 BeesAddress bits that scan-next neither sets on store
nor reads on fetch — so under scan-next those counters are structurally
meaningless.

Replace the walk with a cached per-extent occupancy fragment.  Each
ExtentMetaData gains a small bucket-fill histogram (index = occupied cells in
a bucket, value = number of buckets at that occupancy).  It is rebuilt under
the extent lock at two points that already touch the whole extent:  the
startup load, and each writeback (where the extent is copied for pwrite).
Occupancy can only change when a cell is inserted or evicted, which dirties
the extent, so a writeback-time refresh captures every change; read-mostly
extents keep their load-time fragment.  Staleness is bounded by the writeback
cycle, so the printed graph is effectively current with on-disk data.

The survey is now a sum over fragments with no cell walk and no locking
beyond a brief per-extent read.  Drop the type breakdown and the percent()
helper that only formatted it; total cell count comes from m_cells directly.
verify_cell_range loses its last live caller but is left in place (now
referenced only from #if 0 blocks); removing it is a separate cleanup.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: load the table eagerly at startup, drop demand-load
Zygo Blaxell [Tue, 16 Jun 2026 23:28:33 +0000 (19:28 -0400)]
hash: load the table eagerly at startup, drop demand-load

The hash table mapping is MAP_PRIVATE | MAP_ANONYMOUS, so "demand loading"
was a per-extent pread into anonymous pages on the first worker-thread
touch, gated by ExtentMetaData::m_missing.  Under dedupe conditions,
lookups are effectively random, which turns the table read into maximally
scattered I/O taken on worker threads under the per-extent lock, when it
could be an optimal sequential read at startup, with no further locking
overhead afterward.

Move the read into the main thread in prepare(), after the mapping is sized
and before mlock, looping over extents in index order.  This is sequential
I/O and completes before any worker can look up a hash, so the lookup and
insert paths may now assume the table is fully resident.  Read per-extent
because pread_or_die treats a short read as fatal (it loops only on EINTR);
a multi-GB single read could legitimately come up short.  A read failure
here is fatal on purpose: a table that cannot be fully loaded is not safe
to dedupe against.  Memory-only mode skips the load entirely — the pages
are already zero from MAP_ANONYMOUS.

With every extent resident after prepare(), the demand-load machinery
is dead: delete m_missing, fetch_missing_extent_by_index/_by_hash,
the six worker call sites, the demand-load call in prefetch_loop,
and the m_prefetch_running readahead hint.  The toxic-bit clear and
verify_cell_range that rode along on the per-extent fetch are gone with
it; both guarded against long-fixed kernel bugs that scan-next no longer
bothers to detect.

prefetch_loop keeps its occupancy survey for now (still correct against the
now fully-resident table); collapsing that into incremental counters is a
follow-up.  Residency now rests entirely on mlock, with memcg swappiness=0
or a table small relative to RAM as the fallback when mlock is unavailable.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: add state.hash.randomize-lru config option
Zygo Blaxell [Mon, 25 May 2026 22:45:20 +0000 (18:45 -0400)]
hash: add state.hash.randomize-lru config option

The push_random_hash_addr* methods insert new (not-yet-duplicate)
hashes at a random position in the per-bucket LRU list.  This spreads
evictions so that new hashes don't uniformly evict every old hash, but
it also makes the hash table's contents depend on a per-thread PRNG,
so two runs over identical input diverge.

Hash lifetime is better solved at hash insertion time, when the entropy
of the hashes themselves can act as a deterministic PRNG, and we get more
direct control of how many hashes survive from each extent.  That change
is not included here, but the benefit for deterministic testing is enough
to bring this change forward.

Add state.hash.randomize-lru (default yes, preserving current behavior).
When set to no, the random-insert methods force the insertion position to
0, i.e. insert at the LRU front and evict from the back.  Combined with
thread.thread-max = 1 this removes the last source of nondeterminism in
hash-table eviction, so repeated runs over the same filesystem produce
the same dedupe result -- useful for reproducible performance analysis
where randomized-eviction variance would otherwise mask the effect being
measured.

Document it in bees-config-v1.cc and docs/config-file.md.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash: resize at startup; defer mmap to prepare(); ranged_cast
Zygo Blaxell [Thu, 30 Apr 2026 03:10:50 +0000 (23:10 -0400)]
hash: resize at startup; defer mmap to prepare(); ranged_cast

state.hash.resize now fires at startup (before worker threads), so
the daemon runs with the requested hash table size immediately rather
than after the next shutdown.

init() no longer mmaps.  Deferring the mmap to prepare() — which runs
after all state.hash.* setters, including set_resize() — means there
is never a transient mapping of the OLD (possibly oversized) file.
When an operator moves bees to a smaller machine and asks for a resize,
the old on-disk file may be too large for the new host's RAM; deferring
prevents mlock from committing the old size.

prepare() is idempotent: a second call from start_threads() after
cmd_open_hash already prepared is a no-op.  Test framework calls
prepare_hash_table() explicitly so hash-insert/hash-lookup work
without going through start_threads().

resize_file() uses cell-position as the outer loop (iterating all
old extents 256 times) so that when multiple old buckets collide on
one new bucket (the common case when halving the table), cells from
all colliding buckets are interleaved by their original LRU rank
rather than one bucket's cells evicting another's wholesale.

push_front_in_range() extracted as a static lock-free helper shared
by push_front_hash_addr() and resize_file().

Four static_cast<> conversions in the resize path replaced with
ranged_cast<> (throws out_of_range on overflow/sign error).

Assisted-by: Claude-Code:claude-opus-4-6
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: log [state] keys at startup
Zygo Blaxell [Mon, 27 Apr 2026 04:15:26 +0000 (00:15 -0400)]
config: log [state] keys at startup

The [state] section parses 11 config keys at startup but logged
almost none of them.  state.persistent was only logged on the inert
fallback path (when paths.home was missing), and state.point.interval
already logged from its setter — every other state.* value was silent,
so an operator running with non-default writeback timing or fsync
discipline had no way to confirm what was actually in effect.

Push the BEESLOGINFO calls into setters where setters exist
(BeesHashTable::set_create / set_resize / set_writeback_fsync /
set_writeback_unreadahead / set_close_fsync / BeesRoots::
set_checkpoint_defer), matching the existing setter-side log on
BeesRoots::set_checkpoint_interval.  The hash table setters were
inline header bodies; move them to bees-hash.cc so the log call
doesn't bloat every translation unit that includes bees.h.

Log at the bees.cc call site for the values without setters:

  state.persistent              — unconditionally, before the
                                  in-memory-vs-file-backed branch
  state.hash.size               — pretty-rendered after the rounding
                                  to the 128 KiB extent boundary
  state.hash.writeback-time     — duration in seconds
  state.hash.writeback-rate-max — pretty-rendered raw config value
  effective writeback rate      — the computed
                                  min(size / time, rate-max) that
                                  set_flush_rate() actually receives

state.point.interval's existing setter log is preserved but
reformatted to the standard "key = value [section.key]" shape.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agobees-config-v1: trim [path] home comment to option reference
Zygo Blaxell [Tue, 9 Jun 2026 00:00:28 +0000 (20:00 -0400)]
bees-config-v1: trim [path] home comment to option reference

The path.home comment spelled out the relative-path resolution
mechanism (subvolid=5, openat2 with RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS,
Linux 5.6+ fallback to openat).  docs/config-file.md already documents
the symlink-walk and openat2 behaviour in full.

Keep the absolute-vs-relative semantics and the default inline; defer
the resolution mechanics to the doc.  path.reports is left as-is: its
comment is hard constraints, not background.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agostate: drop reference to missing snapshot feature on kernels too old to use
Zygo Blaxell [Mon, 3 Aug 2026 06:15:59 +0000 (02:15 -0400)]
state: drop reference to missing snapshot feature on kernels too old to use

The Linux kernel version cutoff is 5.4 (soon to be 5.10).  The snapshot
ioctl is far older.

Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agostate: rename state.hash.create to state.create and auto-create path.home
Zygo Blaxell [Sun, 26 Apr 2026 21:56:44 +0000 (17:56 -0400)]
state: rename state.hash.create to state.create and auto-create path.home

The boolean that gates "create state files if they don't exist" really
applies to both path.home and beeshash.dat — they are the two files
that bees writes under [state] when persistent=yes.  Promote the key
from [state.hash] up to [state] so it sits alongside state.persistent
and covers both files.

The new state.create=yes also asks BeesContext::home_fd() to create
path.home itself when the directory is missing, instead of throwing
ENOENT and forcing the operator to mkdir it by hand.  path.home is
created subvolume-first via BTRFS_IOC_SUBVOL_CREATE so it gets
independent snapshot/quota lifecycle from the surrounding filesystem;
on a non-btrfs parent or kernels that reject the ioctl,
btrfs_subvol_create_at returns false and home_fd() falls back to a
plain mkdir().  Only the final path component is created — the parent
of path.home must already exist — and the subvolume path is taken
only when path.home is a relative single-component name (the common
".beeshome" shape); absolute paths and embedded '/' go straight to
mkdir().

home_fd() now branches on (state.persistent, state.create) when the
initial open hits ENOENT:

  - persistent=no                    -> return Fd() (inert mode)
  - persistent=yes && create=no      -> throw with path.home named
  - persistent=yes && create=yes     -> subvol-or-mkdir, then retry

Other open errors (EACCES, EROFS, ENOTDIR, ...) still throw — only
ENOENT triggers the new logic.  errno is captured locally because Fd
construction can clobber it on the failure path.

The inert-Fd return path is safe because the prior commit
("bees-util: make BeesStringFile inert when dir fd is unset") makes
BeesStringFile read/write no-op when m_dir_fd is empty and m_name is
relative — exactly the shape the state files end up with when
home_fd() returns Fd().

bees-hash.cc still gates file creation on m_create (set via
BeesHashTable::set_create) for now; the setter is just fed from the
renamed config key in bees.cc.  The error message in
BeesHashTable::open_file refers to the new key name.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: move THROW_CONFIG_ERROR to bees-config.h
Zygo Blaxell [Sun, 3 May 2026 07:56:56 +0000 (03:56 -0400)]
config: move THROW_CONFIG_ERROR to bees-config.h

This provides external config readers (e.g. BeesFilter) a standard
method to report configuration parse errors.

Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodocs: update running.md to reflect native hash table creation/resize
Zygo Blaxell [Sat, 2 May 2026 02:20:11 +0000 (22:20 -0400)]
docs: update running.md to reflect native hash table creation/resize

Update manual setup instructions to clarify that bees can now
auto-create and resize its hash table natively if state.create = yes
(the default) is used.

Assisted-by: Gemini:gemini-3.5-flash
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodocs: document persistence requirement for state files
Zygo Blaxell [Sat, 2 May 2026 01:56:43 +0000 (21:56 -0400)]
docs: document persistence requirement for state files

Update documentation to clarify that beespoint.ini is only used and
beescrawl.dat is only migrated when state.persistent = yes is
configured.

Also update outdated references to beescrawl.dat in how-it-works.md
and running.md to reflect the current primary use of beespoint.ini.

Assisted-by: Gemini:gemini-3.5-flash
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agobees-config-v1: trim [thread] comments to option reference
Zygo Blaxell [Tue, 9 Jun 2026 00:00:09 +0000 (20:00 -0400)]
bees-config-v1: trim [thread] comments to option reference

The built-in [thread] block header and the thread-max comment had grown
to carry expression examples, the "cap a CPU-relative count yourself"
usage tip, and the legacy -c oversubscription tradeoff.  All of this is
already documented at length in docs/config-file.md, leaving two copies
to drift.

Trim both back to the file's own stated policy (semantics, accepted
values, defaults, direct effects) and point to the doc for the rest.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodocs: document ${NPROC}/${THREAD_FACTOR}, ceil(), and the thread expressions
Zygo Blaxell [Mon, 8 Jun 2026 22:59:43 +0000 (18:59 -0400)]
docs: document ${NPROC}/${THREAD_FACTOR}, ceil(), and the thread expressions

Rewrite the [thread] section of config-file.md for the expression model:
thread-min/thread-max/loadavg-target are size values; thread-max means
exactly what it evaluates to and is no longer silently capped by
thread-factor; thread-factor feeds the default expression via
${THREAD_FACTOR}; loadavg-target keeps fractional values.  The legacy -c N
option still sets an exact, possibly oversubscribed count (its released
behaviour), overriding the expression.

In config-format.md, document the real size-expression grammar (arithmetic
operators, parentheses, % suffix, min()/max()/ceil(), interpolated
variables) -- it previously described only suffixes and a single +/-
adjustment -- and add the missing ${RAM_BYTES}, ${FS_BYTES}, ${NPROC}, and
${THREAD_FACTOR} interpolation entries.

Update the options.md -c/-C descriptions to match: -c is an exact count that
overrides the factor, -C feeds ${THREAD_FACTOR} in the default thread-max.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: configure thread counts with ${NPROC}/${THREAD_FACTOR} expressions
Zygo Blaxell [Fri, 26 Jun 2026 06:56:01 +0000 (02:56 -0400)]
config: configure thread counts with ${NPROC}/${THREAD_FACTOR} expressions

The worker-thread knobs grew a special case in C++: thread-max was either
a bare integer or, when blank, ceil(hardware_concurrency() * thread-factor),
and thread-min/loadavg-target were parsed with stoul().  None of them went
through the config substitution or the size-expression grammar, so the
CPU-relative arithmetic was stuck in bees-context.cc instead of the config
where the defaults belong.

Move that arithmetic into the config expression:

  - Add a ${NPROC} substitution variable (logical CPU count, clamped to at
    least 1, since hardware_concurrency() may legally return 0).

  - Expose the merged thread.thread-factor value as ${THREAD_FACTOR}.  Unlike
    the other subst variables this derives from a config key rather than a
    system fact, so it is populated in set_argv() once all config layers are
    merged, not in the constructor.  The normalized numeric value is stored,
    not the raw string, because bees_parse_ratio accepts "3/2" and "15:10"
    forms that the size-expression grammar cannot parse.

  - Parse thread-min and thread-max as size expressions (subst() then
    bees_parse_size()), and drop the C++ blank/ceil special case.
    thread-factor now reaches the thread count only via the default thread-max
    expression, max(1, ceil(${NPROC} * ${THREAD_FACTOR})).

  - Add a one-argument ceil() function to the size-expression grammar so the
    default can round up like the old code did.

  - Parse loadavg-target with a new bees_parse_size_double(): a target load
    average is inherently fractional, and the released code used stod().
    bees_parse_size() would truncate "0.5" to 0, which means "throttling
    disabled" -- the worst possible misreading.  bees_parse_size() now
    delegates to bees_parse_size_double() and only adds the integer cast.

Command-line semantics are unchanged from the released code: -c N sets an
exact thread count (thread-factor ignored, oversubscription allowed), since
it simply overrides the thread-max key with the literal N.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agothread: don't supply a generic thread status
Zygo Blaxell [Fri, 19 Jun 2026 16:48:29 +0000 (12:48 -0400)]
thread: don't supply a generic thread status

This allows inactive threads to disappear from the threads report.
This may be useful for the numerous idle reporter threads, which
often report only their own activity.

Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agotrace: document BEESTRACE auto-prefix in the doxygen comment
Zygo Blaxell [Sat, 30 May 2026 17:37:04 +0000 (13:37 -0400)]
trace: document BEESTRACE auto-prefix in the doxygen comment

The BEESTRACE macro already injects __FUNCTION__ as a prefix and
__FILE__:__LINE__ as a suffix on the rendered trace line, but the
existing doxygen comment described only the RAII semantics.  Callers
unfamiliar with the macro's expansion would routinely add a redundant
"__FUNCTION__ << \": \"" to the body (carried over from BEESLOG* and
BEESNOTE, neither of which prefixes the function name) and produce
doubled output like "foo: foo: ref ...".

Expand the comment to:

  - state explicitly that __FUNCTION__ and __FILE__:__LINE__ are
    injected automatically, so the argument supplies only the
    call-site payload;
  - show an @code example demonstrating the right form and its
    rendered output;
  - add an @warning admonition that explicitly rejects
    `BEESTRACE(__FUNCTION__ << ": " << ...)` and contrasts the macro
    with BEESLOG / BEESNOTE.

Comment-only change; no behavior or generated code is affected.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agotrace: always write the full trace log if a non-silent exception occurred
Zygo Blaxell [Sat, 30 May 2026 05:03:07 +0000 (01:03 -0400)]
trace: always write the full trace log if a non-silent exception occurred

Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agotrace: Redesign BeesTracer to accumulate and conditionally log traces
Zygo Blaxell [Sat, 23 May 2026 21:47:55 +0000 (17:47 -0400)]
trace: Redesign BeesTracer to accumulate and conditionally log traces

Redesign the BeesTracer class and BEESTRACE macro to collect trace messages in
a thread-local accumulator (tl_captured_traces) during exception stack
unwinding rather than logging them immediately.

If stack unwinding successfully reaches the top of the stack (outermost
tracer), the accumulated traces are written in natural function call order
(caller-first) bracketed by standard BEGIN and END markers. If the exception
is caught early, the traces are safely discarded without polluting logs.

Additionally, update the BEESTRACE macro to use C++14 lambda init-capture of
__FUNCTION__ and brace initialization to cleanly avoid both the Most Vexing
Parse and C++20 designator ambiguities, ensuring the true function name is
printed instead of 'operator()'.

Assisted-by: Antigravity:Gemini-3.5-Flash
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoreporter: add a log sink for reports (filename = -)
Zygo Blaxell [Wed, 17 Jun 2026 04:57:03 +0000 (00:57 -0400)]
reporter: add a log sink for reports (filename = -)

Reports could only be written to files.  Folding the legacy progress log into
the reporter needs a report that emits to the log instead, so the periodic
counter/thread output keeps appearing where operators watch it.

A report whose filename is "-" is a log sink: write_report renders its tokens
as usual, then emits the result via BEESLOG at the report's level rather than
writing a file.  Add a per-report "level" key (syslog-style integer, default
LOG_INFO) and resolve "-" reports to no directory fd.  BEESLOG applies the
same category-level gate as every other log call, so a "-" report respects
log verbosity like anything else.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoconfig: rename [paths]/[reports.*] sections to singular
Zygo Blaxell [Wed, 24 Jun 2026 20:24:16 +0000 (16:24 -0400)]
config: rename [paths]/[reports.*] sections to singular

Every config section family is singular (thread, throttle, log, state,
scan, filter, hash, rewrite, tempfile, loop) except [paths] and
[reports.*].  The v1 schema is still unpublished, so this is the last
chance to make section names consistent without a compatibility alias or
version bump: rename [paths] -> [path] and [reports.*] -> [report.*].

Only the section token changes, not keys: paths.home -> path.home,
paths.reports -> path.reports (the "reports" key naming the report
directory is unchanged), and reports.<name> -> report.<name>.  The
reporter section enumeration in bees_main is updated to sections("report")
with the matching "report." prefix; bees-context.cc, bees-usage.cc, and
the BeesReportConfig doc comment follow.

While renaming bees-usage.cc, fix a stale key reference: the BEESHOME
environment variable was documented as [paths.beeshome], but the key is
home (".beeshome" is only its default value), so it now reads [path.home].

Docs (config-file.md, running.md, wrong.md) are updated in lockstep;
English prose using "reports"/"paths" as ordinary words is left intact.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoreporter: run each report stanza on its own thread
Zygo Blaxell [Wed, 17 Jun 2026 02:35:48 +0000 (22:35 -0400)]
reporter: run each report stanza on its own thread

The reporter ran every report from a single thread driven by a deadline
priority queue.  That serialises all reports behind the slowest write: a
report whose target filesystem stalls (already reachable today via an
absolute report path, and about to become common once a report can target
$BEESHOME) would freeze the fast /run status reports that monitoring depends
on.

Give each active report stanza its own thread, named report_<section>.  Each
thread writes its report and then waits its own interval on the shared
condvar, so a stalled target blocks only that one report.  This also removes
the central scheduler: there is no deadline heap and no reschedule-on-overrun
bookkeeping, just a wait_for loop per report.  The wait_for predicate returns
true only on stop request, so a spurious wakeup falls through to a normal
write rather than firing early.  Shutdown signals stop once and joins every
thread.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoutil: throw on inert BeesStringFile use; callers bail on !home_fd()
Zygo Blaxell [Mon, 27 Apr 2026 01:11:26 +0000 (21:11 -0400)]
util: throw on inert BeesStringFile use; callers bail on !home_fd()

The previous approach made BeesStringFile::read() return an empty string
and BeesStringFile::write() log + no-op when m_dir_fd was empty and the
name was relative.  That silently swallowed a programming error: a
caller had constructed expensive content destined for a file that was
never going to be written.  Replace the silent no-op with a runtime_error
throw so the misuse is operator-visible.

The contract is now: a BeesStringFile bound to home_fd() with a relative
name is only valid when home_fd() is a real fd.  If home_fd() is empty
(state.persistent=no with no on-disk home directory in a follow-up
commit) callers must check !home_fd() upfront and skip the read/write
before constructing content.  The absolute-path branch (m_name starts
with '/') is unchanged: bees-config.cc still passes a Fd() with an
absolute path through AT_FDCWD for the global config file.

Update the three call sites that bind BeesStringFile to home_fd() with
relative names:

  - BeesHashTable stats dump (bees-hash.cc): the entire graph_blob
    construction continues to run unconditionally because the result
    is also written to the log via BEESLOGINFO.  Only the file-write
    half is guarded by if (m_ctx->home_fd()) { ... } so the log copy
    keeps firing when the on-disk state file is unavailable.

  - BeesRoots::snapshot_point() and ::flush_pending_checkpoints()
    (bees-roots.cc): bail at the top when !home_fd().  snapshot_point
    avoids iterating crawlers and serialising the INI string;
    flush_pending_checkpoints is defence-in-depth — with snapshot_point
    bailing the queue stays empty so the loop is a no-op anyway.

  - BeesRoots::import_legacy() (bees-roots.cc): bail at the top when
    !home_fd().  There is no on-disk legacy beescrawl.dat to migrate
    when paths.home is missing, so the BeesStringFile open is skipped
    entirely.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodedup: use bees_readahead_raw
Zygo Blaxell [Sat, 25 Apr 2026 19:51:19 +0000 (15:51 -0400)]
dedup: use bees_readahead_raw

This may help long-running IO stalls we are seeing on dedupe operations.

Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodedup: add physical-extent generation to the logged address format
Zygo Blaxell [Wed, 8 Jul 2026 19:44:25 +0000 (15:44 -0400)]
dedup: add physical-extent generation to the logged address format

The compact address token in dedup/plan log lines, {bytenr+offset[:tag]}, does
not distinguish an extent from a later extent that reused the same bytenr after
the original was freed.  Log analysis that correlates an address across lines
(e.g. deciding whether an extent used as a dedupe src is the same one later
eliminated as a dst) can therefore conflate distinct lifetimes.

Append the physical extent's allocation generation from the extent-tree
EXTENT_ITEM: {bytenr+offset[:tag]/generation}, e.g. {0x1234567000+0x1000:zstd/1234}.
The allocation generation is fixed for one extent's lifetime and changes on
reuse, so it cleanly separates lifetimes.  file_extent_generation is not used:
it is per-reference and differs between reflinks of the same physical extent,
so it cannot identify a physical-extent lifetime.  The value costs one
extent-tree probe, paid only when an address is rendered into a log line.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agocontext: route dedup() physical-address logging through bees_extent_addr
Zygo Blaxell [Thu, 23 Apr 2026 02:57:08 +0000 (22:57 -0400)]
context: route dedup() physical-address logging through bees_extent_addr

Replace the open-coded BeesAddress lookup in BeesContext::dedup() with
the new bees_extent_addr() / bees_extent_same_bytenr() helpers.

Three things go away:

  - The optional<BeesAddress> + addr_string() lambda + two try/catches
    that wrapped the legacy BeesAddress(int, off_t) constructor (which
    can throw on missing extents).  bees_extent_addr() never throws and
    renders {} for missing items, so the call sites become unconditional.

  - The {addr_string(...)} brace-wrapping in the BEESLOGINFO and BEESNOTE
    lines.  bees_extent_addr() returns its own braces, so the format
    string just embeds the call directly.

  - The first_addr / second_addr equality check via get_physical_or_zero(),
    replaced by a single bees_extent_same_bytenr() call that does the
    same "both defined and equal" check inside the helper.

Behavioural changes vs. the prior log output:

  - PREALLOC and compressed extents now render with a tag suffix
    (:prealloc, :zlib, :lzo, :zstd) instead of dropping back to
    "addr-unavailable" or printing only the bytenr.
  - HOLE/INLINE extents now render as {HOLE} / {INLINE} instead of
    triggering the catch path with "addr-unavailable".
  - The +OFFSET inside the braces is the data's logical offset within
    the uncompressed extent, not the physical bytenr-plus-something
    that the old BeesAddress<< produced for compressed extents.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agocontext: introduce s_sectorsize and s_clone_alignment statics
Zygo Blaxell [Thu, 23 Apr 2026 04:10:05 +0000 (00:10 -0400)]
context: introduce s_sectorsize and s_clone_alignment statics

Add two static uint32_t members to BeesContext that hold the
filesystem's sectorsize and clone_alignment as reported by
BTRFS_IOC_FS_INFO.  These become the source of truth for new code
in place of the hardcoded BLOCK_SIZE_CLONE / BLOCK_SIZE_SUMS
constants.  Static is justified because the daemon manages exactly
one filesystem per instance.

Population happens in BeesContext::set_root_fd, the earliest point
where m_root_fd is usable — before BeesConfig parsing, hash table
init, or any other subsystem that might want to consult these
values.  An assertion guards against zero values so a misbehaving
ioctl can't silently produce a divide-by-zero in downstream code.

Log the discovered values at INFO so the daemon's startup banner
records what the filesystem actually claims.  On big-page or
non-default-sectorsize filesystems this makes the deviation from
4096 visible in the log.

Soft-deprecate BLOCK_SIZE_CLONE in its doc comment: new code must
use BeesContext::s_clone_alignment instead.  The constant is kept
because some existing call sites use it as a template parameter
or fixed array bound that needs a compile-time value; those can
migrate incrementally as their surrounding code changes.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodocs: editorial fixes for [state], [state.hash], and [state.point] sections
Zygo Blaxell [Wed, 22 Jul 2026 05:30:26 +0000 (01:30 -0400)]
docs: editorial fixes for [state], [state.hash], and [state.point] sections

Opus isn't very good at commas, apparently.

Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoscripts: make OpenRC init delegate the mount to beesd
Zygo Blaxell [Wed, 24 Jun 2026 20:53:16 +0000 (16:53 -0400)]
scripts: make OpenRC init delegate the mount to beesd

The OpenRC init script mounted the btrfs filesystem itself in start_pre,
in the host mount namespace, and ran the bees binary directly.  That mount
was visible system-wide and leaked if stop_post did not run.  beesd (and
the systemd unit via PrivateMounts=yes) instead mount inside a private
slave-propagation namespace that is invisible to the rest of the system
and torn down automatically when bees exits.

Invoke `beesd --env-config ${fsuuid}` instead of bees directly, so the
mount, mount namespace, and BEESHOME/hash-table setup are all delegated to
beesd.  The script exports the configuration beesd reads in --env-config
mode (DB_SIZE, BEESHOME, BEESSTATUS, OPTIONS); start_pre is reduced to the
fsuuid/DB_SIZE checks and log-directory creation, and stop_post is dropped
because there is no host-namespace mount to clean up.  This removes the
duplicate mount/BEESHOME setup and gives OpenRC the same isolation and
cleanup semantics as the other two front ends.

bees options are passed through beesd's OPTIONS environment variable
rather than its command line: beesd's argument splitter would drop the
value of a space-separated option such as `--scan-mode 4`.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agobeesd: create beeshash.dat at full size, not zero-length
Zygo Blaxell [Fri, 26 Jun 2026 16:54:01 +0000 (12:54 -0400)]
beesd: create beeshash.dat at full size, not zero-length

bees rejects a zero-length beeshash.dat: BeesHashTable::open_file() opens
the existing file and throws on the new_size > 0 check before any resize
can run.  A recent change replaced beesd's "truncate -s $DB_SIZE" with a
bare "touch", delegating sizing to bees's native state.hash.resize.  That
left a fresh install creating an empty hash table that bees cannot open,
so beesd (under both systemd and OpenRC) failed on first start.

Restore beesd's responsibility for creating the hash table at a valid
size: truncate the file to DB_SIZE when it does not exist.  An existing
file is still left untouched, so bees's native resize continues to handle
DB_SIZE changes while preserving hash contents.  DB_SIZE is validated as a
128 KiB multiple before the file is created.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoscripts: use native bees resizing and preserve state
Zygo Blaxell [Sat, 2 May 2026 01:57:09 +0000 (21:57 -0400)]
scripts: use native bees resizing and preserve state

Remove manual hash table resize logic from bees.initd.in and beesd.in.
This logic used to delete beescrawl.dat and beespoint.ini to start
fresh on resize, but bees can now perform in-place resizing while
preserving the persistent crawl state.

Update the scripts to pass -o state.hash.size and -o state.hash.resize=yes
to the bees binary, allowing it to handle creation and resizing
natively.

Assisted-by: Gemini:gemini-3.5-flash
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agoxxhash: add xxhash3 config option
Zygo Blaxell [Fri, 1 May 2026 16:54:22 +0000 (12:54 -0400)]
xxhash: add xxhash3 config option

XXH3_64bits is now stable in xxHash 0.8.x and is ~2x faster than
XXH64 on SSE2 hardware.  Expose it as function = xxhash3 in
[hash.NAME] config sections.

Assisted-by: Claude-Code:claude-sonnet-4-6
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodocs: document [hash.NAME] domain sections
Zygo Blaxell [Tue, 16 Jun 2026 06:06:45 +0000 (02:06 -0400)]
docs: document [hash.NAME] domain sections

Add a config-file.md reference section for hash domains: the [hash.*]
wildcard defaults and concrete [hash.NAME] sections, covering function
(crc64/cityhash/xxhash/xxhash3), priority-based primary-domain selection,
and the step/size/seed/insert keys that are clamped to a single legal
value on this branch.  Explain that the multi-domain model is forward
scaffolding for csum-tree scanning and that only the highest-priority
insert domain is wired into the global hash function today.

Now that the prose lives in config-file.md, trim the redundant block
comment in the [hash.*] built-in schema down to a one-line pointer plus
terse per-key constraints, matching the house style of neighbouring
sections.  Also correct the inline function list to include xxhash3,
which the parser already accepts.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash-domain: add configurable BeesHashDomain and route BeesHash through it
Zygo Blaxell [Sun, 14 Jun 2026 04:25:32 +0000 (00:25 -0400)]
hash-domain: add configurable BeesHashDomain and route BeesHash through it

Add bees-hash-domain.{cc,h} with the runtime types and parser for the
new [hash.NAME] config sections:
  - enum class BeesHashFunction { crc64, cityhash, xxhash }
  - struct BeesHashDomain: name, function, step, size, seed, insert,
    priority, plus a hash() method dispatching to the named function
  - bees_parse_hash_domains(const BeesConfig&): parse all [hash.*]
    sections, validate step/size/seed/insert, return domains sorted
    descending by priority (stable on config-file order for ties)
  - bees_primary_hash_domain(domains): return the highest-priority
    insert-enabled domain

Route BeesHash(ptr, len) through BeesHashDomain::hash() using a
process-global hash function selected at startup.  BeesHash gains a
set_hash_function(BeesHashFunction, uint64_t seed) static entry point
that BeesContext::start() calls once during single-threaded startup
after parsing the config.  Default is CRC-64 so existing
beeshash.dat files stay readable.

Add [hash.*] and [hash.crc64] default sections to bees-config-v1.cc.
So far, only one insert domain is used at a time; the step, size,
seed, and insert values are validated to their constrained shapes
(4096/4096/0/yes) so configs compatible with future multi-hash
configurations still work with the v1 schema.

The domain seed finalization path is present in BeesHashDomain::hash()
as a no-op (seed=0) to keep the dispatch table stable when future
implementations enable it.

Assisted-by: Claude-Code:claude-opus-4-7
Assisted-by: Codex:GPT-5
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodocs: config-file: spell 'bees' correctly
Zygo Blaxell [Tue, 16 Jun 2026 05:01:58 +0000 (01:01 -0400)]
docs: config-file: spell 'bees' correctly

Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agodocs: document [state], [state.hash], and [state.point] sections
Zygo Blaxell [Sun, 26 Apr 2026 21:09:00 +0000 (17:09 -0400)]
docs: document [state], [state.hash], and [state.point] sections

The [state] config family is fully implemented but config-file.md still
treats persistence as undocumented behaviour driven by [paths].  Add
three new sections after [paths] covering all 11 keys: state.persistent;
state.hash.{size,create,resize,writeback-time,writeback-rate-max,
writeback-fsync,writeback-unreadahead,close-fsync}; and
state.point.{interval,defer}.

Source the prose from the operator-facing comments in
src/bees-config-v1.cc:420-490.  The user-doc form is full sentences
rather than the comments' line-wrapped prose, but the technical content
is identical.  Cross-reference behaviour interactions (state.hash.create
is irrelevant when persistent=no, state.point.defer depends on the
hash-writeback counter, expressions in state.hash.size recompute every
startup) and link to the existing size-values and duration-values
references in config-format.md.

The new sections sit between [paths] and [thread] because they govern
the same persistent-state surface as paths.home rather than the
crawl-scheduling surface that follows.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agocheckpoint: trace deferred checkpoint queue lifecycle
Zygo Blaxell [Sat, 25 Jul 2026 01:19:28 +0000 (21:19 -0400)]
checkpoint: trace deferred checkpoint queue lifecycle

When state.point.defer=yes, the existing "Saving beespoint.ini" /
"Nothing to save" / "Saved beespoint.ini in Xs" lines say nothing about
whether the deferred checkpoint queue is actually draining as the hash
table writeback catches up.

Give each PendingCheckpoint a monotonic sequence number and a Timer
stamped at enqueue, then log every queue transition with a "checkpoint"
prefix so the lines are greppable regardless of which thread runs the
flush (writeback thread or the shutdown flush):

  checkpoint queued #57 age 0s writeback 12345      enqueued in snapshot_point()
  checkpoint discarded #14 age 500s writeback 12290 superseded by a later entry
  checkpoint wrote #19 age 480s writeback 12301     durable on disk (peek-then-pop)
  checkpoint dequeued #12 age 512s writeback 12280  obligation removed from the queue

The age is the beespoint data's age since it was captured, so "wrote"
directly reports how stale the checkpoint was when it reached disk. The
seq lets a discarded entry be matched to the queued line it superseded.
The writeback count is the hash table's writeback_extent_count() at
capture time; it gates eligibility (a checkpoint writes once writeback
laps a full extent_count() past it) and correlates each line with the
hash table's own writeback progress.

Assisted-by: Claude-Code:claude-opus-4-8
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agocheckpoint: re-lock mutex on write failure in snapshot_point
Zygo Blaxell [Wed, 3 Jun 2026 05:48:03 +0000 (01:48 -0400)]
checkpoint: re-lock mutex on write failure in snapshot_point

snapshot_point() runs with m_mutex held and, in the non-deferred path,
temporarily released it across m_point_file.write() to keep the slow I/O
off the lock.  The release used a raw mutex::unlock() / mutex::lock()
pair, so a throw from write() unwound out of snapshot_point() with the
mutex left unlocked.  save_point() then called m_mutex.unlock() on the
unlocked mutex, which is undefined behaviour.

Wrap the write in a try/catch that re-locks before rethrowing, so the
postcondition "lock is held on return" holds in both the success and
exception paths.  This is the minimum fix; it does not change the
clean/dirty bookkeeping or the recovery semantics, just the mutex
state on the exception edge.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agocheckpoint: peek-then-pop in flush_pending_checkpoints
Zygo Blaxell [Wed, 3 Jun 2026 05:50:34 +0000 (01:50 -0400)]
checkpoint: peek-then-pop in flush_pending_checkpoints

The queue holds serialized beespoint.ini blobs that snapshot_point()
has handed off; the queue owns the obligation to land them on disk
until a write succeeds.  The previous drain loop popped every
eligible entry up-front and kept only the last one's string on the
stack, so a throw from m_point_file.write() destroyed the only
remaining copy.  In the worst case (no further crawler progress
before shutdown) the unflushed checkpoint was silently lost.

Restructure as peek-then-pop:

  1. Coalesce by popping all earlier eligible entries -- those are
     intentionally superseded by later ones.  The eligibility check
     moves to the second entry so the latest eligible one survives at
     the front.
  2. Verify the surviving head is itself eligible; if not, return.
  3. Copy (do not move) the front entry's ini_string and release the
     lock.
  4. Write outside the lock.  On throw, the entry stays at the front
     for the next call to retry -- or, if a newer entry has been
     enqueued meanwhile, the next coalesce iteration discards this
     one in favour of the newer one.
  5. On success, re-lock and pop.  Safe because the queue is
     single-consumer (writeback thread and the shutdown flush do not
     overlap) and snapshot_point() only ever appends to the tail, so
     the front is still the entry we wrote.

The clean/dirty bookkeeping in snapshot_point() is unchanged: clean
still advances at enqueue, because "clean" means "no new serialized
data needs to be queued", not "all bytes are on disk".  Persistence
of the queued blobs is the queue's responsibility, which this commit
now fulfils across write failures.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agocheckpoint: defer beespoint.ini writes behind hash writeback
Zygo Blaxell [Thu, 23 Apr 2026 21:54:02 +0000 (17:54 -0400)]
checkpoint: defer beespoint.ini writes behind hash writeback

Add a deferred-checkpoint queue so that crawl checkpoints do not advance
past hash table contents that are still buffered in memory.  Without
this, a crash could leave beespoint.ini claiming progress beyond what
beeshash.dat has persisted, causing missed deduplication opportunities on
the next run.

BeesRoots changes:

  * Split save_point() into snapshot_point() (mutate m_point_ini while
    holding m_mutex) and flush_pending_checkpoints() (drain the queue
    outside the lock).  save_point() now orchestrates both.

  * Snapshot takes hash_table()->writeback_extent_count() at enqueue
    time; flush releases entries only once the writeback counter has
    advanced by at least extent_count() entries, guaranteeing every
    extent modified since the snapshot is on disk.  force=true (used
    at shutdown) drains unconditionally.

  * writeback_thread() now polls at m_checkpoint_interval seconds
    instead of the BEES_WRITEBACK_INTERVAL compile-time constant, so
    the state.point.interval config key takes effect.

  * Add load_crawl_state() and print_crawl_state() as the public
    BeesRoots entry points that BeesContext::{load,print}_state()
    will call.

  * Add flush_deferred_checkpoints() for the shutdown path; BeesContext
    invokes it after hash_table()->stop_wait() so pending queue entries
    are flushed to disk before exit.

Config-driven behaviour matrix:

  state.point.defer=no  (default)  - snapshot writes inline, queue unused
  state.point.defer=yes            - snapshot enqueues; writer drains
                                     lazily in save_point() and again
                                     at shutdown via the BeesContext
                                     stop() path.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agohash table: use pretty() for size, not to_hex()
Zygo Blaxell [Fri, 26 Jun 2026 07:06:14 +0000 (03:06 -0400)]
hash table: use pretty() for size, not to_hex()

Signed-off-by: Zygo Blaxell <bees@furryterror.org>
6 weeks agostate: add persistent state config and memory-only hash table
Zygo Blaxell [Sun, 26 Apr 2026 03:09:13 +0000 (23:09 -0400)]
state: add persistent state config and memory-only hash table

Introduces the [state], [state.hash], and [state.point] config
sections, a memory-only mode for the hash table, and setter APIs
on BeesHashTable and BeesRoots for the new config keys.  Wires the
config keys through bees.cc::bees_main so the daemon's startup
banner sets persistence-related options from the configuration
instead of hardcoded constants or the legacy CLI.

Config sections (src/bees-config-v1.cc):

  * [state]: persistent = yes|no.  When `no`, bees starts fresh
    every run with an in-memory hash table; combine with
    loop.exit-when-finished for stateless one-shot deduplication.

  * [state.hash]: size (accepts expressions using min()/max() and
    ${RAM_BYTES}/${FS_BYTES}), create, resize, writeback-time,
    writeback-rate-max, writeback-fsync, writeback-unreadahead,
    close-fsync.

  * [state.point]: interval, defer.

To support the hash-table size expression, bees-config.cc gains
two subst variables (RAM_BYTES from sysconf, FS_BYTES from
fstatfs) and a recursive-descent expression parser replacing the
old parse_size_token function.  The grammar supports the standard
arithmetic precedence with `+`/`-`/`*`/`/`, parentheses, min(),
max(), and the size suffixes K/M/G/T/P/E plus `%`.  `max` on its
own evaluates to uint64_t's maximum.

BeesHashTable (src/bees-hash.cc, src/bees.h) grows:

  * An m_persistent flag and NoFileTag/NoThreadsTag construction
    tags that allow a RAM-only instance or a file-backed instance
    without background threads.
  * A private init() helper shared by all constructors.
  * A resize_file() helper supporting in-place table resize on
    startup via the reverse-LRU rebuild path.
  * Setter APIs for every [state.hash.*] key.
  * Conditional branches in the writeback and prefetch paths that
    short-circuit file I/O when m_persistent is false.
  * An m_writeback_extent_count atomic so the crawl-checkpoint
    defer path can observe progress.

BeesRoots (src/bees.h, src/bees-roots.cc) grows three setter APIs
(set_checkpoint_interval, set_persistent, set_checkpoint_defer)
and the backing members
(m_checkpoint_interval/m_roots_persistent/m_checkpoint_defer).
Actual checkpoint deferral logic (snapshot_point,
flush_pending_checkpoints, the BeesCrawl idle semantics, etc.)
lands in a later round; this commit only provides the
setters that bees.cc needs to call at startup.

bees.cc::bees_main gets a state-setup block that reads every
[state.*] key, builds the hash table in either persistent or
memory-only mode, and configures the crawl-checkpoint policy.

Assisted-by: Claude-Code:claude-opus-4-7
Signed-off-by: Zygo Blaxell <bees@furryterror.org>