Skip to content

perf(cmd): build the command parser once per process - #333

Merged
bpauli merged 1 commit into
mainfrom
perf/cmd-tests-reuse-parser
Nov 4, 2026
Merged

bpauli merged 1 commit into
mainfrom
perf/cmd-tests-reuse-parser

Conversation

@bpauli

@bpauli bpauli commented Nov 4, 2026

Copy link
Copy Markdown
Owner

Summary

Every execute call checked the command table, attached the tree and ran kong.New over all of it. That build is almost the whole cost of a run that stops in Validate (12.5 ms of 12.5 ms without -race, 73 ms with it), and the internal/cmd tests run about 6000 such calls, so the four test shards of make test spent most of their time building the same parser.

execute now keeps one idle parser in a one-slot channel and reuses it. Each call sets the writers, the exit function and the version text of its run on the parser. A concurrent call that finds the slot empty builds its own parser, so the 40-goroutine isolation test still holds without a lock.

Kong's Parse zeroes every flag and positional of every command before it applies the args (kong v1.16.1 context.go Context.Reset, model.go Value.Reset), so the struct values of a run do not reach the next run. It does not clear three model fields that the next Parse reads: Value.Set (the required-flag check and the existingfile mapper), Value.Active and Node.Active (the existingfile mapper) and Flag.Negated (a --no-x flag flips the next --x). parserSet.reset clears them before each reuse. Without it, 1 golden case (wellness_menstrual-log_set@empty-day) and 2 of the new tests fail.

What changed

  • execute takes the parser from idleParser or builds one with newParserSet, and returns it to the slot after run.
  • versionFlag.BeforeReset reads the version through a bound *versionText, which each run sets.
  • TestExecuteRejectsBadTable swaps the table through swapCommands, which drops the idle parser.
  • New tests: TestExecuteResetsFlagsBetweenRuns (pointer, list and negatable flags of run 1 do not reach run 2 or 3), TestExecuteResetsParseChecksBetweenRuns (a required flag and an existingfile positional are checked again in run 2) and TestCommandStateIsResetByParse (lists every unexported or kong:"-" field of the tree, which Parse does not reset, against a known list).

Scope

  • Only the parser build is shared. The command structs are the same ones Kong resets on every Parse; unexported fields of a command keep their value across runs, and the known list in TestCommandStateIsResetByParse names the four that exist today, all set on every run in Validate.
  • The shard split in the Makefile stays as it is. See the timings below.
  • The missing reset of Set, Active and Negated is a Kong limitation for a reused parser. This PR works around it; an upstream fix is a separate matter.

Verification

Same machine (16 cores, load 2 to 4 from other sessions), 5 runs per side, throwaway benchmark of execute for activities list --limit x:

measure before after
execute, no race 12.4 to 12.7 ms/op 0.18 to 0.20 ms/op
execute, -race 66 to 82 ms/op 0.90 to 1.02 ms/op
shard golden-a-g, -race 322 s 64 s
shard golden-h-z, -race 356 s 69 s
shard write-account, -race 195 s 47 s
shard rest, -race 207 s 50 s
other packages, -race 30 s 34 s
all five in parallel (as make test -j) 356 s 69 s
make test on the branch, same setup - 57 s
  • go test ./internal/cmd -run TestGolden passes without -update; git status shows no golden change.
  • Injected defects: with p.reset() removed, TestExecuteResetsFlagsBetweenRuns and both cases of TestExecuteResetsParseChecksBetweenRuns fail. With kong's Context.Reset replaced by a no-op (module replace), TestExecuteResetsFlagsBetweenRuns fails on the leaked --flow, --symptoms and --no-ovulation values.
  • Gate: make fmt-check, make lint, go vet -tags e2e ./..., make test, make build && make conformance GCCLI_BIN=bin/gccli.

execute checked the command table, attached the tree and ran kong.New
on every call. That build is almost the whole cost of a run that stops
in Validate (12.5 ms without -race, 73 ms with it), and the internal/cmd
tests run about 6000 such calls.

execute now keeps one idle parser in a one-slot channel and reuses it.
Each call sets the writers, the exit function and the version text of
its run. A concurrent call that finds the slot empty builds its own
parser.

Kong's Parse zeroes every flag and positional before it applies the
args, but it keeps Value.Set, Active and Flag.Negated, which the
required-flag check, the existingfile mapper and the negatable bool
read in the next Parse. parserSet.reset clears them before each reuse.

make test with -race on 16 cores: 356 s before, 69 s after.
@bpauli

bpauli commented Nov 4, 2026

Copy link
Copy Markdown
Owner Author

Independent verification: PASS+NOTES

  • Head: 814059a
  • Base: 8a832a9
  • origin/main merged against: e51f9e2 (local merge, no conflicts, not pushed)

All runs used own worktrees, HOME and XDG_CONFIG_HOME in a temp dir, BROWSER=/bin/false, and no live Garmin calls.

Gate (head, and head merged into main)

  • make tools, make fmt-check, make lint (GOTOOLCHAIN=go1.26.0, 0 issues), go vet -tags e2e ./... and make test: pass on both.
  • go test ./internal/cmd -run TestGolden without -update: pass on both, git status clean.
  • TestCommandStateIsResetByParse passes on the merge, so profile power-zones set from feat: set FTP and power zones #329 adds no unexported command state.

Binary vs base on the HTTPS mock

  • tools/parity.sh: merge vs e51f9e2, 461 compared, 0 differences. Head vs 8a832a9, 460 compared, 0 differences (root and every group and leaf --help, 4 completion scripts, 12 bad inputs).
  • make conformance (MITM proxy mock, auth import token, file keyring) passes for the base, head, main and merge binaries. On the merge that is 5188 golden replays in 4 modes (848 skipped by the suite), so every replayed case gives the same stdout, stderr, exit code and requests as main.
  • Own sweep, 48 arg lines run through both binaries on the same mock, comparing stdout, stderr, exit code and request bodies: main vs merge 48/48 equal, base vs head 48/48 equal. The lines cover reads, writes, --json, --plain --header, GCCLI_JSON and GCCLI_PLAIN, --version, --help, usage errors, xor and and groups, a missing required flag, a missing existingfile, and profile power-zones set good and bad inputs (default and explicit floors, running without floors, bad floor count, floors that do not increase, --ftp 0, --ftp 2, --ftp abc, a bad sport, a missing sport, a missing --ftp).

Leak tests (throwaway, in-process, on the merge, not committed)

Each one runs execute many times in one process on the reused parser and compares each run with a fresh-parser run of the same args, or with the golden file.

  • Every ordered pair of golden cases of one leaf, A then B, with A in another output mode than B: 6742 pairs x 4 mode combinations, B always equals its golden. All 1509 goldens in shuffled order with a random mode, 3 seeds: all equal.
  • Hand sequences: pointer, list and negatable flags given and then left out (wellness menstrual-log set); power-zones set cycling --ftp 279 --floors ... then set running (still "missing flags: --ftp=WATTS"), then set cycling --ftp 280 (default floors 0, 154, 210, 252, 294, 336, 420, not the earlier floors), then set running --ftp 300 (still "give --floors with 5 values"); --help and --version then a normal run; a usage error then a run that prints JSON to stdout; global flags and env modes given then left out; required flag, and group, xor group, required positional and existingfile positional given then left out; completion scripts after a run with flags. All equal to fresh runs.
  • Fixture command through swapCommands with map, counter, negatable bool with a default, enum with a default, int default, pointer, slice, required flag, existingfile, xor, and, required and optional positionals and an env flag: 11 runs, all equal to fresh runs.
  • Panic path: a run that panics in Run (recovered by the test), then a normal run: equal to a fresh run.
  • Concurrency under -race: 24 goroutines x 60 mixed runs, x3, compared with fresh output: no race, no difference. TestExecuteRunsAreIsolated passes 3/3.

Injected defects (on the merge)

defect tests that fail
p.reset() removed TestExecuteResetsFlagsBetweenRuns, TestExecuteResetsParseChecksBetweenRuns, TestGolden (101 subtests, then a nil *c.FTP panic in power-zones set at profile.go:97, because the leaked Set passes the required --ftp check), TestExecute_GoalsListSendsStatus, TestWriteCommandOutput
Flag.Negated not cleared TestExecuteResetsFlagsBetweenRuns, TestGolden
Value.Set not cleared TestExecuteResetsParseChecksBetweenRuns, TestGolden (panic as above), 2 more
Value.Active not cleared none (see note 2)
Node.Active not cleared none (see note 1)
per-run Stdout/Stderr line removed, or set only when built TestExecuteResetsParseChecksBetweenRuns, TestGolden, 14 more
per-run Exit set only when built TestExecuteResetsParseChecksBetweenRuns, TestGroupHelp, TestExecute_Version, 2 more
per-run version set only when built TestExecute_Version
drain removed from swapCommands TestExecuteRejectsBadTable ("exit 0, want 1") in a package run. It passes when run alone, because then no earlier test has filled the slot.

My own pair and sequence tests also fail for the Negated and Set defects (36 and 44 failing pair subtests on 3 leaves).

Speed (same machine, 16 cores, load 2 to 6)

  • execute of activities list --limit x, 5 runs per side: no race, 12.7 to 13.0 ms/op on base and 0.13 to 0.14 ms/op on head. With -race, 64.9 to 66.8 ms/op on base and 0.67 to 0.75 ms/op on head. --version: 12.2 to 12.6 ms/op on base and 0.060 to 0.062 ms/op on head. Every op checks the exit code.
  • make test, 2 runs per side, alternated, cold test cache: base 349 s and 359 s, head 56 s and 58 s. The slowest shard is 340 to 352 s on base and 49 s on head.
  • CI test job: 2m13s and 3m11s on this head, against 10m31s to 11m10s for the last 4 main pushes.

Notes

  1. Node.Active is set by kong v1.16.1 in trace but never read. The existingfile, existingdir and filecontent mappers read Value.Active only. The description and the reset comment say Node.Active is read by the existingfile mapper. Clearing it is harmless, but no test can detect it, because no behavior depends on it.
  2. No test fails when Value.Active is not cleared. No command today has an optional existingfile value with a default. A throwaway fixture with that shape (arg:"" optional:"" type:"existingfile" default:"nofile.txt") shows the reset is needed: run 1 fix here.txt, then run 2 fix fails with [<file>]: stat $DIR/nofile.txt: no such file or directory without the reset, and prints an empty path with it. A small case like that would guard the field. This does not block the merge.
  3. On the merge, removing p.reset() fails 101 golden subtests, not 1 as the description says (that count was measured before feat: set FTP and power zones #329). It also panics in power-zones set. So the reset is required for the new command, and it works.
  4. The last main CI run (e51f9e2) has a red darwin-cgo-build: TestRefreshLockWaitMessage got empty stderr. That is on main without this PR. All checks on this head pass, darwin too.

@bpauli
bpauli merged commit 2bcd38d into main Nov 4, 2026
8 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant