Skip to content

Patch faster on top of the patcher optimizations - #195

Merged
sarbian merged 4 commits into
masterfrom
perf/all-on-pr194
Nov 27, 2026
Merged

sarbian merged 4 commits into
masterfrom
perf/all-on-pr194

Conversation

@sarbian

@sarbian sarbian commented Nov 27, 2026

Copy link
Copy Markdown
Owner

Patch faster on top of the patcher optimizations

Builds on #194 (sparr's "Patcher optimizations"): this branch is #194's three commits plus 19 commits on top, one
per change
, so review from "Keep the type index valid around copy patches and lookups" on (or merge #194 first,
after which this PR shows only those). Each commit builds and passes the tests on its own, and its message says what
it changes and why; the table below gives what each one saved. It does not include #193, which merges cleanly next to
it.

The patched result does not change. On an RO/RP-1 install (102 mods, 83,979 patched nodes), every cache file
(ModuleManager.ConfigCache, .Physics, .TechTree) and the patch log are byte-identical to stock 4.2.3's and to
#194's, in every timed run. The one file that changes is ModuleManager.ConfigSHA, whose overall SHA is now computed
from the per-file hashes: existing caches are rebuilt once after updating.

Timings

KSP 1.12.5, RO/RP-1 install, Windows, Unity's development player, the cache rebuilt (only ModuleManager.ConfigCache
deleted, so hashing, the file check, NEEDS, patching and the cache write all run). "Ran in" is ModuleManager's own
total.

Build Ran in, cache rebuilt Ran in, cache loaded
stock 4.2.3 90.0 s (1 run) —
#194 30.6 s (mean of 2) 3.8 s
this branch 12.3 s (mean of 3) 1.7–2.3 s

That is 2.5x faster than #194 and 7.3x faster than stock when the cache is rebuilt, and about twice as fast
as #194 when it is loaded. Launch to the main menu with the cache rebuilt went from 87–92 s with #194 to about 73 s.
(Stock and #194 were timed in an earlier series on the same install; this branch's cache-loaded figure is one run each
of it and of two builds with the same loading code.)

Each commit was timed as its own build, stacked in this order, with the cache rebuilt (3 runs each for the last
nine, 2 for the others). What each one saved, from the "Ran in" means or, for the changes that target one phase, from
that phase:

# Commit Saved
1 Keep the type index valid around copy patches and lookups nothing (correctness)
2 Copy config nodes with less work 5.1 s
3 Match broad patches with less work within noise
4 Parse patch value and subnode names once 3.6 s
5 Find literal-name edit patches' nodes by name 2.1 s
6 Select subnodes for ,* and :HAS in one pass 0.7 s
7 Look up root nodes for variables through the type index 1.2 s
8 Hash config files on worker threads SHA 1.5 → 0.6 s
9 Check the cached files' hashes with a dictionary file check 0.37 → 0.02 s
10 Write the cache without a flush per node nothing measurable on Windows
11 Remember NEEDS answers while extracting patches extraction 1.6 → 0.6 s
12 Hash each config file once nothing measurable (reading the files is the cost)
13 Find copy and delete patches' nodes through the type index 0.7 s
14 Insert values without looking at the node's others 0.3 s
15 Compare literal :HAS types and names directly 0.7 s
16 Load the cache with less work cache load 0.56 → 0.43 s
17 Write the cache without copying every node first 0.35 → 0.06 s
18 Stop the patch log thread without waiting out its sleeps up to 0.15 s, within noise
19 Let edits share the subnodes they leave alone 3.6 s

Commit 10's writer is what commit 17 builds on. Commit 12 is kept because the hasher no longer holds the files' bytes;
nothing after it depends on it, so it can be dropped on its own.

What changes

Type index (on #194's)

  • Copy patches invalidate the whole index; patches that add or remove nodes invalidate it again after they run.
  • Edit, copy and delete patches with literal names visit only the nodes with those names, through a name index. If a
    special command writes a name value in place while a patch runs, the rest of that patch scans every node again.
  • Root lookups in values and pastes (#$@PART[foo]/bar$, #@PART[foo]/MODULE[x]) use the index.
  • An MM_PATCH_LOOP pass that renames its node updates the index after each pass.
  • Deletes drop their nodes from the index; copies invalidate only their type.

Applying patches

  • An edit copies its node's name and values and keeps the same subnodes, instead of copying the whole tree. A
    subnode is copied, in place, when the patch first edits (@) or replaces (%) it. Nothing else writes into an
    existing subnode except special commands (*@PART[foo]/bar = x): a patch with one, or with a paste (which can carry
    them), copies whole nodes as before. So does every edit of the run after a special command writes a {/} value or
    a rename writes a name with a space or parenthesis, both of which a whole copy would have cleaned. The replaced
    version is never read again. Copy patches, +SUB, pastes and inserts still build independent copies, so no two
    nodes in the database share a subnode.
  • DeepCopy builds the copy's name directly when ConfigNode(string) would not change it.
  • Wildcards: a glob when the string has no newline (the regex otherwise), literal patterns compared directly (x and
    x\n, as ^x$ matches), and parsed constraints that keep their nested ones.
  • ModifyNode caches the parse of value commands, subnode commands and the whitespace removal of subnode names.
  • ,* and :HAS subnode selection walk the subnodes once.
  • A value inserted without an index goes at the end without scanning the node's values.

Hashing, checking, NEEDS

  • Config files are hashed on worker threads, at most 64 files ahead of the caller, which combines the paths and the
    per-file hashes in order. A worker that dies marks its file as failed; if none is left the caller reads the files.
  • CheckFilesChange looks the FILE nodes up by filename.
  • NeedsChecker keeps the mod list as a set and each NEEDS expression's answer; a name not in the set is checked
    with the old linear search, so the answer is always the culture comparer's.

Cache and log

  • The cache is written from the patched nodes as their sanitized, escaped copies would be written (same bytes),
    through a buffered writer, without building those copies.
  • The cache load unescapes only values containing a backslash, and looks each file up once.
  • The patch log thread is woken to stop instead of being polled.

Differences from stock

  • ModuleManager.ConfigSHA: the overall SHA is different, so caches are rebuilt once.
  • In memory only, after a fresh patching run: subnodes a patch never touched keep their comments, which the old
    whole-node copies dropped. Nothing reads them, and the cache does not contain them.
  • An exception while matching a delete patch is logged once per node (stock's loop never moved on from that node).
  • A cache write that fails on a null name or value is logged and the cache deleted, instead of the exception leaving
    the patching thread. The cfg parser never produces either.

Tests

574 tests (477 at #194's head). The new ones run the new code against the old on the same inputs: the glob against
the regex (fixed cases and 20,000 random ones), subnode selection against the old index loop for start indexes −7
to 7, CheckFilesChange against the old algorithm, the cache writer against DeepCopy + escape + ConfigNode.Save
(including braces, = in names, tabs, newlines, names the constructor splits), copies, deletes and edits through the
index against each patch's plain Apply, and edits sharing subnodes against whole copies (over @ % ! + ,*, a
negative index, :HAS, loops, special commands, pastes, renames one and two levels down, and a patch that throws),
checking after every patch that the versions it replaced are unchanged.

sparr and others added 4 commits October 30, 2026 11:05
Matching each patch against every node spent most of its time
allocating, and the allocations stalled the patching thread in Boehm GC
waits. In a profiled RP-1/RO repatch, NodeMatcher.IsMatch was 55% of
the patching thread, WildcardMatch 36%, and GC waits 22%.

- WildcardMatch compares strings directly when the wildcard has no * or
  ?, keeping the regex's match before a final newline, and caches its
  regex by the wildcard instead of building the pattern on every call.
- CheckConstraints parses each constraint string once and caches it.
- CheckConstraints visits the matching subnodes in one pass instead of
  calling FindConfigNodeIn with each index in turn.
- FindConfigNodeIn no longer builds a list of the matching subnodes.
- KeyValueCache.FetchWithKey takes a delegate that need not capture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every edit patch tested every root node, and NodeMatcher.IsMatch
rejects most of them by type alone.

PatchApplier now keeps a PatchTypeIndex of the database's list nodes,
grouped by node type in list order, and gives it to edit patches, which
visit only the nodes of their matcher's type. Edits replace values in
place and cannot rename a root node, so they leave the index valid; it
is invalidated if a type changes anyway. Copy and delete patches mark
their matcher's type stale and insert patches their node type, and a
stale group is rebuilt when next needed. IPatch.Apply is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
NodeMatcher.IsMatch looked up a node's name value for every patch with
a name pattern, once per node of the patch's type. With the previous
two commits applied, in a profiled RP-1/RO repatch, that lookup was
about 15% of the patching thread.

ProtoUrlConfig already looked up the name value for FullUrl; it now
keeps the Value object and exposes its value as NameValue.
NodeMatcher.IsMatch(IProtoUrlConfig) matches against it, and edit,
copy, and delete patches call that through an INodeMatcher extension
that falls back to IsMatch(ConfigNode) for other matchers. A special
command (*@part[foo]/name = bar) writes to that Value object in place,
so its renames are seen. Edits and copies modify a copy and wrap it in
a new ProtoUrlConfig, so their renames are seen too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Builds on PR 194's type index. The patched output is unchanged: on an
RO/RP-1 install (83,979 patched nodes) every cache file and the patch log
are byte-identical to stock 4.2.3's, and only ModuleManager.ConfigSHA
differs (see the SHA below).

Index:
- Copy patches invalidate the whole index, and patches that add or remove
  nodes invalidate it again after they run.
- Edit, copy and delete patches with literal names find their nodes through
  a name index, falling back to a scan when a special command writes a name
  in place.
- Root lookups (#$@part[foo]/bar$, pasted @part[foo]) go through the index.
- An MM_PATCH_LOOP pass that renames its node updates the index after each
  pass.
- Deletes drop their nodes from the index, and copies invalidate only their
  type.

Applying patches:
- An edit copies its node's name and values but keeps the subnodes it leaves
  alone, instead of copying the whole node; a subnode is copied when the
  patch first edits or replaces it. Patches with a special command or a
  paste, and every edit after a special command writes a brace or a rename
  writes a name a copy would clean, still copy whole nodes.
- DeepCopy skips the ConfigNode(string) name cleanup when it has nothing to
  do.
- Wildcards without a newline are matched with a glob instead of a regex,
  literal patterns are compared directly, and parsed constraints keep their
  nested ones.
- ModifyNode caches the parse of each value and subnode command.
- ,* and :HAS subnode selection is done in one pass.
- Values inserted without an index no longer scan the node.

Loading, hashing, caching:
- Config files are hashed on worker threads, at most 64 files ahead, and
  the overall SHA is built from the per-file hashes. It differs from the old
  one for the same files, so existing caches are rebuilt once.
- CheckFilesChange indexes the FILE nodes by filename.
- NEEDS keeps the mod list as a set and each expression's answer; a miss is
  checked with the old search.
- The cache is written without copying every node first (same bytes), with
  a buffered writer, and loaded unescaping only values with a backslash.
- The patch log thread stops at once instead of polling.

Tests: 574, with new tests comparing the new code with the old on the same
inputs (glob against regex, subnode selection, CheckFilesChange, the cache
writer, indexed against plain patches, shared subnodes against whole
copies).
@sarbian
sarbian merged commit b1686e2 into master Nov 27, 2026
1 of 2 checks passed
@sarbian
sarbian deleted the perf/all-on-pr194 branch November 27, 2026 12:54
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.

2 participants