Commit Graph

766 Commits

Author SHA1 Message Date
Christopher Haster 37288fceab scripts: Renamed -p/--percent -> -%/--percent
How long has there been a whole key dedicated to percentages sitting on
my keyboard!?

There's some funky business with format strings in argparse, but this
was already worked around for dbgbmap.py's -%/--usage flag.
2026-03-09 22:54:20 -05:00
Christopher Haster 2cf87dedb4 scripts: csv.py: Added -H/--hlabel and --tlabel
These are useful for customizing the table renderer's header and total
labels:

  ./scripts/csv.py test.csv -ba -fc \
      -Hc='c(MiB/s)' \
      --tlabel='wow so many (%(c)s)'
  a                   c(MiB/s)
  x                          6
  wow so many (6)            6

In theory header labels could be controlled by the field names
themselves, but our use of Python's namedtuples internal is quite
limiting.

The immediate use case is -Hprobe=bench+probe in the bench-related
rules, but it may also be useful for adding units such as in the above
example.

---

I considered adding these to all csv scripts, but decided that was too
much. punescape modifiers are probably a good line for what should be
limited to csv.py.
2026-03-09 22:54:11 -05:00
Christopher Haster 8bbddd3500 scripts: Added shortform for -t/--total flag
This flag has proven useful in external scripts, might as well give it a
short form.

-t is also an infrequently used flag, so I think the risk of collision
is low even across all csv scripts. The only existing use is in
test/bench.py for -t/--trace (and apparently in gcov for -t/--stdout?).
2026-03-09 22:54:07 -05:00
Christopher Haster b99d245cd8 scripts: Renamed -c/--compare -> -C/--compare
The lowercase -c/--compare felt clunky. I think because we tend towards
using uppercase for flags that operate on csv rows, such as -D/--define,
-L/--add-label (plot.py), etc.
2026-03-09 22:54:04 -05:00
Christopher Haster e1b0abf446 scripts: csv.py: Renamed -L/--list-computed -> -L/--list-eval
I forgot the name and think this is slightly easier to remember, "eval"
is quite a bit more common in programmer lingo.
2026-03-09 22:54:00 -05:00
Christopher Haster ad9b39a762 scripts: csv.py: Added saturate function
This is useful for enforcing an upper-bound on fracs based on their
total component.

Technically possible via decomposing + min + recomposing, but... Well
which one do you think is easier?

- saturate(x)
- frac(min(max(int(x), 0), total(x)), total(x))

And this assumes x is easily available and not some other expr (though
chaining csv.py could work around that).

---

The motivation for this was `make bench-widths`, where one read
benchmark could ruin the entire column due to introducing infinities.
Now:

  make bench # (squished a bit)
  probe           readed               progged                  erased
  b_wt_seq+w     1.0/1.0 (100.0%)   31.7/256.0 (12.4%)   4096.0/4096.0 (100.0%)
  b_wt_random+w  1.0/1.0 (100.0%)   15.3/256.0 (6.0%)    4096.0/4096.0 (100.0%)
  b_wt_logging+w 1.0/1.0 (100.0%)   15.4/256.0 (6.0%)    4096.0/4096.0 (100.0%)
  b_wt_many+w    1.0/1.0 (100.0%)   16.1/256.0 (6.3%)    4096.0/4096.0 (100.0%)
  b_rt_seq+r     1.0/1.0 (100.0%)  256.0/256.0 (100.0%)  4096.0/4096.0 (100.0%)
  b_rt_random+r  1.0/1.0 (100.0%)  256.0/256.0 (100.0%)  4096.0/4096.0 (100.0%)
  b_rt_many+r    1.0/1.0 (100.0%)  256.0/256.0 (100.0%)  4096.0/4096.0 (100.0%)
  TOTAL          1.0/1.0 (100.0%)  149.0/256.0 (58.2%)   4096.0/4096.0 (100.0%)
  #                                  ^- notably not infinity
2026-03-09 22:53:54 -05:00
Christopher Haster b751981574 scripts: Added CsvFfrac type
A simple float variant of the CsvFrac type:

- frac(1.5,2)  => 1/2 (50.0%)
- ffrac(1.5,2) => 1.5/2.0 (75.0%)

Useful for `make bench-widths` (previously make bench-bus), where we
want to find the average buffer utilization:

  probe            readed              progged                 erased
  b_rbyd+create   1.0/1.0 (100.0%)  13.8/256.0 (5.4%)        ∞/4096.0 (∞%)
  b_rbyd+delete     ∞/1.0 (∞%)         ∞/256.0 (∞%)          ∞/4096.0 (∞%)
  b_rbyd+fetch    1.0/1.0 (100.0%)     ∞/256.0 (∞%)          ∞/4096.0 (∞%)
  b_rbyd+lookup   1.0/1.0 (100.0%)     ∞/256.0 (∞%)          ∞/4096.0 (∞%)
  b_rbyd+usage      ∞/1.0 (∞%)         ∞/256.0 (∞%)          ∞/4096.0 (∞%)
  b_wt_seq+w      1.0/1.0 (100.0%)  31.7/256.0 (12.4%)  4096.0/4096.0 (100.0%)
  b_wt_random+w   1.0/1.0 (100.0%)  15.3/256.0 (6.0%)   4096.0/4096.0 (100.0%)
  b_wt_logging+w  1.0/1.0 (100.0%)  15.4/256.0 (6.0%)   4096.0/4096.0 (100.0%)
  b_wt_many+w     1.0/1.0 (100.0%)  16.1/256.0 (6.3%)   4096.0/4096.0 (100.0%)
  TOTAL             ∞/1.0 (∞%)         ∞/256.0 (∞%)          ∞/4096.0 (∞%)

Now that we have 4 types, the cast matrix gets a bit complicated, but
this is side-stepped a bit by a custom __frac__ hook.

---

Some other tweaks to csv.py:

- Added CsvFold.type to typecheck folds _after_ we know the expr's final
  type.

- Adopted CsvFfrac as an output for most of the math functions/folds

- Stopped early termination of typechecking if we change type!

  This was broken: int(float(1.5) + int(1))
2026-03-09 22:52:51 -05:00
Christopher Haster 73e06612bf scripts: Added __hash__ to CsvFrac, tweaked __eq__
This adds __hash__ to CsvFrac, and tweakes __eq__ to be more strict
about equality.

Previously CsvFrac only considered the relevant ratio for equality,
making hashing difficult:

- before: 1/2 == 2/4 => true
- after:  1/2 == 2/4 => false

But now that we have csv.py, with the explicit ratio function, it's
probably a good idea to be strict by default.

Note comparison is unchanged:

- 1/2 < 2/4 => false
- 1/2 > 2/3 => false

---

This popped up during debugging, and would be useful to have around.

Note CsvInt/CsvFloat already implicitly define __hash__ through
namedtuple's implicit __eq__ and friends. But this is disabled in
CsvFrac due to the explicit __eq__.

Which is good because otherwise it would've been wrong with the ratio
comparison!
2026-03-09 22:52:47 -05:00
Christopher Haster ebde2c7063 runners: Added both run+compile-time --no-internal/reentrant/fuzz flags
--no-internal has already proven useful for skipping internal tests for
refactoring, so it makes sense to add --no-reentrant/fuzz flags as well.
--no-fuzz seems particularly useful for when you want to skip the less
targeted fuzz tests:

- with fuzz tests: 634616/634616 passed, in 1239.90s
- with --no-fuzz:    85434/85434 passed, in  423.41s

I also added runtime variants to test/bench_runner and test/bench.py.
These may be useful to skip tests without needing to recompile the
runner.

---

Also tweaked -s/--step to filter permutations in any --list-* flags, for
consistency.
2026-03-09 22:52:10 -05:00
Christopher Haster 9974656c5c scripts: test.py/bench.py: Added explicit internal flag
This adds an explicit:

  internal = true

As an alternative to:

  in = 'lfs3.c'

For marking tests/benches as internal without actually placing them in a
specific source file.

The internal flag and --no-internal have proven suprisingly useful for
running a subset of tests when refactoring, as internal tests break much
more frequently than the high-level API. However, placing all the
internal tests in lfs3.c _has_ put a big strain on compilation/link
times.

`internal = true` now lets you mark tests/benches as internal, without
the extra compile/link overhead. You don't get access to any internal
things, but the flag can still be useful for filtering.

---

The original motivation for this was in the test_fwrite_clip_* tests,
but they ended up using lfs3_bptr_size to check leaf sizes, so oh well.
At least it's a good flag to have around. (In theory these could be made
"fake internal" with a manual bitmask, but it doesn't seem worth the
potential maintenance headache for saving a bit of link time. Though
maybe in the future priorities will change.)

Also cleaned up the handling of None in test/bench config a bit. Now
None should be equivalent to missing config fields, at the cost of more
noise in the Python code. None vs missing always feels unusually clunky
in Python.
2026-03-09 22:52:02 -05:00
Christopher Haster 8a4d114934 scripts: Fixed CsvInt(CsvFloat(mt.inf)) bypassing int/float cast
Turns out mt.isinf is happy to accept non-primitive floats (such as
CsvFloat) as long as __float__ is defined. But CsvInt expects a float
inf, not a CsvFloat, so things explode later.

Fixed by explicitly casting to float if mt.isinf, instead of passing
as-is.

Also tweaked CsvInt/CsvFloat constructors to not bother checking
isinstance, unconditional int/float casts are probably cheaper than the
condition in Python.
2026-03-09 22:51:30 -05:00
Christopher Haster e16580e00c scripts: bench.py: Added bench_runtime to probe measurements
This mirrors test_runtime in test.py, which has been useful for finding
test cases that are slowing down our tests.

Though note bench.py's output is per-probe, so summing bench_runtime
would be longer than the total runtime of the bench if multiple probes
are involved. Probes can be nested, so I'm not sure this is avoidable. I
guess it's the worst-case runtime if all probes were run independently?

Also note, confusingly, bench_runtime is cumulative while bench_simtime
remains per-sample. Maybe this will help prevent interchanging the two?
2026-02-19 14:04:39 -06:00
Christopher Haster 5dc88e3e00 scripts: csv.py: Added delta expr
This is the inverse of accumulate, returning the difference between
subsequent results. In theory accumulate(delta(x)) and
delta(accumulate(x)) are noops.

This is particularly useful for normalizing our bench n value in
scripts. It's the only value still returned as a cumulative measurement,
which is a bit inconsistent, but necessary for uniquely identifying
probe steps.
2026-02-19 14:04:25 -06:00
Christopher Haster 484b7dd1e8 scripts: csv.py: Ignore missing by fields in enumerate/accumulate
Note this matches the behavior of mods, e.g. I would expect this to not
break if ORDER is missing:

  ./scripts/csv.py \
      -bcase='%(case)s+%(probe)s+%(ORDER)s' \
      -ft=accumulate(bench_simtime, case, probe, ORDER)

Normally the expr compiler would force typechecking of ORDER, giving it
a default value of int(0) if missing, but we intentionally bypass
typechecking in enumerate/accumulate's by fields since they may be
strings.
2026-02-19 14:04:10 -06:00
Christopher Haster 8a35b9870b scripts: Tweaked table renderer to not hide conflicting results
I think this is currently only possible with overlapping by/field
fields, but hiding results with conflicting by fields is not ideal.
Especially since this function is central to so many scripts:

  cat test.csv
  a,b,c
  x,2,1
  x,1,2
  x,1,3

Before:

  ./scripts/csv.py test.csv -ba -bb -fb -fc
  warning: by fields are unstable
  a,b            b        c
  x,2            2        1
  TOTAL          4        6

After:

  ./scripts/csv.py test.csv -ba -bb -fb -fc
  a,b            b        c
  x,2            2        5
  x,2            2        1
  TOTAL          4        6

This solves the main issue with unstable by fields, so no more warning.

Note that some features rely on by being unique to work (added/removed
numbers, compare fields, etc). They shouldn't error, but may be
incorrect/unintuitive with conflicting by fields, so avoiding
conflicting by fields is still a good idea.
2026-02-19 14:01:35 -06:00
Christopher Haster a3082437df scripts: Relaxed lost results due to unstable by fields to a warning
So it turns out this _can_ happen, without an in-script coding error.

Consider the behavior of a script with overlapping by/field fields:

  $ cat test.csv
  a,b
  x,2
  x,1
  x,1
  $ ./scripts/csv.py test.csv -ba -bb -fb

During the first fold, rows 2 and 3 will contain b=1, but during the
second fold they will have been merged, resulting in b=2.

So, relaxing to a warning for now. Maybe the table renderer should be
rewritten to avoid folding? (note diffing results may be tricky)
2026-02-19 13:59:32 -06:00
Christopher Haster 4405ad47e4 runners: Reworked test/bench for out-of-tree extensions
The main changes:

- Added TEST_DEFINES and BENCH_DEFINES to allow overriding the default
  test/bench define header:

    -DTEST_DEFINES=my_test_defines.h

  Note these are VERY different from LFS_DEFINES upstream. They aren't a
  typical header file, and are included multiple times with various
  query macros.

  It's hacky, but works surprisingly well.

  Or maybe I'll just do anything to avoid having to write multiline
  macros. Ugh, backslashes.

- Moved more logic into bench/test_defines.h, including everything
  needed to integrate other filesystems out-of-tree.

  This mostly meant moving all of the cfg initialization logic into its
  own query macro (replacing the BENCH/TEST_CFG field macros).

But this also includes a bunch of small tweaks encountered while trying
to get external benchmarks running again.

The external benchmarks include several other filesystems (littlefs2,
SPIFFS, Yaffs2), and I'm hoping this injectable/queryable header thing
will do a good job at avoiding a maintenance headache. (At least a
better job than forking bench_runner.c, which was the previous
solution.)
2026-02-19 13:42:49 -06:00
Christopher Haster 85b7a48df7 scripts: csv.py: Added bounded examples to -l/--list-fields
Now -l/--list-fields includes however many results fit in 36 chars:

  $ ./scripts/csv.py --list-fields test.csv
  i              int    # 16,17,14,18,19,15,20,13,12,29,27,28,...
  suite          ?      # bench_p26_wt
  case           ?      # bench_p26_wt_linear,bench_p26_wt_ran...
  NO_FRUNCATE    int    # 0
  SIZE           int    # 2097152
  SEED           int    # 42

The whole point of -l/--list-fields is to give a quick information dump
about what's inside a csv file, and we're already parsing everything to
try to figure out types, so why not?

Much easier to read than head:

  $ head -n5 test.csv
  i,suite,case,NO_FRUNCATE,SIZE,SEED,BLOCK_SIZE,FILE_SIZE,SIM_...
  16,bench_p26_wt,bench_p26_wt_linear,0,2097152,42,65536,64,36...
  16,bench_p26_wt,bench_p26_wt_linear,0,2097152,42,65536,64,36...
  16,bench_p26_wt,bench_p26_wt_linear,0,2097152,42,65536,64,36...
  16,bench_p26_wt,bench_p26_wt_linear,0,2097152,42,65536,64,36...
2026-02-19 13:35:21 -06:00
Christopher Haster efde754f88 scripts: csv.py: Optional by fields for unique enumerates/accumulates
This extends csv.py's enumerate/accumulate exprs with optional by field
arguments. Each set of by fields gets its own state, allowing multiple
parallel enumerates/accumulates to be processed simultaneously.

This is especially useful when the number of by field sets is unknown.
In theory you could split/merge each by field set with a separate csv.py
call, but it'd be a real pain.

Consider some bench results:

  case,n,simtime
  bench_rbyd,1,100
  bench_rbyd,2,10
  bench_rbyd,3,100
  bench_btree,1,200
  bench_rbyd,4,10
  bench_btree,2,20
  bench_btree,3,2000
  bench_btree,4,200

It was a bit awkward to handle these with csv.py's accumulate, as
accumulate operated strictly per-row, ignoring the case field.

But now with optional by fields:

  $ ./scripts/csv.py test.csv \
        -bcase -bn \
        -fsimtime='accumulate(simtime, case)'
  case,n           simtime
  bench_btree,1        200
  bench_btree,2        220
  bench_btree,3       2220
  bench_btree,4       2420
  bench_rbyd,1         100
  bench_rbyd,2         110
  bench_rbyd,3         210
  bench_rbyd,4         220
  TOTAL               5700

Note that these by fields are a bit special in csv.py's grammar. So far,
they are the only fields in field exprs that aren't typechecked. The
alternative would be string types in csv.py, but I'm not sure I want to
go that far.

---

It's tempting to try to invert this logic (accumulate(simtime, n)), but
I'm not sure how it would work internally. The duplicate by fields
("case") do get annoying, but specifying them in the expr helps make the
relevant state explicit.

Keep in mind we don't evaluate the actual by fields until much later in
csv.py. Entangling these stages risks confusion (-ba='%(b)s'
-c='enumerate(n)'? hidden by fields? overlapping by+field fields?).
2026-02-19 13:07:08 -06:00
Christopher Haster cf7e0e3fef scripts: csv.py: Tweaked foldchecking to check that folds match
I mean, what would you expect this to do?

  max(a) + sum(b)

Whatever your answer is, it's wrong (the way csv.py works, we always
compute folds after expr evaluation). The best option is to error,
matching the behavior of mismatched types.
2026-02-19 13:07:01 -06:00
Christopher Haster 9a224a1c52 scripts: csv.py: Fixed incorrect fold type when type changes
csv.py's -L/--list-computed was returning some confusing types:

  $ ./scripts/csv.py /dev/null -fa='float(1)' -L
          a  int  sum
              ^-- huh!?

Turns out csv.py's fold typechecking was all broken. Folds can change
the type, but only at the invocation:

  $ ./scripts/csv.py /dev/null -fa='sum(float(1))' -L
          a  int  sum
  $ ./scripts/csv.py /dev/null -fa='avg(int(1))' -L
          a  float  avg
  $ ./scripts/csv.py /dev/null -fa='int(avg(1))' -L
          a  float  avg

This is maybe defensible for explicit folds, since their evaluation is
also lifted, but not so much for things like literals/fields/etc.

---

Fixed by allowing None to indicate a generic fold, and allowing types to
be lazily figured out in csv.compile.
2026-02-19 13:00:35 -06:00
Christopher Haster d37785cc9b scripts: test/bench.py: Sped up simple suite/case filters
By "simple" I mean any non-globbing suite/case ids.

Non-globbing suite/case ids can be filtered early in the test_runner.
But globbing ids require, surprise, globbing, which is currently handled
by test/bench.py.

---

This greatly speeds up valgrind testing of specific suites/cases,
otherwise things get bogged down during the initial --list-cases due to
the sheer number of test permutations we've accumulated.

Maybe we shouldn't be running the initial --list-cases under Valgrind,
but oh well. This mostly solves the problem without too many changes.
2026-02-19 12:39:01 -06:00
Christopher Haster 23ac67bf34 Prefer power-loss -> powerloss
Just trying to be a bit more consistent.
2026-02-13 13:56:20 -06:00
Christopher Haster f07ed90a63 runners: bench: Renamed bench m -> probe
This needed a different name, and "bench probe" is sort of reminiscent
of the "debug probes" you can use to measure things in the real world.

Maybe this is just my embedded engineering background poking through,
but honestly anything is better than a single char m, especially for a
non-integer field.
2026-02-13 13:45:01 -06:00
Christopher Haster fe93d62523 scripts: csv.py: Added -l and -L shortform flags
These seem useful enough to have shortform flags:

- -l/--list-fields - Input fields before processing
- -L/--list-computed - Computed fields and expr dependencies

Note while -L/--list-computed has more information, it's also more
likely to trigger an assert/error due to poorly implemented field exprs.
2026-02-13 13:45:01 -06:00
Christopher Haster 6093fa79ac scripts: csv.py: Tweaked --list-computed to infer all input field types
On one hand, only inferring the used input fields is conceptually
correct because that's how csv.py works. On the other, it doesn't really
make sense for --list-computed to show _less_ information than
--list-fields.

So, showing all inferred types now:

  $ ./scripts/csv.py --list-computed test.csv \
        -bcase='%(case)s+%(m)s' \
        -fsimtime='float(bench_simtime)/1.0e9' \
        -fsimthroughput='float(n)/max(float(bench_simtime)/1.0e9,1.0e-9)'
  i              int   .-->  case           ?    ?
  suite          ?     |.->  simtime        int  sum
  case           ?    -+|.>  simthroughput  int  sum
  SKIP_WARMUP    int   |||
  FILE_SIZE      int   |||
  SEED           int   |||
  ...
  m              ?    -'||
  n              int  ---+
  bench_reads    int    ||
  bench_progs    int    ||
  bench_erases   int    ||
  bench_readed   int    ||
  bench_progged  int    ||
  bench_erased   int    ||
  bench_simtime  int  ---'

I think this makes --list-computed a strict superset of --list-fields
now.
2026-02-13 13:45:01 -06:00
Christopher Haster 60dec6b77d scripts: csv.py: Tweaked expr-less -F to still typecheck
I was expecting -ba -Fa to sort numerically, but it was not. Turns out
hidden field fields (-F/--hidden-field) without exprs were never
typechecked.

This is not an issue for non-hidden field fields (-f/--field), because
we typecheck these explicitly in compile.
2026-02-13 13:45:01 -06:00
Christopher Haster 49e3b22907 scripts: csv.py: Fixed bottleneck from overlapping by/from fields
Found from some confusing behavior when by/from fields overlap. It turns
out when this happens (-bhi -Fhi, for example), the generated getattr
for the by field would trigger the __getattribute__ for the overlapping
field field, resulting in a fold on _every add operation_.

Hopefully you can see where this is a bit of a problem when summing a
large number of results (O(n^2)?).

---

Fixed by switching getattr to object.__getattribute__ and reconsidering
csv.py's entire design.
2026-02-13 13:45:01 -06:00
Christopher Haster 04b536eb79 runners: bench: Dropped cumulative results
Now that we have csv.py's accumulate(), this information is strictly
redundant!

  $ ./scripts/csv.py test.csv \
        -bspecific_permutation_here \
        -fbench_creaded='accumulate(bench_readed)'

The point of adding accumulate() was to drop these. We really shouldn't
be doubling the size of the csvs with redundant/derivable data.
2026-02-13 13:45:01 -06:00
Christopher Haster 68de9efd17 scripts: csv.py: Added --list-computed to expose expr deps/types/etc
Less useful than --list-fields, but fun.

This shows more of the internal expr eval info: input fields + types,
output fields + types + folds, and a small dependency graph showing what
goes where:

  $ ./scripts/csv.py --list-computed test.csv \
        -bcase='%(case)s+%(m)s' \
        -fsimtime='float(bench_simtime)/1.0e9' \
        -fsimthroughput='float(n)/max(float(bench_simtime)/1.0e9,1.0e-9)'
  i              ?     .-->  case           ?    ?
  suite          ?     |.->  simtime        int  sum
  case           ?    -+|.>  simthroughput  int  sum
  SKIP_WARMUP    ?     |||
  FILE_SIZE      ?     |||
  SEED           ?     |||
  ...
  m              ?    -'||
  n              int  ---+
  bench_reads    ?      ||
  bench_progs    ?      ||
  bench_erases   ?      ||
  bench_readed   ?      ||
  bench_progged  ?      ||
  bench_erased   ?      ||
  bench_simtime  int  ---'

Maybe I was just itching to write another ascii-art renderer.
2026-02-13 13:00:22 -06:00
Christopher Haster 187f35df61 scripts: csv.py: Added --list-fields for quick field access
One issue I keep running into with csv.py is that it's difficult to get
started with a new/unfamiliar csv file.

csv.py itself doesn't know what to do until you start specifying fields,
but you can't start specifying fields until you know what fields there
are. Add to this the fact that our csv files have so much info shoved in
them that their "human readability" is mostly theoretical.

The --list-fields flag provides a quick solution to this:

  $ ./scripts/csv.py --list-fields test.csv
  i              int
  suite          ?
  case           ?
  SKIP_WARMUP    int
  FILE_SIZE      int
  SEED           int
  ...

csv.py doesn't have much info at this stage, but we can at least include
the best-effort type guessing we use for field exprs.
2026-02-13 12:41:02 -06:00
Christopher Haster 6c458b321c scripts: csv.py: Simplified -i/--enumerate to alias -bi -Fi=enumerate()
Now that we have the enumerate expr, -i/--enumerate can be implemented
entirely during expr eval:

- -i/--enumerate        => -bi -Fi=enumerate()
- -I/--hidden-enumerate => -Bi -Fi=enumerate()

Instead of internally reimplementing the same behavior.

This is what our help text implies, so might as well put our money where
our mouth is. And the less special internals we have, the better.

I considered removing -i/-I completely, but it's quite a convenient flag
when debugging csv.py expressions.
2026-02-10 17:33:01 -06:00
Christopher Haster ac338e66f0 scripts: csv.py: Added explicit z field, reusing -Z/--children
In an effort to move away from magic usage of -i/--enumerate, this adds
an explicit z field for differentiating -r/--hot results (and for normal
recursive results).

Instead of trying to think of a new flag to control this, this just
piggybacks on -Z/--children, which now accepts a tuple:

- ./scripts/csv.py -z3 -Z
- ./scripts/csv.py -z3 -Zchildren
- ./scripts/csv.py -z3 -Zz,children

The only tricky bit was needing to insert z in front of the by fields,
otherwise it was mostly a simplification from the enumerate mess.

Another positive side-effect: -r/--hot (and -z/--depth) now implies
-Zz,children, removing the annoying/confusing behavior of hotify folding
results by default.
2026-02-10 17:33:01 -06:00
Christopher Haster 078a1fb4c6 scripts: Adopted explicit underscore in Result._prefix
For consistency with the --prefix flag.

I confused myself while debugging some script behavior, and that's
no good.
2026-02-10 17:32:55 -06:00
Christopher Haster 98279a0b36 scripts: csv.py: Simplified --prefix, moved to collect_csv
The current... attempt at an approach was broken and becoming horribly
unmaintainable. Two issues found without even looking:

1. Field inference didn't understand prefixes, leading to duplicate
   by/field fields when attempting to infer by fields with --prefix.

2. Sort wasn't working for some reason, probably because they behavior
   of sort, defines, etc are really weird since they apply to both by
   fields and field fields.

I considered just dropping support for --prefix completely, this really
isn't worth the time, but instead found a simple solution of moving
prefix handling to one of the first steps in collect_csv.

This has the downside of creating conflicts when a prefixed/non-prefixed
field has the same name, but I don't care. --prefix is a niche flag that
shouldn't mess with the rest of the code like this, and none of the
other scripts really handle field conflicts correctly anyways.
2026-02-10 17:14:49 -06:00
Christopher Haster 695b1e94df scripts: csv.py: Fixed issues with non-default children/notes fields
- Fixed the initial filter using explicit 'children'/'notes' literals

  Whoops, how did this happen?

- Fixed fold using default children/notes result attributes

  This one is a bit more excusable, self.children is easy to overlook.
  But not actual string literals, that's silly.
2026-02-10 17:13:13 -06:00
Christopher Haster 84b2e73a30 scripts: csv.py: Added enumerate/accumulate exprs
This adds two new exprs to csv.py, useful for sequential data:

  enumerate()    A number incremented each result
  accumulate(a)  A running sum across results

To make these work required adding support for cross-row state, thus the
new state field in CsvExpr.Expr.eval.

Once you have that cross-row state, implementing enumerate/accumulate is
pretty straightforward. The only complication being that we need to hash
state by the unique Python id (`id(self)`), otherwise multiple exprs
would share state, which would be pretty weird.

Note that csv.py's pipeline is now quite complex, and stage order is
important!

  input --> define    --> expr --> folding --> sorting --> output
            filtering     eval

As a result, it's unfortunately not possible to organize enumerate/
accumulate by by fields. I poked around with the idea but decided it was
too complex (aren't I supposed be building a filesystem?). The guiding
principle behind csv.py is most problems can be solved with more process
substitution.

---

This is a bit clunky since we can't use the existing fold system, but
csv.py is already a pile of hacks, so what's one more?

The reason for the clunkiness is that the original idea behind csv.py
was to treat each folded row independently and order-agnostic. Not the
greatest idea in hindsight, cross-row operations are useful!
2026-02-10 16:52:58 -06:00
Christopher Haster 3978a32156 scripts: csv.py: Started adding -g/--accumulate
The idea here is to add some sort of accumulate operation to csv.py, so
we can stop cumulative-result clunkiness. It would also be immensely
useful as a general function, and -i/--enumerate already sets a
precedent for this sort of cross-row behavior.

But I'm starting to think using flags here is not the best way, maybe
this would be better as a field expr?
2026-02-10 16:52:11 -06:00
Christopher Haster 45f1850028 scripts: csv.py: Fixed missing -F/--hidden-field parsing
For some reason -F/--hidden-field fields weren't being parsed as a
CsvExpr, breaking any attempt to use exprs with hidden fields. Probably
just broken during a refactor.

Fortunately an easy fix.
2026-02-10 16:40:15 -06:00
Christopher Haster cfafd07414 make: Leaned into simtime in Makefile
The value of simtime isn't actually the simtime value, but the
simulated throughput, which is easy enough for our csv.py script to
calculate (with a daintily placed max to avoid divide-by-zero).

Throughput has the benefit of being somewhat size-agnostic, making
cross-benchmark comparisons easier.

I guess it's technically possible to do something similar with
readed/progged/erased numbers, but conceptually that would be really
confusing...

---

Also renamed test/bench_time -> test/bench_runtime to hopefully prevent
confusion between the two time spaces.
2026-02-10 16:27:07 -06:00
Christopher Haster d3dd927de3 runners: emubd/kiwibd: Adopted emulated simtime API
This is based on some work in external benchmarks. What's worked well
there is emulating a global simtime based on per-byte estimates.

This moves the emulated simtime into emubd/kiwibd, and extends the idea
with both per-byte and per-op timing estimates for hopefully more
realistic results.

---

The problem is how NAND flash reads work.

Per-byte timing estimates are surprisingly accurate for NOR flash. There
is some overhead for sending the address, but it's mostly dominated by
bus cost (~20ns/B [1]).

NAND flash, on the otherhand, technically does support byte-level reads,
but first needs to read into 2KiB buffer. Surprisingly, these are pretty
close in cost (~19ns/B bus [2] vs ~12ns/B buffer [2]).

This close-ness makes modeling NAND flash difficult. If we set
read_size=1, we risk hiding the cost of small reads, which littlefs3 is
full of (rbyd lookups). If we set read_size=2048, we unfairly penalize
littlefs3 for the same reason.

---

The solution here is to expose both per-byte and per-op timing
estimates. This lets you model NAND reads using two data points:

  ^
  |                                realtime --> ...............o
  |                                             :    .....'''' :
  |                              ...............:''''  ^       :
  |                              :....'''''            |       :
  |               ..........::::::                  simtime    :
  |          .....:''''                                        :
  |o....:::::.....:                                            :
  |:                                                           :
  |:                                                           :
  +:-----------------------------------------------------------:>
   min read                                              max read

Where:

  bus_timing = 19ns
  buffer_timing = 25us
  buffer_size = 2KiB
  erase_size = 128KiB

  min_read = buffer_timing
  max_read = (erase_size/buffer_size)*buffer_timing - buffer_timing
  read_timing = min_read
  readed_timing = ((max_read - min_read)/erase_size) + bus_timing

  simtime = reads*read_timing + readed*readed_timing
            (per-op)            (per-byte)

This should correctly penalize small reads without complicating
emubd/kiwibd too much.

That's the idea anyways! It will take some use to understand if this is
a reasonable approach.

As a plus, this is a superset of the per-byte model, so both can be used
for realistic vs idealistic simulations (and to test the bus+buffer
model itself).

1: https://www.winbond.com/resource-files/W25Q256JV%20SPI%20RevQ%2002072025%20Plus.pdf
2: https://www.winbond.com/resource-files/W25N01GV%20Rev%20R%20070323.pdf
2026-02-10 15:28:32 -06:00
Christopher Haster 35c09db971 scripts: test.py/bench.py: Some small tweaks
- Delayed defines/permutations assignment until after generation. Just a
  bit of code smell.

- Expanded all __eq__, __ne__, __lt__, __gt__, etc magic methods, just
  to minimize surprises in the future.
2026-01-09 00:03:48 -06:00
Christopher Haster 0c6e455961 scripts: test.py/bench.py: Allowed expressions in ifdefs/ifndefs
This extends our ifdef/ifndef test attributes to support more
complicated logic expressions.

So far we haven't really needed this (ifdef/ifndef accepts an implicitly
anded list, which has covered everything so far), but I realized there's
a simple trick to make this work.

For example, in test.toml:

  ifdef = 'A && !(B || C)'

Generated ifdef:

  #if (defined(A) && !(defined(B) || defined(C)))

This doesn't require complex parsing or anything, just a simple regex:

  s/[a-zA-Z_0-9]\+/defined(&)/g

Is using #if defined(A) everywhere instead of #ifdef A more expensive
for the compiler? Not sure. But it seems like we're heavily dominated by
the single-threaded link time, so I'm not sure we care.
2026-01-09 00:03:45 -06:00
Christopher Haster 5511c100ed scripts: dbgflags.py: Added -d/--diff, lineno, better find reuse
This started with adding -d/--diff support to dbgflags.py, which is very
useful for comparing flags during test failure.

The flag asserts in our tests generally look like this:

  tests/test_mount.toml:171:assert: assert failed with 33570064,
  expected eq 33570576
      assert(fsinfo.flags == (

Which can now be quickly compared with dbgflags.py:

  $ ./scripts/dbgflags.py +i 33570064 -d 33570576
   LFS3_I_GBMAP         0x02000000  Global on-disk block-map in use
   LFS3_I_REVPERTURB    0x00000010  Mounted with LFS3_M_REVPERTURB
   LFS3_I_MKCONSISTENT  0x00000100  Filesystem needs mkconsistent to write
  -LFS3_I_LOOKAHEAD     0x00000200  Lookahead buffer is not full
   LFS3_I_PREERASE      0x00000400  Blocks can be pre-erased
   LFS3_I_COMPACT       0x00000800  Filesystem may have uncompacted metadata
   LFS3_I_CKMETA        0x00001000  Metadata checksums not checked recently
   LFS3_I_CKDATA        0x00002000  Data checksums not checked recently

The assert print is a bit more annoying than it needs to be, as it only
prints in decimal. But, since our prettyasserts.py only works at the
syntax layer, it's not possible to make it any smarter.

---

To make this diffing work required a couple more features in our
self-parsing Flag class:

- Keep track of lineno, mainly for ordering things
- Moved find logic into a staticmethod on all classes
- Added _sentinel based defaults to find functions
- Allowed self to be non-class in line functions to deduplicate "Unknown
  flag" messages

I went ahead and extended these to the other self-parsing classes (Err
and Tag) in case they're useful in the future.
2026-01-09 00:03:33 -06:00
Christopher Haster b3ab83d5b5 Added REVPERTURB, reworked how we handle revision counts
The main change is adding LFS3_M_REVPERTURB, which will be necessary for
preerase allocations, but I got distracted and ended up giving the
revision count subsystem a bit of a refactor.

Main changes:

- Added LFS3_M_REVPERTURB, which ensures the leading bit in the
  revision count changes after each allocation/relocation/compaction.

  This is generally optional, but will be required for preerase
  allocations. Our ecksum system is only reliable if we ensure at least
  one bit changes, otherwise the chance of ecksum collision is very
  high.

  The downside of LFS3_M_REVPERTURB is that we need to read the contents
  of the new block to figure out what the bit should change to. Probably
  a minimal cost in the system, but still a good reason to make the
  behavior optional.

  Does LFS3_M_REVPERTURB have any use outside of preerased allocation?
  I'm not sure. Maybe it has some niche use reducing the chance of bd
  ECC collisions?

- Dropped LFS3_M_REVDBG, but adding low-effort debug bits that are
  always enabled.

  Making LFS3_M_REVDBG conditional was probably overkill. The flag
  checks probably cost more than the actual debug bits when enabled.

  Instead, replaced with a simpler, low-effort debug bit system, where
  we only set the debug bits during mdir allocation/relocation. These
  bits shouldn't change during normal compaction, but we _don't_
  introduce debug bits if mounting a filesystem from a driver without
  these debug bits.

- Restricted recycle counter to at most 20-bits to make space for
  things. This ensures perturb/debug bits don't get overwritten (though
  we really only care about perturb bits).

  2^20 (~1M) recycles is probably enough for any device littlefs will
  run on, especially considering the recycle_count should probably be
  several orders of magnitude smaller than the device's expected erase
  cycles.

  Worst case this can always be increased in the future without
  backwards incompatible changes. The only hard requirement for revision
  counts is that the full 32-bits are comparable.

- Simplified lfs3_rev_inc and friends, and moved most of the
  disk-dependent revision count stuff down into lfs3_rbyd appendrev.

  This deduplicates the messy revision count handling in
  lfs3_btree_commit_.

  Though note the implicit lfs3_rbyd_appendrev now defaults to writing
  the btree debug bits ('b'). A bit of a hack, but works for littlefs.

Here's the resulting encoding:

  vvvv---- -------- -------- -ddddddd
  vvvvrrrr rrrrrr-- -------- -ddddddd
  vvvvrrrr rrrrrrnn nnnnnnnn pddddddd
  '-.''----.----''----.----' ^'--.--'
    '------|----------|------|---|---- 4-bit relocation revision
           '----------|------|---|---- recycle-bits recycle counter
                      '------|---|---- pseudorandom noise (if revnoise)
                             '---|---- perturb bit (if revperturb)
                                 '---- low-effort debug bits
                              11-1---  - h = mroot anchor
                              11-11-1  - m = mdir
                              11---1-  - b = btree node

Note we store revision counts as le32s, so the perturb bit should end up
as the leading bit in the first byte.

Costs a bit more code (mostly because the debug bits are now
unconditional, even if low-effort), but simplifies the codebase:

                        code          stack          ctx
  before:              35124           2136          660
  after:               35144 (+0.1%)   2136 (+0.0%)  660 (+0.0%)
  after+yesrevperturb: 35192 (+0.2%)   2136 (+0.0%)  660 (+0.0%)

                        code          stack          ctx
  gbmap+np before:     38252           2144          776
  gbmap+np after:      38272 (+0.1%)   2144 (+0.0%)  776 (+0.0%)
  gbmap+np after+yrp:  38328 (+0.2%)   2144 (+0.0%)  776 (+0.0%)

                        code          stack          ctx
  gbmap+yp before:     38832           2168          796
  gbmap+yp after:      38852 (+0.1%)   2168 (+0.0%)  796 (+0.0%)
  gbmap+yp after+yrp:  38908 (+0.2%)   2168 (+0.0%)  796 (+0.0%)
2026-01-09 00:02:05 -06:00
Christopher Haster 843412cc79 preerase: Implemented the gc side of preerase
Allocating pre-erased blocks gets quite complicated due to our
restricted flash model, but at least the actual pre-erasing is
relatively straightforward:

- We keep track of known preerased state in lfs3->gbmap.preeraser.

- If LFS3_GC_PREERASE is provided during gc work, we increment the
  preeraser's known window by scanning the gbmap.

- Any BMFREE ranges we find, we erase a block at a time, and store the
  resulting ecksum in a BMERASED range in the gbmap.

- We keep track of how many blocks we erased, and stop early if this
  exceeds cfg.gc_preerase_count. This just lets users tune how many
  blocks to preerase in case something (?) prevents preerased blocks
  from being used.

Some notes:

- We don't really do anything with ranges in lfs3_alloc_preerase. In
  theory we could bulk in erase to minimize the number of commits to the
  gbmap, but we expect erase to dominate, so this probably isn't worth
  it.

  And if erase doesn't dominate, why would you bother pre-erasing
  blocks?

- Preerasing isn't really a traversal operation, and is managed by a
  sort of secondary state machine in lfs3_fs_gc_.

  This also means lfs3_trv_read with LFS3_T_PREERASE does nothing, but I
  guess that is ok? It's tempting to try to make lfs3_trv_read also
  preerase, but it's unclear what block it should return -- it's
  probably the wrong API.

- Introducing ecksums actually went quite a bit smoother than I
  expected. Though it helps ecksums are the only optional payload, no
  type punning or anything.

  Ecksums do muddy the gbmap's design a bit, unfortunately. The main
  issue being that we can only merge BMERASED ranges with equal ecksums.
  This makes BMERASED ranges less compressable than the others, and may
  be one reason to limit cfg.gc_preerase_count.

  However:

  1. This is where I think it's useful to emphasize that the gbmap's
     responsibility is to track _free_ blocks, in-use blocks are
     secondary.

     When allocating, we're going to stop at the first BMFREE/BMERASED,
     but may need to skip over an unbounded number of BMINUSE/BMBAD
     blocks. So the compressability of BMFREE/BMERASED ranges should
     have less of an impact on block allocation.

  2. In practice, most flash uses consistent erase values, so the
     resulting ecksums will probably be compressable. The exceptions are
     noop-erases (SD/eMMC, RAM, NVRAM, etc), and encryption with block
     address permutation?

     Though noop-erases are a pretty big exception.

Code changes:

                    code          stack          ctx
  before:          35116           2136          660
  after:           35116 (+0.0%)   2136 (+0.0%)  660 (+0.0%)

                    code          stack          ctx
  gbmap+np before: 38040           2136          776
  gbmap+np after:  38188 (+0.4%)   2144 (+0.4%)  776 (+0.0%)

                    code          stack          ctx
  gbmap+yp before: 38040           2136          776
  gbmap+yp after:  38608 (+1.5%)   2144 (+0.4%)  796 (+2.6%)
2026-01-09 00:01:42 -06:00
Christopher Haster 4f22d8c591 scripts: dbgflags.py: Added support for flag aliases
Also tweaked related flag comments a bit.

---

This adds another internal flag modifier ('a') to dbgflags.py to
indicate a flag is an alias for multiple other flags.

These still show up in -l/--list and name searches:

  $ ./scripts/dbgflags.py -l +ck
  LFS3_CK_MKCONSISTENT  0x00000100  Make the filesystem consistent
  LFS3_CK_LOOKAHEAD     0x00000200  Repopulate lookahead buffer
  LFS3_CK_COMPACT       0x00000800  Compact metadata logs
  LFS3_CK_CKMETA        0x00001000  Check metadata checksums
  LFS3_CK_CKDATA        0x00002000  Check metadata + data checksums
  LFS3_CK_CK            0x00003000  Alias for all check work
  LFS3_CK_GC            0x00003b00  Alias for all gc work

But are hidden from value searches, as they would be redundant and the
specific low-level flags are probably more useful:

  $ ./scripts/dbgflags.py +ck 0x00003000
  LFS3_CK_CKMETA  0x00001000  Check metadata checksums
  LFS3_CK_CKDATA  0x00002000  Check metadata + data checksums
2026-01-09 00:01:29 -06:00
Christopher Haster d54fef8099 Reorganized traversal flags again
One nice thing about merging LOOKAHEAD + LOOKGBMAP, is now our core
traversal flags fit in a single byte. This is useful for organizing
things, especially so as the traversal flags seem to permeate into
basically every flag set.

The main change was to actually group these flags into a byte, which
helps readability and in theory could make some bulk accesses cheaper
(in practice I don't think we currently leverage this):

  T_MODE             0x00000001  ---- ---- ---- ---- ---- ---- ---- ---1
  T_RDONLY           0x00000000  ---- ---- ---- ---- ---- ---- ---- ----
  T_RDWR             0x00000001  ---- ---- ---- ---- ---- ---- ---- ---1
  T_MTREEONLY        0x00000002  ---- ---- ---- ---- ---- ---- ---- --1-
  T_EXCL             0x00000008  ---- ---- ---- ---- ---- ---- ---- 1---
  T_MKCONSISTENT     0x00000100  ---- ---- ---- ---- ---- ---1 ---- ----
  T_LOOKAHEAD        0x00000200  ---- ---- ---- ---- ---- --1- ---- ----
  T_PREERASE*        0x00000400  ---- ---- ---- ---- ---- -1-- ---- ----
  T_COMPACT          0x00000800  ---- ---- ---- ---- ---- 1--- ---- ----
  T_CKMETA           0x00001000  ---- ---- ---- ---- ---1 ---- ---- ----
  T_CKDATA           0x00002000  ---- ---- ---- ---- --1- ---- ---- ----
  T_REPAIRMETA*      0x00004000  ---- ---- ---- ---- -1-- ---- ---- ----
  T_REPAIRDATA*      0x00008000  ---- ---- ---- ---- 1--- ---- ---- ----

  t_EVICT*           0x00000010  ---- ---- ---- ---- ---- ---- ---1 ----
  t_TYPE             0xf0000000  1111 ---- ---- ---- ---- ---- ---- ----
  t_ZOMBIE           0x08000000  ---- 1--- ---- ---- ---- ---- ---- ----
  t_CKPOINTED        0x04000000  ---- -1-- ---- ---- ---- ---- ---- ----
  t_DIRTY            0x02000000  ---- --1- ---- ---- ---- ---- ---- ----
  t_STALE            0x01000000  ---- ---1 ---- ---- ---- ---- ---- ----
  t_BTYPE            0x00ff0000  ---- ---- 1111 1111 ---- ---- ---- ----

  * Planned

This gives btype a full byte as well, which is a bit overkill, but can
be reduced in the future if we run into traversal flag pressure.

This also pushes some future planned flags (DEDUP, COMPR, etc) into
higher-order bits, but that's not the end of the world.

Code changes basically nothing:

                 code          stack          ctx
  before:       35152           2136          660
  after:        35152 (+0.0%)   2136 (+0.0%)  660 (+0.0%)

                 code          stack          ctx
  gbmap before: 38080           2136          776
  gbmap after:  38076 (-0.0%)   2136 (+0.0%)  776 (+0.0%)
2026-01-09 00:01:07 -06:00
Christopher Haster 7a57b1e2bd Renamed LFS3_T_COMPACTMETA -> LFS3_T_COMPACT (and gc_compact_thresh)
This effectively reverts 1f824a0:

- LFS3_T_COMPACTMETA -> LFS3_T_COMPACT
- gc_compactmeta_thresh -> gc_compact_thresh

And friends.

After using LFS3_T_COMPACTMETA for a bit, I think it just adds noise
without much value. Especially when next to LFS3_T_LOOKAHEAD,
LFS3_GC_PREERASE, LFS3_M_SYNC, etc.

It's interesting that we already have some very distinct verbs for this
sort of thing based on data type (compact => metadata, garbage-collect
=> disk, compress => data).
2026-01-09 00:01:05 -06:00
Christopher Haster 347c7b7290 scripts: gdb: Forward +flags to dbg scripts
dbgflags.py now uses +flags to indicate flag namespaces, but our gdb
script only forwarded -f/--flags, which made dbgflags a bit of a pain
to use in the debugger!

Fortunately an easy fix.

Now this works:

  (gdb) dbgflags +t trv.gc.t.h.flags
  LFS3_T_RDWR          0x00000000  Open traversal as read and write
  LFS3_T_MKCONSISTENT  0x00000100  Make the filesystem consistent
  LFS3_T_LOOKAHEAD     0x00000200  Repopulate lookahead buffer
  LFS3_t_TRAVERSAL     0x60000000  Type = traversal
  LFS3_t_MDIR          0x00010000  Btype = mdir
2026-01-09 00:00:57 -06:00