The generic `pio test -e native` selected test_packet_filter and
test_battery_gate, which need their own include paths, source selection and
filesystem shim; both errored out and failed the whole command. List them in
test_ignore so each runs in the environment that can actually build it.
Also correct the safety net the review found unsound:
- makePacket() left payload, path and transport codes uninitialized while
mesh::Packet's constructor only sets header/path_len/payload_len, so tests
hashed whatever the stack held. Initialize them, and clamp payload_len, hsz
and hops to the real buffer bounds. LenInterval's 200-byte packet became the
184-byte boundary that actually exists; the hsize=4 case is now labelled
artificial, since Packet::setPath rejects hash size 4 as reserved.
- filterCLI() was called through a null RegionMap*, and the CLI does call
members on it. Provide the real constructor in the stub and pass an instance.
- NativeFile::read() formed a data pointer for zero-length and past-EOF reads,
so reading an empty file passed nullptr to memcpy. Return 0 first. write()
validates its backing store and tracks position; the two-argument open now
honours "r"/"w", and flush/rename exist for the persistence work to come.
- The CLI helper now replies into the real 160-byte CLI_REPLY_MAX with a canary
after it, asserting both no overrun and NUL termination in the window.
Add ASan+UBSan environments for both feature suites so "assertions passed" is
not mistaken for "no undefined behaviour". The three problems the review found
this way — the oversized fixture, the null member call and the empty read —
had all been passing their assertions.
54 native + native_kiss_modem cases green; the sanitizer envs report zero
diagnostics.
Folding sender= and text= into one branch kept the original text= arm as
unreachable code, and put the IvUnit enum between parseIvNum()'s comment and
parseIvNum(). Both are caught by reading the diff rather than by a test.
The private/public sandwich around the one-line declaration was noise;
resetToDefaults() belongs at the bottom with the rest of the class's
internals. Also aligns the save_flag comment with its neighbours.
"filter add 0 chan=<admin channel> action=forward" is left over from a CLI that
took an index; `filter add` takes key=value pairs only, so the command as
written answers "Err - expected key=value, got '0'" — advice that cannot work
in the one situation it is meant for.
ruleDigest() does two jobs with the same bytes: the digest `filter list` shows,
and the salt of the prob roll. Its range is the whole persisted record, tail
padding included, so editing a prob= rule — or loading a config under firmware
whose record differs — silently re-rolls which packets that rule decides, and
churns the digest column at the same time.
Nothing changes here: the roll is what it has always been, and changing it
would change which packets existing rules drop. What was missing is that this
is a choice, and it is now written down in both places: the function says the
two jobs are shared on purpose and that a stable rule identity wants a
different function, and FILTER.md tells users the roll is deterministic per
packet per stored rule, not forever.
Two small things in the channel store:
- `filter get`-style status recounted the channels with a non-empty name, but
every slot below num_channels always has one (addChannel only ever writes the
slot it is about to count, and delChannel zeroes the tail), so the count was
always num_channels. The dead loop is gone; the rest of the file already
treated the store as dense, except searchChannelsByHash()'s null-key guard,
which stays as the corruption check it is.
- `chan - filter.getChannel(0)` appeared twice as a way to ask "which index is
this channel?". indexOfChannel() now answers that directly and findChannel()
is a thin wrapper over it, so `filter add chan=` does one lookup instead of
find-then-subtract.
No reply changes (StatusLineFormat pins the exact line).
patternAborted() answered "did the last patternMatches() give up?" from a
file-static flag, which put an invisible ordering requirement between two
files: read it too late and you count some other pattern's abort. The only
caller is FilterRules::regexMatches(), counting budget aborts for `filter
stats`.
patternMatches() now takes an optional `bool* aborted`, written on every call
(false first), and the global is gone. The parameter defaults to NULL, so the
~40 test call sites that only want a yes/no keep reading as before.
The vendored engine keeps its own budget-exhausted flag — that is TinyRegex's
documented API and stays untouched.
The "bill airtime exactly once per packet" rule was spread over five
`air_evaluated_ms += …` / `air_saved_ms += …` statements in two functions,
with the reason each one is conditional living in a comment somewhere else —
including the one case that is easy to get wrong, a content drop that never
reaches the forwarding hook and so is billed by the phase that dropped it.
billEvaluated() and billSaved() are one-liners, but they put the rule in one
comment next to the only two counters it governs, and every call site now says
which of the two it means. No arithmetic changes; the existing airtime tests
(including the counted-once ones) cover the result.
checkContent() called millis() inside the rule loop, so the throttle gate
stamped throttle_last_ms from a fresh reading per rule, while checkPacket()
takes its clock as a parameter. Both read the same millis(), but one rule's
window could then be stamped from a later millisecond than its neighbour's.
The scan now takes one reading and passes it to every rule, which is what
checkPacket() effectively already did. No behavior change on this platform.
Packet::calculatePacketHash() is a SHA-256 over the payload, and probDecides()
called it for every matching rule that carries prob= — up to FILTER_MAX_RULES
hashes per packet, plus one to tag the content-verdict stash and one to verify
it in checkPacket().
PacketHashCache computes it once per entry point and hands out the same
bytes, so the prob rolls, the stash tag and the stash guard all share one
hash, and a list with no prob rules still pays exactly what it did before
(nothing, or one for the guard).
The roll is bit-for-bit what it was: same hash bytes, same salt, same order.
"Which predicates can only be judged on decrypted data" lived in two places:
ruleIsDeferred() named the three fields for the packet-level phase, and
checkContent() re-tested the same three fields inline. A new content predicate
added to only one of them would be evaluated in the wrong phase — and since
content predicates never match a packet-level scan, the failure mode is a rule
that silently never fires.
contentPredicates() is now the single answer, as a flag set: the packet phase
asks "is any bit set", the content phase switches on the same value. No
behavior change, and the existing
ContentRulesAreDeferredNotDroppedAtPacketLevel already pins all three
predicates' deferral, so it stands as the regression net.
BatteryGate.cpp still used sprintf() into the reply buffer in three places,
which the fork's hard invariant forbids — commit 0a784736 bounded the filter
CLI and left this file behind. All three write constants today, so nothing
overflowed, but the invariant is about the call, not the payload.
While here, the same edits the filter CLI had already made:
- the usage line was spelled out three times; it is one BATT_USAGE constant now
- the "digits but out of range" vs "not a number at all" distinction moves out
of parseMilliVolts' `bool* numeric` out-parameter into badMilliVolts(), which
also drops the hand-rolled strtol in favor of the shared parseIntRange()
- every reply write goes through snprintf(reply, CLI_REPLY_MAX, ...)
- setThresholds()'s return was ignored; it is noted as unreachable, since the
range and the hysteresis were both checked above
CliUtil.h gains cliCopyCommand(), so both handlers copy the command tail into
their scratch buffer the same way (the battery CLI had its own strncpy + NUL).
It is written without StrHelper::strzcpy on purpose: the battery gate's host
test build links neither StrHelper nor ltoa(), and a shared header that drags
in a link dependency for six lines of truncation is worse than the duplication
it removes.
Reply strings are unchanged.
`filter add` spelled out the same four things several times over:
- copy a comma list into a scratch buffer for strsep(), refusing a value that
does not fit — written out for chan=, type=, region= and hsize=
- "parse a whole decimal token in [lo, hi]" — hand-rolled for prob, throttle,
hsize, the interval endpoints and `ratelimit advert <hours>`, each with a
slightly different notion of what "a number" means
- the hops/len/snr branches differed only in which Interval they filled and
which word the error used
- sender and text differed only in destination and length
copyCsvList() and parseIvNum()'s new IvUnit enum (instead of a bool snr_mode
threaded through parse/format) collapse those, and the rules are named by `key`
in the reply. The interval error wording is unchanged, as is every accepted
value — with one deliberate tightening, called out because it changes
behavior:
filter ratelimit advert abc used to answer "OK - advert ratelimit 0h"
filter add hsize=2x used to answer "OK - rule 0 added" (atoi -> 2)
Both are now errors, matching what every other numeric parameter already did
and what `filter get`'s own round-trip needs. Covered by tests.
Also rewrites parseInterval's high-endpoint length as `hend - (comma + 1)`
instead of `len - 1 - (comma - tok) - 1`.
Both configs spelled out their "fresh node" state twice — once in the
constructor, once at the top of load() — and the two copies had drifted:
- FilterRules::load() reset the rule store, the counts and `enabled`, but not
the advert window, the drop/abort counters or the airtime totals. A reload
whose file was missing, truncated or of an unknown version therefore kept
the previous ratelimit window and stats: `filter ratelimit advert 9` +
a deleted config file came back as 9.
- BatteryGate::load() reset its RAM counters, FilterRules::load() did not.
Each class now has one resetToDefaults() used by both the constructor and
load(), so a field added later is reset by both. For FilterRules that also
means a reload clears the limiter's cache and counters — derived state the
file does not hold, which is the point of loading.
Tests: a reload with no config file leaves both configs in their documented
default state (previously the filter kept its window and its off state).
Also drops the `if (!enabled) { enabled = true; }` dance in
BatteryGate::setThresholds().
FilterRules had grown to hold four unrelated things: the rule store, the keyed
channel store, the per-node advert window, and the telemetry/persistence around
them. The advert window is self-contained (a ring cache, a repeat-window length
and a drop counter, with its own CLI verbs and its own tests), so it moves into
AdvertRateLimiter.{h,cpp} and FilterRules keeps thin forwarders — MyMesh, the
CLI and the tests see the same API as before.
Pure move, with two mechanical cleanups made while relocating the code:
- the "is the ring wrapped" test was recomputed on every scan iteration; it is
loop-invariant, so it is now computed once (AdvertRateLimiter::drop)
- "limiter off" (hours == 0) moved inside drop(), so checkPacket() asks one
question instead of testing the flag and then calling
The persisted window length is still two bytes at the same offset in the config
header; load()/save() read and write it through the limiter.
247 native tests unchanged (the 12 limiter cases cover the moved code).
PacketFilterConfig.h invites per-build overrides of every capacity number,
but two of them (FILTER_PATH_HASH_SLOTS, FILTER_REGION_LIST_LEN) live inside
FilterRule and so move every persisted offset after them. FILTER_REGION_LIST_LEN
already had a static_assert for this; FILTER_PATH_HASH_SLOTS had none, and
raising it failed on an unrelated-looking message:
error: static assertion failed: FilterRule::throttle must start where the
v4/v5 record ended
A named static_assert now fails on the knob that was raised and says what a
real change costs (FILTER_CFG_VERSION bump plus migration code in load()), and
the config header says which knobs are layout-affecting. parsePath's scratch
buffer is sized from the macro instead of a hardcoded 4 (same size today).
Nothing changes for the default build.
Both save()s cleared their dirty flag before opening the file, so a config
that could not be written (open failed, flash full) was silently marked saved
and never retried — the change was lost until the next mutation.
The flag is now cleared only after the write actually completed: the filter
reuses the `ok` it already accumulates, and the battery gate checks the record
write for the first time. A failed write stays dirty and loop() retries it; a
partial file is already discarded by the length checks in load().
No test: the native FS shim cannot fail an open, and the property is the
absence of a lost write rather than a reachable behavior.
The filter and the battery gate each carried their own copy of the same two
things: the dirty-flag + write-back timer (two constants, both 3000 ms, two
markDirty() bodies, two loop() checks) and the per-platform file-open #if
blocks (read mode in both load()s, write mode in filterOpenWrite() and again
inline in BatteryGate::save()). Adding a target meant editing every copy.
PersistUtil.h (fork-owned, the persistence counterpart of CliUtil.h) now
holds LazySave (markDirty/due/clear) plus fsOpenRead()/fsOpenWrite(), and both
configs use them. CliUtil.h set the precedent that a shared helper belongs
here rather than in one config's .cpp.
Pure move: the delay is unchanged, the platform modes are unchanged, and the
dirty flag is still cleared at the same point in save().
`chan=` provisions '#' names into the channel store while it parses, but a
rejected later param only removed the half-built rule:
filter add chan=#leaky type=wat -> Err - unknown type 'wat'
rules 0, channels 2, #leaky present
That is not inert: a stored '#' PSK is what searchChannelsByHash() hands to
core's group decryption, so a typo'd add silently left the repeater decrypting
a channel no rule refers to.
A rejected add now removes the rule and any channel it added (they are always
appended, so the tail is dropped from the end). Success paths are unchanged.
Test: a failed add leaves the store exactly as it was, and a following good
add still provisions.
parseHexHash() accepted up to 8 hex chars and decoded n/2 bytes into the
caller's pointer, with no size to write against. `filter add chanhash=AABB`
therefore wrote 2 bytes into FilterRule::chan_hash and `=AABBCCDDEE` wrote 4,
running into chan_flags and the first bytes of sender (chan_hash@48,
chan_flags@49, sender@50). Only the rollback of the half-added rule kept the
corruption from being stored.
parseHexHash() now takes the destination size and refuses a value that does
not fit, so a longer chanhash is rejected before anything is written. Path
entries pass their own 4-byte capacity, which is unchanged behavior.
No functional change to accepted rules: chanhash still takes exactly one
byte. Test: an 8-hex-char chanhash is refused like every other wrong length.
Top-level '|' alternation for sender=/text= patterns, implemented in the
fork-owned PatternMatch wrapper so the vendored engine keeps only bug fixes.
FILTER.md documents the dialect, the 8-alternative cap and the stored-config
compatibility notes.
Follow-up to f1d4f9e6, which fixed the history-dependent matching in the
wrong layer: it enumerated the affected shapes in the wrapper (altDefect),
where they had to be kept in sync with the engine's parser by hand. This fixes
the mechanism in the engine instead and drops that scanner.
re_compile() never sets `ch` for BEGIN/END/quantifier symbols, and matchone()'s
default case compared that byte whenever such a symbol was used as an operand —
so '*Bot', 'a**', 'A^B' and '^*' matched, or didn't, depending on whichever
pattern had been compiled before. matchone() now returns 0 for those: they
consume nothing, so they match nothing.
Measured over every pattern up to length 5 on a metacharacter alphabet, both
engines side by side across 1,417,240 pattern/subject combinations:
identical to the old engine 1,409,299
changed, was history-dependent 7,941
changed, was deterministic 0
So no pattern that ever behaved predictably changes; the class is simply gone.
The wrapper rule is no longer needed and is removed, which also drops the
per-branch scan it added to the packet path and the third copy of the
tokenizer. filter add accepts these patterns again, as it did before: they
match nothing, the same as any pattern that does not match what you meant.
Tests: 217 filter cases (was 220 — the two wrapper-rejection tests and their two
CLI equivalents gave way to one engine-level test,
TinyRegexOperands.NothingToRepeatMatchesNothing, which pins the contract and
checks that well-formed patterns still match what they always did. The
determinism test stays, now covering the previously-garbage shapes through the
filter's own entry point. '$*' is called out explicitly: a quantifier on '$' has
no operand to reject and degenerates to matching the empty string, harmlessly
and stably.
Verified: 217 + 29 cases green, suite clean under ASan+UBSan; determinism
sweep 1,240,085 cases with zero history-dependent patterns; differential fuzz
479,676 cases with no disagreement of any kind against the engine (the wrapper
is now behaviour-neutral for patterns without '|'); CLI fuzz 300k lines clean;
all 36 patterns the guide shows still accepted; Xiao_S3_WIO_repeater builds, RAM
unchanged at 20.6%.
Vendored delta is now two code lines. AGENTS.md records the rule that motivated
it: vendored source changes for bug fixes only, and only after asking — not
every bug is worth a vendored edit, so the trade-off gets proposed rather than
decided unilaterally.
An adversarial pass over the pattern layer (differential fuzzing against the
vendored engine, an exhaustive history-dependence sweep, and a CLI fuzz)
turned up a pre-existing engine defect that makes a rule decide packets at
random:
re_compile() never fills in the `ch` byte of BEGIN/END/quantifier symbols, and
matchone() compares that byte whenever such a symbol is used as an operand.
Every pattern up to length 5 was enumerated over a metacharacter alphabet:
16,999 of 1,240,085 pattern/subject combinations answered differently depending
on which pattern had been compiled before them. `sender=*Bot`, `sender=a**` and
`sender=A^B` all match — or don't — according to the previous packet's rule. In
a filter that either leaks the traffic a drop rule was meant to stop or silences
it when it should not.
Fixed in the wrapper, which already owns structural validation, rather than in
the vendored engine (which stays byte-identical):
- "nothing to repeat" — a '*', '+' or '?' with no repeatable symbol before it,
including a quantifier on an anchor ('^*') and stacked quantifiers ('a**').
- "^ and $ must be at the pattern edges" — an anchor away from the edges of its
own alternative. Per alternative, so '^a|b$' is fine.
As with the empty alternative, both are add-time rules that matching also
honours: a stored rule carrying such a pattern now matches nothing rather than
guessing, and the reply names the offending field.
The same fuzzing caught a bug in the new checker itself — it tested for the
class end before the escape, so '[\]]' closed the class early and diverged from
the engine's parse. Fixed, and the escape now takes precedence exactly as in
splitAlternatives().
Tests: 220 filter cases (was 215). New NothingToRepeatRejected,
AnchorsMustBeAtPatternEdges, AddRejectsPatternsTheEngineCannotDecide,
StoredUndecidablePatternNeverMatches, and
PatternMatchDeterminism.VerdictDoesNotDependOnEarlierPatterns, which primes the
shared engine state and pins a stable verdict for every pattern in the table.
Verified: full suite clean under ASan+UBSan; 479,676 differential cases with no
unexplained disagreement; 1,240,085-case history-dependence sweep with zero
escapes; 300k-line CLI fuzz with no overrun, bad reply or rule-list drift; all
34 patterns the guide shows still accepted; Xiao_S3_WIO_repeater builds (RAM
unchanged at 20.6%).
Fixing this at the source would mean a fourth documented modification to
TinyRegex.cpp (have matchone() treat non-consuming symbols as non-matching
instead of comparing that byte). Left alone pending a decision.
Review pass over the alternation feature.
Behaviour:
- A stored pattern that splits into an empty branch ("A||B", "A|", "|A" —
all accepted by the firmware that took '|' literally) stopped matching
entirely: splitAlternatives() refused to split it, so patternMatches()
returned false for the whole rule. The splitter is now purely mechanical;
patternValid() refuses an empty branch at add time and patternMatches()
skips branches that cannot match, keeping the ones around it. A branch the
engine refuses is skipped for the same reason.
- Rejections name the field they came from: "Err - empty alternative in
sender regex" rather than "... in regex", which was ambiguous for a rule
carrying both sender= and text=. The wrapper's reasons are field-agnostic
phrases the caller composes, so PacketFilter no longer depends on TinyRegex.
Docs (FILTER.md, same commit as the behaviour):
- The groups row claimed ^(Alice|Bob)$ does not match the literal name
(Alice|Bob); the first alternative is a prefix match, so it does.
- The no-groups bullet now also gives the escaped spelling for a literal pipe.
- Stated once that a pipe inside a table is written \| only so the cell
renders, which otherwise reads as the dialect's literal-pipe escape.
- Trimmed the cost and pattern-length sentences that Alternation and Limits
both carried.
Deslop: PATTERN_ERR_MAX replaces three hardcoded 48s, a stale file list in the
test header and a comment restating setPattern()'s doc comment are gone, and
the over-long-pattern test now exceeds either pattern storage by construction.
No persistence change — patterns are stored verbatim, so no config version
bump. TinyRegex.h/.cpp are back to being byte-identical to the base branch.
215 filter cases (was 213) and 29 battery cases green; Xiao_S3_WIO_repeater
builds.
Stage 1 of plans/2026-10-01-filter-regex-alternation.md: a new fork-owned
wrapper, PatternMatch.h/.cpp, owns the user-facing pattern language and adds
top-level '|' alternation to sender=/text=:
filter add sender=^Alice$|^Bob$
The vendored TinyRegex engine is untouched — it keeps its three documented
modifications, and syntax is added one layer up, in the wrapper. The pattern
is stored as text exactly as before, so there is no persistence change, no
FILTER_CFG_VERSION bump and no static_assert change.
Wrapper behaviour:
- top-level '|' splits the pattern; each alternative is compiled and matched
in order, first match wins, so anchors bind per alternative (^Alice|Bob$
is "(^Alice)|(Bob$)"). '\|' and '[|]' stay literal pipes;
- empty alternatives ("A|", "|A", "A||B") are rejected — an empty branch
matches everything;
- at most FILTER_PATTERN_MAX_ALTS (8, new build-flag-overridable tunable in
PacketFilterConfig.h) alternatives per pattern;
- evaluation stops at the first alternative that exhausts the engine step
budget, fail-open, counted once in budget_aborts as before.
Groups stay unsupported and parentheses keep today's literal behavior, so
"^(Alice|Bob)$" is accepted and matches a sender literally named "(Alice|Bob)"
— documented as the trap it is, in FILTER.md.
Compatibility: one intentional reinterpretation. A stored pattern containing
an unescaped '|' previously matched a literal pipe and now means OR; write
'\|' for a literal pipe. Noted in FILTER.md and in this subject line, which
is what the release body's filter-changes section lists.
Reply strings: existing ones stay byte-identical ("Err - bad/long sender
regex" / "Err - bad/long text regex" remain the fallback for engine-level
rejections); only newly rejected patterns gain strings — "Err - empty
alternative in regex" and "Err - too many alternatives (max 8)".
Verified: pio test -e native_packet_filter 213 cases pass (196 pre-existing,
unchanged, plus 17 new covering alternation, per-branch anchors, escapes,
structural rejections, budget interaction, CLI round-trip and checkContent
rules); pio test -e native_battery_gate 29 pass. Firmware compile check
pio run -e Xiao_S3_WIO_repeater: +712 B flash, +8 B RAM, no new static RAM
in the filter itself (48 B of stack during evaluation).
FILTER.md documents the syntax, the per-branch anchor footgun, the cap, the
pattern-length pressure and the compat break; AGENTS.md gains the amendments
approved in the plan (fork-owned file set, code map, hard invariant #5,
backwards-compat rule, test counts).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Drop 'Built from', 'Upstream base', and 'Targets' lines from the release
body; it now contains just 'Filter changes in this build' plus the
auto-generated notes. Remove the now-unused base_line and short_sha
step outputs.
- factor the duplicated match tail in checkPacket()/checkContent()
(prob + throttle gates, hit count, airtime billing) into one
FilterRules::decideMatch() helper
- consume the content-verdict stash in one place in checkPacket()
- parseHexHash() reuses filterDecodeHex() instead of a second hex loop
- bound every CLI reply write with snprintf(reply, CLI_REPLY_MAX, ...)
to match the two sites that were already bounded
- merge the twin enable/disable CLI branches
Native tests: 191/191 passing (pio test -e native_packet_filter).
The FIRMWARE_TARGETS repo variable is shared by the dev and stable
channels, but each channel builds its own branch: targets added to
platformio.ini on dev are not visible to repeater-filter-stable until
its upstream base (main) gains them. Fail-hard validation then blocked
the stable channel for boards it never offered (muzi_base_duo_repeater).
Warn and skip unknown targets instead, matching how the build job
already omits boards that fail to compile. Still fail when every
target is unknown so a typo'd or emptied variable is not silently
ignored.
Mirrors the upstream firmware-builder.yml pattern: continue-on-error on
the build matrix job so a broken board is omitted from the release
artifacts instead of failing the whole run.
The FIRMWARE_TARGETS repo variable contains CRLF line endings, so every
target name carries a trailing \r and the validate step rejects the first
entry ('Unknown build target'). Strip \r before splitting on
spaces/commas/newlines in both the validation loop and the JSON array
conversion.
Force-build runs left RANGE at HEAD, so the curated 'Filter changes in
this build' section had no lower bound and listed every filter commit
ever made instead of only commits since the channel's previous tag.
Set RANGE to <prev-tag>..HEAD in the forced path when a previous tag
exists; the skip gate is unaffected (forced builds still always build).