Skip to content

perf: optimize the Mode B brace slicer itself — measured as pure slicing cost, NOT tiktoken (~20% of Optical_Detector) #3174

Closed

Description

@squid-protocol

Blocking-diagnostic issue, deliberately small. In the 2026-09-18 profiling, <lang>::Cartography_Mode_B_Braces is the single largest regex-telemetry key on both repos — 33.8s of vscode's 5,000-file sample (2.8× the #2 key) and ~9s on node's — but this number is known-misleading: the Mode B timing envelope wraps tiktoken tokenization work, not just the brace-slicing regex (this already burned one investigation; see the perf notes). Nobody should start an optimization from this key until it is split.

Task

Add sub-keys to the Mode B cartography path so the telemetry separates (a) the brace-slicing regex sweep, (b) tiktoken encode time, (c) everything else in the envelope — e.g. typescript::Cartography_Mode_B_Braces/regex, /tiktoken, /other. Then one profiled vscode run answers the question: is there a real regex target here, or is it tokenizer cost (which needs a completely different attack: caching, sampling, or skipping tiktoken where the census doesn't need it).

Efficient workflow (time/token/model)

  • This is a small-model / fleet-able task end to end: find the Mode B envelope in detector.py's splice cartography section, wrap the two inner operations with time.perf_counter() sub-accumulators into the existing regex_telemetry dict (same lang::key convention, so --splicing-speed renders them with zero renderer changes), run one vscode profile, paste the table here.
  • No corpus audits, no golden checks, no A/B needed — telemetry-only change, no behavioral surface.
  • One caution for the implementer: profile runs to date were Zero-Dependency Mode with tiktoken PRESENT (numpy/pyyaml absent) — keep that environment so numbers stay comparable to the 2026-09-18 baseline.
  • Budget: <1 hour wall, one ~60s vscode profile run. If the split shows regex ≥ half the 33.8s, file the follow-up optimization issue with that evidence; if it's tiktoken, the follow-up belongs to the tokenizer-cost family instead (cache by content hash? encode once per file instead of per segment?) — decide then, not now.

🤖 Generated with Claude Code

Activity

  1. squid-protocol commented on Sep 18, 2026

    @squid-protocol
    OwnerAuthor

    Answered empirically ahead of instrumentation, via an import shim that blocks tiktoken (HAS_TIKTOKEN=False end to end) on vscode:

    tiktoken ON tiktoken OFF
    typescript::Cartography_Mode_B_Braces (5,000-file sample) 33.8s 36.0s (= noise)
    wall, no profiling flags 52.0s 52.2s
    5_Optical_Detector cumulative 169.6s 172.3s (= noise)

    Conclusion: the "wraps tiktoken" caveat is outdated for current code — Mode B's cost is the brace-slicing work itself, and tiktoken's wall footprint is ~zero (its per-file/per-function get_token_mass CPU hides in parallel workers off the critical path). Also relevant: token_mass cannot be dropped casually anyway — log_density_token_mass is a trained dimension of the 38-D function-archetype vector pinned by feature_contract_sha.

    Retitling this issue to what it now is: optimize _slice_by_braces itself (~36s of vscode's sampled regex time, the single largest key — ~20% of the Optical_Detector phase). Attack surface to explore: what the slicer re-scans per function start (each of vscode's many func_start anchors triggers brace matching over the body; nested/overlapping rescans would be the classic quadratic-ish shape), whether the existing _seg_nl-style precomputation can be shared, and whether the per-candidate work can reuse the func_start match positions coding_analysis already computed instead of re-deriving them.

    🤖 Generated with Claude Code

  2. changed the title [-]perf: decompose Cartography_Mode_B_Braces telemetry (tiktoken vs regex) before anyone targets it[/-] [+]perf: optimize the Mode B brace slicer itself — measured as pure slicing cost, NOT tiktoken (~20% of Optical_Detector)[/+] on Sep 18, 2026
  3. squid-protocol commented on Sep 18, 2026

    @squid-protocol
    OwnerAuthor

    Two notes from the #3173 session that affect how this gets measured.

    1. The vscode baseline in this issue can't be reproduced as-is — the node/vscode source trees are no longer on the box (only prior scan outputs remain under v2.7.0_telemetry_rescan/). Re-baseline against present mega-repos (all_language_repo, curl, temporal-crucible-pool), or restore the checkouts first.

    2. Fresh top-regex profile (all_language_repo, 2867-file sample, zero-dep, post-#3072 engine) for context — the ordering is repo-specific, so don't scale the vscode number blindly:

    [ CUMULATIVE REGEX EXECUTION TIME ]
    2.648s  cobol::Cartography_Mode_A_Labels     <- #1 here (not Mode B)
    1.629s  cobol::func_start
    1.225s  typescript::Cartography_Mode_B_Braces
    0.496s  c::Cartography_Mode_B_Braces
    0.434s  dart::Cartography_Mode_B_Braces
    0.401s  cpp::Cartography_Mode_B_Braces
    

    Mode B braces is still a real lever (it sums across all brace languages), but on a mixed corpus Cartography_Mode_A_Labels (COBOL) is the hotter single key. Confirm Mode B's share on the target repo before committing to the ~20% figure.

    Tooling: measure this with the new tests/tools/phase_ab.py (#3178) —
    phase_ab.py --repo <r> --rounds 3 --control --phase Cartography_Mode_B --phase 5_Optical_Detector gives a per-key A/B with an A-vs-A noise floor. The earlier "Mode B is pure slicing, not tiktoken" finding still holds (verified via HAS_TIKTOKEN=False import-shim; wall unchanged without tiktoken).

  4. squid-protocol commented on Sep 18, 2026

    @squid-protocol
    OwnerAuthor

    Diagnostic done — and it overturns the premise. There is no regex/quadratic target in Mode B.

    In-process cProfile of the real cartography path (splice() over ~1091 C/C++/TS files: all of curl + the all_language_repo cpp/ts samples, zero-dep mode, post-#3072 engine). Attribution inside _slice_by_braces (= the Cartography_Mode_B_Braces key, ~22% of Optical_Detector, matching the ~20% here):

    component share of Mode B note
    per-match Python loop (_slice_by_braces tottime) ~52% language guards, name/args slicing, satellite build
    _calculate_block_metrics (per function) ~15% already O(log n) via the spatial_map bisect
    _build_brace_safe_stream (per file) ~17% the shielding regex pass
    _find_balanced_end / brace scan ~0.5% str.find = 0.024s; already C-fast

    So the brace-matching regex the issue expected to optimize is ~0.5%, and there's no quadratic re-scan — each func_start resolves its own body once via a bounded C-loop. The func_start finditer inside Mode B is also negligible (0.01s); its real cost lives in the coding_analysis rule key, not here.

    Reusing coding_analysis's func_start positions (the issue's idea) isn't sound as-is: Mode B matches against _build_brace_safe_stream(code) (blanks #define lines etc.), a different haystack than coding_analysis's, so positions/groups don't transfer.

    The one real, safe lever I found and shipped (branch perf/3174-mode-b-microopt, output-identical): guard the two per-match C/C++ operations that are no-ops on most signatures — the member-initializer-list char walk (":" in sig) and the #else/#elif finditer ("#" in sig) — plus computing block.count("\n") once. cProfile: _slice_by_braces tottime 0.370s → 0.329s (−11% of the per-match Python), full-curl audit.json/sarif.json byte-identical, 290 detector tests green. But end-to-end it's ~0.2% of Optical_Detector — below the wall-clock noise floor (the phase_ab A-vs-A control confirms: steady-state rounds show mine ≈ main).

    Recommendation: Mode B has no headline win — the cost is intrinsic to extracting + measuring every function, and it's already well-optimized in its hot children. The genuinely dominant lever in Optical_Detector is coding_analysis (the per-rule regex sweep: ~2× everything else in tottime), already worked by #3069/#3072. Suggest closing this as diagnosed, optionally taking the sub-noise cleanup above.

  5. squid-protocol commented on Sep 18, 2026

    @squid-protocol
    OwnerAuthor

    Closing as diagnosed. The core question — is there a real regex/quadratic target in Mode B — is answered no (brace scan ~0.5% of the key; cost is diffuse per-match Python + block metrics, already well-optimized in its hot children). The output-identical per-match cleanup is in #3179 (kept modest and honestly scoped; it helps most on core-constrained hosts where per-worker CPU sits closer to the wall). The genuinely dominant Optical_Detector lever is coding_analysis, already worked by #3069/#3072.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions