strawberry/fuzz/fuzz_rarity_state.cpp
trvon f76db466eb
Some checks failed
Build and Test / build (debug, clang) (push) Has been cancelled
Build and Test / build (debug, gcc) (push) Has been cancelled
Build and Test / build (release, clang) (push) Has been cancelled
Build and Test / build (release, gcc) (push) Has been cancelled
Build and Test / macos (push) Has been cancelled
Build and Test / docker (push) Has been cancelled
Stage 4: keep the live rarity model across daemon restarts
The shadow scorer's rarity model started empty at every daemon start, so
each restart cost an hour of warm-up with no decisions. The daemon now
saves it to model_dir/rarity.state (checksummed, atomic write, hourly and
at stop) and restores it at start. A restored state younger than the
7-day half-life skips the warm-up; decay catches up on the first event.

A file made with other rarity settings, a bad checksum, or a negative or
non-finite count is refused with a reason (status model.rarity_state,
doctor model.rarity_state) and the model starts empty. The file must be
owned by the daemon user and not group/world writable, like model files.

Also fixes status model.warmup_windows, which was never filled in.

Tests: R1/R2 in test_learn (round trip, decay clock, refusals), S8 in
test_shadow (warm-up skipped only when recent), daemon restart restores
the saved state, doctor warning; new fuzz_rarity_state target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 23:25:01 -06:00

46 lines
1.4 KiB
C++

// Rarity state decoder over untrusted bytes: never crashes; what it accepts
// re-encodes to the same bytes and scores safely. Each input is tried as a
// whole file and, with a valid checksum appended, as a file body (so the
// fuzzer reaches the parser behind the checksum).
#include "strawberry/hash_utils.hpp"
#include "strawberry/learn/rarity.hpp"
#include <cmath>
#include <cstdint>
#include <string>
using namespace strawberry;
using namespace strawberry::learn;
namespace {
void check(std::string_view file) {
RarityOptions small;
small.width_log2 = 4; // small sketches, so short inputs can be valid
small.depth = 1;
small.first_seen_capacity = 8;
RarityModel m(small);
int64_t saved = 0;
std::string error;
if (m.decode_state(file, saved, error)) {
if (m.encode_state(saved) != file) __builtin_trap();
const auto s = m.surprisal(TupleKind::parent_child, "a > b");
if (!std::isfinite(s.bits) || s.bits < 0) __builtin_trap();
m.advance_to(saved);
(void) m.first_seen("k", saved);
} else if (error.empty()) {
__builtin_trap();
}
}
} // namespace
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
const std::string_view in(reinterpret_cast<const char*>(data), size);
check(in);
std::string body(in);
body += HashUtils::sha256_data(data, size);
check(body);
return 0;
}