PureYAML/Knowledge/parse-hotspots.md
Mihaela Mihaljevic e61ff0b971
Some checks failed
rules-freshness / rules (push) Failing after 12m24s
docs(knowledge): parse hotspots and candidate changes
2026-11-20 16:56:46 +01:00

42 KiB

Where the PureYAML parse spends its time, and the candidate changes

Written 2026-11-20 on wip/parse-analysis, from origin/main at 6ca71f4. Reading only: no build, no test and no timing was run for this note, so nothing here is MEASURED by it. The measured facts it starts from come from Knowledge/performance-research.md item 5 of PureTree (branch wip/perf-research) and are marked CARRIED. Every other claim is marked DOCUMENTED (read in the code, with file:line, paths relative to Sources/ of PureYAML unless a repository is named), REASONED (follows from what is documented, but no one has timed it) or UNVERIFIED (a guess that a probe must settle). No number in this note is invented: where a size or a time is missing, the probe of section 4 is what produces it.

0. The question, the constraint, the carried facts

The question: where do the 1.5 to 1.7 s of the parse go, on the 13.5 MB openapi/github-api.github.com.json, and which change is worth making first.

The constraint: PureYAML is a Pure library. Foundation and the stdlib only; SIMD of the stdlib kind (SIMD16, SIMD32, SIMD64 of UInt8) is allowed, Accelerate is not; no Apple framework in any import form (Rules/universal/no-apple-frameworks-in-pure.md).

CARRIED (MEASURED by the PureTree note, release, TV Mac mini M4, load 4 to 7, in process): Outline.parse 529 ms and Highlight.tokens 314 ms at 13.5 MB (about 25 MB/s for the tokens); the parse inside Engine.diagnose is 1.5 to 1.7 s per the brief; Array(text.unicodeScalars) costs 28 ms and +51.5 MB resident (13,502,359 scalars at 4 bytes); a plain SIMD newline count took 72 ms against 40 ms for the scalar loop (the compiler vectorizes the scalar loop). The last fact sets the rule of this note: no SIMD claim without a stage profile that names a byte-class scan as the hotspot.

Two facts about the carried numbers that the reading shows (DOCUMENTED below), and that a reader of them should not skip:

  1. The two parse numbers are not the same work. Outline.parse of a JSON file goes through PureYAML.JSON.parseLocated (PureYAMLJSON/JSON.Parse.swift:17-20), which first rebuilds the whole text as a masked copy (JSON.Source.swift:14-49), then calls PureYAML.parseLocated, and Outline.parse then builds its own node tree from the result (PureTree: Sources/PureTreeModel/PureTree.Outline.swift:17-31, 80-104). Engine.diagnose goes through Bonsai (Bonsai: Sources/Bonsai/Diagnostics/Bonsai.Diagnostics.Engine.swift:47-49, 61, 68-70), which calls PureYAML.parseStreamLocated(Bonsai.JSONC.normalized(source)), never the JSON entry, and then projects the located tree to a plain value tree (located.map { $0.value }). So "the parse" is three different stretches of code at three call sites.
  2. 529 ms for the first and 1.5 to 1.7 s for the second, on the same engine and the same file, is a factor the code does not explain by itself (the second does less masking and more projection; section 2.8). It may be load, or a stage the first does not have. UNVERIFIED, and the first job of the probe.

1. The pipeline from text to tree, stage by stage

The entry points: PureYAML.parse, parseLocated, parseStream, parseStreamLocated (API.swift:3-21) all end in Parsing.Parser (Parsing/Parser.swift:6-19), whose four methods are the same five steps with a different composer mode (Parsing/Parser.Events.swift:46-90). The steps:

# Stage Where Input to output What it allocates, DOCUMENTED
1 Reader Parsing/LibYAML.Reader.swift:36-40 String to [Unicode.Scalar] Array(string.unicodeScalars): 4 bytes per scalar, one buffer for the whole file. CARRIED: +51.5 MB for 13.5 MB. Then one more full pass: recordFirstInvalidControlCharacter (:151-159) calls CharacterClass.isPrintable on every scalar until the first bad one (none, in a good file)
2 Scanner Parsing/LibYAML.Scanner.Fetch.swift:10-53, LibYAML.Scanner*.swift scalars to [Token] scanAll() runs fetchNextToken until STREAM-END and returns indentEngine.tokens (:10-15). Tokens are never dequeued (IndentEngine.swift:76-79, comment at Fetch.swift:7-9), so the whole token stream is alive at once. A Token is two Marks (three Int each, Mark.swift:3-5) plus a TokenType (Token.swift:5-9) whose scalar case carries a String and a ScalarStyle and whose tagDirective case carries two Strings (TokenType.swift:21-27); the enum is therefore at least as wide as its widest payload. The exact stride is UNVERIFIED (the probe prints MemoryLayout<Token>.stride)
3 Parser Parsing/LibYAML.Parser.swift:20-36 [Token] to [Event] init scans everything first (:20-23); parse() appends one Event per state-machine step into an array (:30-36). peekToken() returns a Token by value (:41-43), so each peek copies a token and retains its string payload if it is a heap string; parseNode peeks several times per node (LibYAML.Parser.Node.swift:9, 24, 52). states and marks are stacks (LibYAML.Parser.swift:12-13), cheap. An Event scalar carries a String, two String? and two Marks (Event.swift:11)
4 Mark conversion Parsing/Parser.Events.swift:7, Event.swift:44-70 [Event] to a second [Event] .map { $0.bumpingMark() } rebuilds every event with marks moved from 0-based to 1-based. A second array of the same length, while the first is still alive, so the peak holds both
5 Nesting check Parsing/Parser.Events.swift:12, 29-44 read pass over the events none, one more sweep (depth limit 64, :22-24)
6 Composer Parsing/EventStreamComposer.swift:31-54, driven by Parser.Events.swift:46-55, 68-78 [Event] to Value (and LocatedValue when tracksLocations) see 1.1
7 Located projection, only in a caller Bonsai Engine.swift:68-70, Model/LocatedValue.swift:31-40 LocatedValue to Value a second full tree: .sequence(items.map(\.value)) and Mapping(pairs.map(\.pair)) per node

The Streaming API (Streaming/Streaming.Scanner.swift) shares stage 1 and 2 through Reader.append and markFinal (LibYAML.Reader.swift:63-74); any new reader has to keep that interface (section 5, oracle O3).

1.1 What the composer builds per node (DOCUMENTED, Parsing/EventStreamComposer.swift)

For every scalar event (:127-151): composeScalarValue (see 1.2); a chargeExpansion call; one EventStreamComposedNode (EventStreamComposedNode.swift:2-9) holding the Value, a ComposedMappingKey (a Key, the scalar's String again, the normalized tag, the style), the Mark, an empty sequenceItems array and, when locations are tracked, a LocatedValue?. scalarParser.normalizedTag(tag) is called per scalar for the key (:145) and again inside composeScalarValue (ScalarComposition.swift:15, 34); for nil it returns at once (TagNormalizer.swift, the guard let tag). The key part is needed only for the scalar that is a mapping key, yet it is built for every scalar, including the values.

LocatedValue is declared indirect enum (Model/LocatedValue.swift:11). An indirect enum boxes the payload of every case, so each located node, leaves included, is one heap block (.scalar(Value, SourceRange) holds a Value plus four Int). REASONED: one allocation and one release per node, on top of the arrays, for a tree of millions of nodes. The indirect is not needed for the recursion, because the recursive cases already hold arrays ([LocatedValue], [LocatedPair]). The number of nodes of the test file is UNVERIFIED (the probe counts them).

For a sequence (:183-208): container.values.map(\.value) copies the children's values into a new array; the located tree is built from container.locatedValues (a parallel array that the composer appended with locatedNode(node) per child, :257-259); the completed node keeps sequenceItems: container.values, so the whole children nodes (value, key, located) stay referenced by the parent until it is dropped. For a mapping (:210-298): localPairs and localLocatedPairs grow in step, one Pair and one LocatedPair per entry, and pendingKeyNode retains the key node. Key(value:) is called for every completed container (:198, 235) although only a container used as a mapping key needs it; for a collection it is a cheap wrap (Model/Key.swift:8-25).

1.2 What happens to each scalar's text (DOCUMENTED)

Scanner, quoted scalars (LibYAML.Scanner.FlowScalar.swift:26-85): a loop that, per Unicode scalar, does reader.peek() (bounds check, the isFinal branch, Reader.swift:45-54), CharacterClass.isBlankZ (a space test, a tab test, a five-case break switch, a nil test, CharacterClass.swift:24-49), several comparisons against the quote and the backslash, then state.string.unicodeScalars.append(character) and reader.skip() (index += 1; column += 1, :86-92). Whitespace between words goes through a second loop that appends the blank to state.whitespaces and flushes it to state.string by foldFlow (:157-175, 184-204). The result is moved into a .scalar(value:style:) token (:54-58).

Scanner, plain scalars (LibYAML.Scanner.PlainScalar.swift:225-244): the same per-scalar shape, plus foldPending(&state) (a guard on two fields) and state.endMark = reader.mark (builds a Mark per scalar) for every content scalar. The phase machine around it (:126-196) exists for the streaming API and costs a switch per run, not per scalar.

Between tokens: scanToNextToken (LibYAML.Scanner.SkipToToken.swift:10-53) calls blankLineAhead() (:88-94, a peek loop) on every loop turn, then the dispatch (Fetch.swift:57-127) tests the leading scalar against a series of cases. staleSimpleKeys (LibYAML.Scanner.swift:63-88) runs once per token and walks every open flow level's SimpleKey (a struct of two flags, an Int, a Mark and two flags, copied out at :65), so its cost per token is the flow depth. saveSimpleKey and removeSimpleKey (:93-121) write that struct per scalar. Each : inserts a KEY token into the middle of the token array (Fetch.swift:350, IndentEngine.swift:83-86); the insert point is one or two slots from the end, so the move is short.

Composer, per plain scalar (ScalarComposition.swift:12-24, Parsing/Parsing.PlainScalar.swift:9-97, Parsing/Text.swift:2-16): trim walks Characters with isWhitespace (grapheme iteration) and builds a new String; resolve runs a string switch for null, bool (a switch of eighteen literals), integer (which runs removingNumericSeparators, a String.filter that visits Characters and builds a new String, then a literal array radixPrefixes of seven tuples, then hasPrefix calls), and for a non-integer, contains("."), contains("e"), contains("E") and Double(removingNumericSeparators(...)), a second filter. A quoted scalar skips all of it: composeScalarValue returns .string(value) for .doubleQuoted and .singleQuoted (ScalarComposition.swift:19-25). An integer too long for Int becomes a string, not a double (integer returns nil, the text has no ., e or E, so resolve ends in .string(text), Parsing.PlainScalar.swift:19-25): a quirk the oracle must keep.

Position tracking: per scalar the reader increments index and column (cheap); per token it builds Marks; per node the composer converts Mark to SourcePosition (line, column) in range(...) (EventStreamComposer.Located.swift:2-8). Mark.index counts SCALARS, not bytes: its one reader is the 1024-scalar limit of a simple key (LibYAML.Scanner.swift:74), plus the control-character check (Fetch.swift:38). Columns count scalars as well (Reader.swift:90-91). A UTF-8 reader has to keep both counts in scalars.

2. Where the 1.5 to 1.7 s most likely go

Honest frame: no stage was timed, so this is a ranking of suspects with the reason for each, not a split of the time. The shares are unknown until the probe of section 4 runs.

  1. REASONED, likely large: allocation and reference-count traffic in the composer and the model. Per node, in located mode: a located box (the indirect enum), a composed node with a key struct, array appends in two parallel arrays, a Pair plus a LocatedPair per mapping entry, and container.values.map(\.value) per sequence. These are heap and refcount operations proportional to the node count, with the strings shared by copy-on-write (so no byte copy, but a retain each time a string is copied into a node, a key, an event, a token). Reason for ranking first: it is the only stage whose cost per input unit is a heap allocation rather than a branchy loop over a cache-resident table, and the tree is millions of nodes at this size (count UNVERIFIED). The tree is also torn down by recursive release when the caller drops it, a cost that sits in the same wall time (REASONED).
  2. REASONED, likely large: three full-size, wide arrays alive at once (tokens, events, bumped events; stages 2, 3, 4), each grown by append (doubling, with a copy at every growth) and each touched freshly (first-touch page faults on memory the process has never held). Wide because the structs carry Marks of three Int (Mark.swift:3-5) and strings. The peak is the sum, which also explains the memory that the PureTree note did not measure (CARRIED section 7, point 7). The access pattern is sequential, so it is bandwidth and fault cost, not latency. The stride of Token and Event is UNVERIFIED (the probe prints them).
  3. REASONED, a real share but probably smaller: the per-scalar scanner loops over [Unicode.Scalar] in the quoted and plain scalar scanners, which for a file of long strings (a GitHub API description file is mostly strings, UNVERIFIED: the probe counts tokens by style) do about ten comparisons per scalar plus an append that encodes the scalar into UTF-8. Note the contrast with the carried SIMD result: a loop of one comparison per byte is already at memory speed (40 ms for 13.5 MB), so what costs here is not the touching of the bytes but the work stacked on each scalar (the multi-class test, the append, the position update). That is a statement about code shape, not a measurement.
  4. REASONED, small to moderate: plain-scalar resolution for the plain scalars of a JSON file (numbers, true, false, null): two String.filter passes, a literal array, trim by Character, per number; a string switch per word. Small per scalar, so it matters in proportion to how many plain scalars the file has (UNVERIFIED; for a GitHub API file most scalars are quoted, which skip it).
  5. REASONED, small: staleSimpleKeys and the simple-key writes per token, proportional to flow depth.
  6. REASONED, small and bounded: the reader (the 28 ms Array(unicodeScalars) is CARRIED; the validity pass of recordFirstInvalidControlCharacter is one more linear pass, a branchy range test per scalar).
  7. REASONED, small: the nesting pass and the mark conversion (stages 4 and 5) in time; in memory they are the peak (item 2).
  8. UNVERIFIED, may explain the gap between 529 ms and 1.5 to 1.7 s: the diagnose path has the located-to-value projection (stage 7, a second tree, allocated and then released), the JSONC pass (Bonsai.JSONC.normalized makes Array(text.unicodeScalars) of the file and scans it, Bonsai.JSONC.swift:15-27, 35-73; it returns the text itself when no comment is found), stream mode instead of single-document mode, and the teardown of the located tree. The Outline.parse path has the masking pass (JSON.Source.swift:14-49: one scalar loop with an append per scalar into a new String.UnicodeScalarView, plus a copy into String; isHeldBack builds an array literal per scalar in a string, :54-56, which the optimizer may or may not remove: UNVERIFIED), then Outline's own tree. Which of these adds up to the difference is exactly what the stage probe separates.

Not suspects, DOCUMENTED: the plain-scalar fold state and the phase machine (per run, not per scalar); the merge-key machinery (mergedPairs returns at once without merge sources, :343-345); the alias budget (one subtraction per node, ExpansionBudget.swift:20-25); the nesting depth bound (64) means no deep recursion cost.

PureTree's own Highlight.tokens (314 ms, not PureYAML) is a separate case, worth one line here because it is on the same path and has the same shape: PureTree.Highlight.Lexer.init (PureTree: Sources/PureTreeModel/PureTree.Highlight.Lexer.swift:11-16) builds [Character] with text.map (grapheme breaking over the whole file; Character is 16 bytes, so the array is 16 times the file in bytes of element, REASONED from the stdlib layout) and [String.Index] (8 bytes each) before lexing. A UTF-8 byte lexer would remove both arrays and the grapheme pass. It is a PureTree change, not a PureYAML one; listed in section 3 as candidate P1.

3. Candidates, in order of expected value over risk

Order is by expected value divided by risk, then by size. Expected gains are RANGED only by their reason; none is a promised number. Every candidate starts with the probe of section 4 (C0).

C0. The stage probe (S, first, nothing else starts before it)

Described in section 4. It turns the ranking of section 2 into a split.

C1. Fewer allocations per node in the composer and the model (S to M, low risk, probably the largest gain)

  1. Drop indirect from LocatedValue (Model/LocatedValue.swift:11). Source-compatible for every caller (no case or label changes), so the public API shape holds; the enum becomes as wide as its widest payload (Value plus SourceRange, four Int), larger than a pointer, so array copies move more bytes: a trade that only the probe can judge. Gain: one allocation, one release and one pointer chase per node (REASONED). Risk: a binary-size or stack-frame effect in recursive functions (value, synthesized); measure.
  2. Build the ComposedMappingKey only for a node that is a pending key (completeMappingNode is the only reader of node.mappingKey, :266-298, and consumeAlias/complete build it for all). Make EventStreamComposedNode.mappingKey computed from value plus the two fields the scalar case saves, or optional and filled only when the parent container is a mapping with no pending key. Gain: a Key, one String copy and a tag normalization saved per non-key scalar (REASONED).
  3. Do not keep sequenceItems (the full child nodes) alive in the parent for every sequence, only for the merge-key path that needs marks (:312-337 reads node.sequenceItems[index].mark); keep an array of Mark only when the sequence is used as a merge value, or keep it always but as marks only (24 bytes per item instead of a whole node). Gain: peak memory and release work (REASONED).
  4. Remove the second tree walk where a caller wants both: not a PureYAML change; Bonsai may take the plain value from the plain composer path at the same cost, or PureYAML may offer a composer mode that emits both trees in one pass. UNVERIFIED which is cheaper; the probe gives the cost of the projection (stage 7).
  5. Plain-scalar resolution without allocation (S): classify the token text by its bytes with a small state machine for the plain decimal integer (-?[0-9]+ without a leading zero, which the code reads as octal, Parsing.PlainScalar.swift:60-77), the plain decimal float, and the five null and eighteen bool words; send everything else to the current resolve unchanged. Replace trim by a byte or unicodeScalars trim only if the oracle proves it equal for every Unicode whitespace the Character.isWhitespace accepts (it is grapheme-based, so a combining mark after a space changes the answer; keep the old path for any non-ASCII text). Gain proportional to the share of plain scalars (UNVERIFIED).

Parity oracle O1 (section 5) plus O5 (the resolver differential). Size S for items 1 and 2, M for 3 and 4, S for 5.

C2. Remove the passes between the parser and the composer (S, low risk)

  1. Have LibYAML.Parser emit 1-based marks directly (add one to line and column where it builds the event, LibYAML.Parser.*.swift), and delete .map { $0.bumpingMark() } (Parser.Events.swift:7). Same output, one array and one pass fewer; the peak memory falls by one event array (REASONED).
  2. Do the nesting check inside the event producer, recording the FIRST offending event and its position and throwing after parse() returns, which keeps today's error precedence: a scanner or parser error anywhere wins over a nesting error, and a nesting error wins over any composer error, because today the check runs on the whole array before composing (Parser.Events.swift:12, called before the loop at :51). An inline throw at the first deep event would change which error a malformed, deeply nested document reports; the deferred throw does not.
  3. Keep the events array (the composer reads it by iteration, and the error order above depends on it being complete). A pull composer that consumes events as they are made would drop the array, but changes the same error precedence; not proposed.

Oracle O1 (events equal, errors equal, including a case that has a nesting error and a later syntax error, and one that has a nesting error and an earlier composer error). Size S.

C3. A UTF-8 byte reader with a run fast path for quoted and plain scalars (L, the largest change, moderate risk)

Design, from the code:

  1. The reader holds the text's UTF-8 bytes (ContiguousArray<UInt8>(text.utf8), one copy of 1 byte per byte, or withUTF8 on a mutable copy to avoid even that), not [Unicode.Scalar]. DERIVED from CARRIED: the buffer is 13.5 MB against 51.5 MB. Input is a Swift String, so it is valid UTF-8 and the decoder never meets an invalid sequence (a byte reader fed from Data would need a validation stage; not needed here).
  2. peek(_ offset:) keeps its signature (Unicode.Scalar?, offset in SCALARS, including negative, SkipToToken.swift:74): decode forward or backward over scalar boundaries; an ASCII fast path when the byte is below 0x80. skip() advances one scalar by its encoded length and does index += 1, column += 1 in scalars; skipLine() keeps CR LF as one break and NEL, LS, PS as one break each (their encodings are two and three bytes). mark(atIndex:) and the control-character index stay in scalar units (a counter is kept, or derived when needed).
  3. The 1024 rule (Scanner.swift:74) and Mark.index stay in scalars; this is the parity trap of the whole candidate (section 6).
  4. The run fast path, which is where the speed comes from, not the byte reader alone. In scanFlowScalar, when the closing quote is found on the same line with no backslash (double-quoted) or no second quote (single-quoted), no line break, and no break scalar among the bytes, the token value equals the bytes between the quotes exactly (DOCUMENTED reading of FlowScalar.swift:36-59: blanks inside a line go through whitespaces and come back verbatim by foldFlow, trailing blanks before the closing quote are kept; only a break or an escape changes the text). Then: scan the bytes against a 256-entry class table (one lookup per byte, no SIMD), build the String once from the byte range, and set index and column by the scalar count of the run (equal to the byte count when every byte is below 0x80). Anything that does not qualify falls back to the current loop from the opening quote, so every unusual case keeps its present code. The plain scalar has the same shape for a run without #, : followed by a blank, flow indicator (in flow), blank or break. It must keep the end-mark and leadingBlanks side effects (PlainScalar.swift:209-221).
  5. The control-character check is unaffected as long as the reader keeps the first-bad-scalar index in scalars and fetchNextToken keeps comparing reader.index (Fetch.swift:38): a bad scalar inside a quoted string that the fast path consumed is reported at the next token, as today. Because the first-bad search (LibYAML.Reader.swift:151-159) is itself a pass, it moves to the table scan or stays as one pass over bytes (a byte below 0x20 other than tab, LF, CR, or 0x7F, is bad; the C1 range 0x80 to 0x9F is the two-byte sequence C2 80 to C2 9F, NEL C2 85 excepted; U+FFFE and U+FFFF are EF BF BE and EF BF BF; CharacterClass.isPrintable, :92-101, is the specification).
  6. SIMD, only here and only conditionally: after C0 names the run scan (the table loop of item 4) as at least the dominant share of the scanner, and only if a first SIMD version beats the table loop in the paired probe by more than the spread of the table loop across runs. The carried result (72 ms against 40 ms, a mask counted with replacing(with:where:) and wrappedSum) is the warning: a stop-byte search is a different operation (find the first lane where a mask is set, then stop), for which the stdlib offers SIMD*<UInt8> comparisons and .any; whether it beats a vectorized scalar loop at stop distances of a few dozen bytes (the length of a JSON string) is UNVERIFIED. Strings are short and the stops frequent (every quote, escape, blank), so a wide vector may pay its setup for little.

Expected gain, REASONED: the per-scalar loop work of section 2, item 3 becomes per-byte table work plus one string build per token, and the buffer shrinks 4 times (DERIVED). Not a promise on time: the share is what C0 measures. Risk: the scalar-unit bookkeeping (column, index, the 1024 rule, the control index) and the streaming append/ranDry contract (a chunk is a String, so a chunk boundary is a scalar boundary, but peek past the end must still set ranDry when !isFinal). Size L.

C4. Slimmer tokens and events (M, moderate risk, after C0)

Token and Event carry two or three marks of three Int, and TokenType carries up to two strings. A smaller form would store the scalar text once in a side table indexed by an Int32, store marks as line and column plus index in 32 bits, or hold the marks of a token as one start and the length. The cost is a limit on file size or an overflow path (a 32-bit index limits a file at 2^31 scalars, a behaviour change that has to be an explicit error and not a silent wrap), a larger change to code that pattern-matches on TokenType in every parser file, and the existing tests that compare tokens and events (Token and Event are Equatable). Gain, REASONED: less memory and bandwidth in stages 2 to 4, in proportion to the saved bytes. UNVERIFIED how it compares with C2 plus C3; do it only if C0 shows the three arrays as the dominant cost after C1 and C2.

C5. Lazy position tables (rejected for PureYAML, L)

Instead of tracking line and column per scalar and storing SourcePosition per node, store byte offsets and compute line and column from a line-start table on demand. Rejected here for two reasons that the code gives: (a) SourceRange and SourcePosition are public stored values (Model/SourceRange.swift, Model/SourcePosition.swift) filled for every node of a located tree, and PureTree reads the range of every node (Outline.swift:80-104), so the positions are not optional work, and a lazy form is an API change; (b) the per-scalar position update is two integer increments, which are not a suspect in section 2. The idea could still apply in a PureTree consumer that does not need every node's position; that is a separate analysis.

P1 to P3. On the same path, in other repositories (listed so they are not lost; each its own owner)

  1. P1, Highlight.Lexer (PureTree, PureTree.Highlight.Lexer.swift:11-16): [Character] and [String.Index] for the whole file; a UTF-8 lexer removes both. S to M; oracle: the tokens and ranges equal for every asset, with the ranges compared as offsets and with a text of combining marks and CRLF (the lexer maps CRLF to one character, :14, a parity trap of its own). Gain REASONED (a grapheme pass and two arrays removed); the 314 ms is CARRIED.
  2. P2, Outline.node(of:) (PureTree, Outline.swift:94-102): path + [index] allocates an array per node. Share a path by a parent pointer or build children with the parent's path reserved. S. REASONED.
  3. P3, JSON.Source masking (PureYAMLJSON/JSON.Source.swift:14-49): a scalar loop that rebuilds the whole text even when no held-back character exists. A first pass that only looks for a held-back scalar inside a string (no output) and returns the text unchanged when there is none (the common case, restoring already returns at once for an empty originals, :59, 69, 82) removes one text copy. S. Oracle: the masked text and the originals equal the present ones on every asset and on generated texts that hold each held-back character inside and outside strings. REASONED gain.

4. The measurement that must come first (C0, the stage probe)

A test file kept out of the repository history until it is judged (a probe, not a guard), in the Tests/ of PureYAML with @testable import PureYAML, release build on a test machine (swift test -c release -Xswiftc -enable-testing --filter StageProbe), never on the owner's Mac. It is described here and was not run.

Input: the text of openapi/github-api.github.com.json (path of the assets repository SlayerMotionHQ/PureTreeAssets), the 4.3 MB openapi/stripe-spec3.json if present at that size (UNVERIFIED which asset is 4.3 MB), the 255 KB and 118 KB assets, and one YAML asset (openapi/github-api.github.com.yaml) so a plain-scalar-heavy file is seen as well. The text is loaded once, outside every timed region.

For each input, N = 12 runs after 2 warm-ups, the median and the spread (maximum minus minimum) reported, ContinuousClock, the load of the machine (uptime, read by the human, printed in the header) stated; each stage's output is kept alive in a withExtendedLifetime and dropped outside the timed region unless the stage is the teardown.

Stages, each timed alone from the previous stage's retained output so that no stage includes another:

  1. Array(text.unicodeScalars) alone, and LibYAML.Reader(text) (adds the validity pass); the difference is the validity pass.
  2. Scanner(text).scanAll() (reader included; subtract stage 1 for the scan alone), with the token count, the count of scalar tokens by style, the total scalars in scalar tokens, and MemoryLayout<Token>.stride, MemoryLayout<Event>.stride, MemoryLayout<EventStreamComposedNode>.stride, MemoryLayout<LocatedValue>.stride.
  3. LibYAML.Parser(tokens:).parse() on the retained tokens (events), with the event count.
  4. The .map { $0.bumpingMark() } alone, then enforceNestingLimit alone (call it through the Parser extension, it is private: copy its 15 lines into the probe with a comment naming the source).
  5. The composer over the retained events, twice: tracksLocations: false and true, in .singleDocument and in .stream mode (Parser.Events.swift:46-90), counting the nodes it makes.
  6. The located-to-value projection: located.value over the tree of stage 5 (LocatedValue.swift:31-40).
  7. The teardown: the time to drop the located tree and the value tree (set the last reference to nil inside the timed region).
  8. The whole of PureYAML.parseStreamLocated(text) and of PureYAML.JSON.parseLocated(text), to check that the stages add up to the wholes (a gap of more than the spread is a stage the list missed).
  9. For the plain-scalar suspect: PlainScalar.resolve over every plain scalar text of the file (collected untimed), counting resolved kinds, to give the share of numbers.
  10. For the byte-scan suspect (only if stage 2 is large): the table loop and the SIMD stop-byte loop of C3 item 6 over the bytes of every quoted scalar of the file, paired in the same run, same machine, same load.

Printed per input: the table of stage, median, spread, share of stage 8's whole, plus resident size before and after each of stages 1 to 5 (the PureTree probe used mach_task_basic_info; that is an Apple call, so in PureYAML it sits in a #if canImport(Darwin) test-only helper outside the library target, as Rules/universal/no-apple-frameworks-in-pure.md allows for witness tests). Verdicts are written to Knowledge/measured/ of PureYAML as MEASURED with the machine, the load and the commit, and C1 to C4 are then ordered by the shares found, not by section 2.

Decision rule, derived from the probe's own spread and not from a guess: a candidate is kept if its paired gain (same machine, same hour, before and after in the same run order) exceeds the spread of the same stage across its 12 runs, and the whole-parse gain does too. A candidate that does not clear it is reported as not worth the code, with the numbers.

5. The parity oracles

The question, the domain, the authority and the failure report, as Rules/universal/oracle-first.md asks.

The authority is the present parser at origin/main 6ca71f4. Equivalence is exact: the same tokens, events, Value tree, LocatedValue tree with every position, and the same error (type, the context, problem and mark fields, and String(describing:) of a ParseError), with Double compared by bit pattern (so .nan equals itself and -0.0 is not 0.0). No tolerance.

The domain.

  1. All asset files of PureTreeAssets, found by walking the tree under SlayerMotionHQ/PureTreeAssets for .yml, .yaml, .json, .geojson (the brief says 74; assets.tsv lists 58 downloaded paths and tiny/ adds a further set, 87 tracked paths in all, so the count of 74 is UNVERIFIED: the oracle enumerates by walking and prints the count it found, and the harness fails when the count differs from the number the owner confirms). Both parseStreamLocated and, for .json, JSON.parseLocated.
  2. The repository's own corpora: Tests/Fixtures/yaml-test-suite (the cases of YAMLTestSuiteConformanceTests), real-yaml, acme, validation-failures, real-yaml-corpus.yaml.
  3. Generated inputs, from a seeded generator written in the test target (seed printed, so a failure replays): random YAML and JSON trees emitted by the repository's own PureYAML.dump and JSON.Writer, with strings built from a pool that includes every class boundary: ASCII, two-, three- and four-byte scalars, NEL, LS, PS, BOM at the start and in the middle, CR, CR LF, LF, tab, a combining mark after a space, U+007F, C1 controls, U+FFFE, U+FFFF, ', ", \, #, :, -, ?, and runs around the 1024-scalar limit of a simple key (1023, 1024, 1025 scalars of multi-byte text, which is where a byte count and a scalar count part).
  4. Malformed inputs: every asset truncated at each of 200 deterministic cut points (including inside a multi-byte scalar's string at the scalar level, since a String cannot be cut inside a scalar, only between), every broken-* asset, an unterminated quote at end of text, a control character before and after a syntax error, a nesting depth of 63, 64 and 65 with an earlier and with a later syntax error.
  5. Streaming: the chunked scanner on the same inputs, chunks of 1, 3, 17, 4096 scalars (StreamingScannerDifferentialTests is the existing harness; it must stay green and be extended with multi-byte chunks).

The harness has three tiers, because the old implementation will not stay beside the new one in one binary.

  1. A golden recorder, run once on the unchanged commit: for each input of the domain, a canonical text serialization of (tokens, events, value tree, located tree, error), written to Tests/Fixtures/parse-oracle/<name>.golden when the serialization is under 1 MB, and as a 64-bit FNV-1a digest of the serialization stream (an algorithm written in the test, not Hasher, which is seeded per process) when it is larger, with the byte length. The recorder is a test with an explicit flag and is never run by the normal suite.
  2. The checker, in the normal suite: recompute the serialization and compare with cmp semantics (byte equality) against the golden, or digest and length against the digest file. A mismatch prints the input name, the first differing token or event index and both renderings.
  3. Where the old code is small enough to keep, a second, live oracle: the present Reader stays in the test target as ScalarReaderOracle (copied, with a comment naming the commit) and a differential test drives random sequences of peek(k) (k from -2 to 5), skip, skipLine, append(chunk), markFinal on both readers and compares index, line, column, mark, isAtEnd, ranDry, invalidControlCharacterIndex and mark(atIndex:) after every step. This is the strongest check of C3, because the reader is where the unit change happens.

The negative controls, so a passing run means something: (a) a mutated reader that counts bytes for column instead of scalars must fail on the multi-byte generator; (b) a mutated 1024 rule on bytes must fail at the 1024-scalar boundary case; (c) a mutated fast path that drops a trailing blank before the closing quote must fail on the assets; (d) a mutated bumpingMark that adds one to the byte index must fail the event equality; (e) a mutated nesting check that throws at the first deep event must fail the error-precedence case. Each mutation is a test that applies the change in a copy and asserts the harness reports a difference; a harness that cannot see them is not an oracle.

Every case is handled or reported, never skipped: an input is equal, differs (a failure), unsupported (listed with its reason) or blocked (listed with its reason); the count of each is printed and unsupported and blocked must be zero for the assets.

Candidate by candidate:

Candidate Oracle Measurement that must come first Size
C0 stage probe none (it measures); its own check is that the stages add up to the whole within the spread itself S
C1.1 drop indirect the located tree equal (Equatable) and every .range equal on the domain; the golden checker stages 5 and 7 plus teardown (stage 7) S
C1.2 key built only for keys composer output equal on events of the domain and on the EventComposer-level tests (ParsingEventTests, LocatedValueConformanceTests) stage 5, compare composer time against a variant S
C1.3 sequence items as marks merge-key fixtures (MergeKeyCompatibilityTests) and a generated merge-key set with a non-mapping item (the error mark must be the item's mark) stage 5 M
C1.5 plain resolve an exhaustive differential resolve(new) == resolve(old) over every string of length up to 4 over a 20-character alphabet (digits, sign, ., e, E, _, x, o, b, letters of the bool and null words, space, tab, a non-ASCII letter), plus the owner-corpus plain scalars, plus 10 million random strings from the same pool with the seed printed; Double by bit pattern stage 9 S
C2.1 marks emitted 1-based events equal; the 1-based line and column of an error equal on the broken-* assets stages 4 and 3 S
C2.2 inline nesting check, deferred throw the error-precedence cases of domain item 4 (nesting before and after a syntax error, before and after a composer error) stage 4 S
C3 byte reader and run fast path all three tiers; plus the streaming differential at chunk sizes of domain item 5; plus the negative controls (a) to (c) stages 1, 2 and 10 (the share of the scan, then the paired scan variants) L
C4 slimmer tokens tokens and events equal after a decode back to the present form; a file-size limit test that fails loud, not wrapped stages 2 to 4 (strides and the share of the three arrays) M
P1 Highlight byte lexer tokens and ranges equal on every asset and on the generated set, CRLF and combining-mark cases included a stage timing of Highlight.tokens in PureTreeResponsivenessTimingTests split into [Character] building and lexing S to M
P2 Outline paths allNodes and node(at:) equal on every asset Outline.parse split into the located parse and the node build S
P3 JSON.Source first pass masked text and originals equal on every asset and on texts holding each held-back character in and outside strings stage 8 split: Source.init alone S

6. The traps, found by reading (each one a case for the oracle)

  1. Scalars, not bytes, are the unit everywhere that is visible. Mark.index, Mark.column, the 1024-scalar simple-key limit (Scanner.swift:74), the first-bad-scalar index and its mark(atIndex:) (Reader.swift:124-143), and the SourceRange columns of the located tree all count Unicode scalars; PureTree's own Outline.index(of:in:) counts Characters (Outline.swift:123-133), which differ for a combining mark or CR LF. A byte reader that counts bytes changes the public positions of every file with one non-ASCII character.
  2. CR LF is one break, and CR alone is a break (Reader.swift:105-115); NEL, LS and PS are breaks and are 2, 3 and 3 bytes. Source masks LS, PS and C1 controls for JSON (JSON.Source.swift:54-56), so the JSON path and the YAML path differ on them: both must be in the domain.
  3. A BOM at index 0 does not advance the column; elsewhere it does (Reader.swift:94-101, SkipToToken.swift:15-23).
  4. The control-character error fires at the next token, not at the character (Fetch.swift:26-45, comment included), and scanStep() does not route through that check (the comment says so): the streaming differential must pin the present behaviour, not the intended one.
  5. A 20-digit integer is a string (Parsing.PlainScalar.swift:19-25), 0123 is an octal 83, 0-3 is not minus three (:72-73), _ is stripped everywhere in a number (:95-97). Any fast number path falls back for a leading zero, a sign followed by a zero, an underscore, or an overflow.
  6. Error precedence: scanner error, then parser error, then nesting error, then composer error, today (Parser.Events.swift:5-14, 51); the nesting check on the whole array is what fixes the third place.
  7. tracksLocations changes only the located tree: the plain path must stay byte-identical (comment at EventStreamComposer.swift:5-6); a lean-node change must be checked in both modes.
  8. Public API: LocatedValue, LocatedPair, SourceRange, SourcePosition are public; dropping indirect is source compatible, changing a payload is not.

7. What was not seen

Everything that is not reading: no build, no test, no timing, no profile, on any machine; the real app; the size of Token, Event, EventStreamComposedNode and LocatedValue in bytes; the token, event and node counts of the test file; the share of quoted, plain, and numeric scalars in it; whether the optimizer removes the array literals in integer and isHeldBack; the cost of the teardown of the located tree; why the diagnose parse is slower than the outline parse; whether a SIMD stop-byte search beats the table loop at the lengths of JSON strings; the number of asset files (74 in the brief, 58 downloaded plus tiny/ in the manifest). The ranking of section 2 is a hypothesis list until the probe of section 4 is run.