Skip to content

Explicit Bench Optimization Analysis

Scope

This note summarizes a focused round of optimization work against the committed uv run poe bench workload for the explicit 10_000 resource synthesis path.

The goal was simple:

  • recover known regressions first
  • inspect the remaining hot path with profiling and bytecode
  • keep only changes that strictly improved the benchmark

Benchmark Methodology

Primary benchmark:

uv run poe bench

Comparison policy used during this effort:

  • compare one code change at a time
  • use repeated runs and compare medians rather than a single best run
  • discard any change that does not improve the benchmark total time
  • keep the worktree clean between experiments

Representative accepted baseline during the later bytecode-guided pass:

  • creation median: 0.2389s
  • synth median: 0.0960s
  • total median: 0.3349s

For committed historical records, detached worktrees were used so benchmark rows could be recorded against the exact commit with git_dirty=false.

Regressions Recovered

Two real regressions were identified and fixed before the later micro-optimization work.

1. Synth Regression

First bad commit:

  • d3960a2 Add hybrid vs Terraform regression scenarios

Cause:

  • normalize_hcl_attributes() was changed to recursively normalize every attribute value through _normalize_value().
  • That turned a narrow typed-meta serialization fix into a full deep walk across every resource config during synth.

Kept fix:

  • restrict normalization to the typed Terraform meta objects that actually need conversion:
  • LifecycleRules
  • Timeouts
  • ConnectionConfig
  • ProvisionerConfig lists and tuples

2. Creation Regression

First bad commit:

  • 69d0bb6 Add single-pass nested value analyzer

Cause:

  • _apply_config_bulk() started forcing the heavy nested analyzer path for every attribute during construction.
  • That moved dependency and runtime-analysis overhead into creation, including the common scalar and plain-container cases.

Kept fix:

  • add a cheap runtime precheck before the heavy analyzer
  • return None for the common no-runtime case instead of allocating a _ValueAnalysis
  • avoid unnecessary dependency-edge cleanup on brand-new resources

Recovered state after those fixes:

  • synth returned to roughly the previous floor
  • creation improved substantially, but still remained somewhat above the best historical lows

Bytecode And Profiling Findings

The later optimization pass inspected both cProfile output and adaptive CPython 3.14 bytecode.

Creation Hot Path

Primary remaining functions:

Main conclusion:

  • CPython is already specializing the obvious dict and attribute access well.
  • The cost is mostly the number of Python-level calls and branches per attribute, not missed local-variable hoists.

Examples from the adaptive disassembly:

  • _apply_config_bulk() already specializes to opcodes such as LOAD_ATTR_SLOT, LOAD_ATTR_METHOD_NO_DICT, CALL_METHOD_DESCRIPTOR_FAST, and STORE_SUBSCR_DICT
  • _value_may_need_runtime_processing_impl() still has a large branch and call surface:
  • about 234 instructions
  • about 15 call opcodes
  • about 20 conditional branches

Measured scan cost on the current benchmark-shaped sample:

  • _value_may_need_runtime_processing_impl(): about 1.65 µs per call

That matters because the explicit 10k creation profile still hits that helper tens of thousands of times.

Synth Hot Path

Primary remaining functions:

Main conclusion:

  • synth is no longer dominated by deep recursive normalization, but normalize_hcl_attributes() still performs enough branching and conversion checks on every key that small source-level fast paths looked attractive in isolation
  • in the full harness, those micro-optimizations did not survive repeated measurements

Experiments Tried And Reverted

Every item below was implemented, benchmarked, and then removed because the measured result was not strictly better than the current baseline.

Earlier Follow-Up Experiments

  • iterative _value_may_need_runtime_processing_impl()
  • median total: 0.4140s
  • result: worse than baseline
  • _nf_config synth fast path in synthesize_hcl_attributes()
  • median total: 0.3848s
  • result: worse than baseline
  • remove @autoscope from Resource
  • larger-sample median total: 0.3463s
  • result: initial sample looked promising, sustained sample did not
  • avoid calling _analyze_value() for the immutable no-runtime case by duplicating scan logic in _apply_config_bulk()
  • median total: 0.3530s
  • result: worse than baseline
  • use the validated stack directly inside the constructor rather than walking the scope chain again
  • median total: 0.3479s
  • result: worse than baseline

Bytecode-Guided Experiments

These were tested after the bytecode review using a 5-run median baseline of:

  • creation 0.2389s
  • synth 0.0960s
  • total 0.3349s

Tried and reverted:

  • remove the redundant _nf_config copy before normalize_hcl_attributes()
  • median total: 0.3405s
  • split immutable config handling into a dedicated _apply_config_bulk / _analyze_value_immutable hot path
  • median total: 0.3575s
  • add a narrow explicit constructor fast path for the benchmark shape
  • median total: 0.3564s
  • add a plain-key fast path inside normalize_hcl_attributes()
  • median total: 0.3517s

Why These Micro-Optimizations Failed

The main lesson from this round is that the remaining benchmark cost is not coming from one obvious missed local optimization.

What the bytecode and repeated measurements suggest instead:

  • the adaptive interpreter is already doing a good job on attribute and dict access
  • the remaining overhead comes from control flow and repeated function calls across many small objects
  • adding more branches to create a "fast path" often just increases total interpreter work, even when a microbenchmark looks favorable
  • small synth-only changes can still perturb total time enough that they lose once creation noise and full-app synthesis are included

Potential Future Work

The next useful gains are more likely to come from structural changes than from local instruction-count cleanups.

1. Reduce How Often Runtime Scanning Runs

Highest-leverage idea:

  • stop invoking _value_may_need_runtime_processing_impl() on every top-level attribute unless the attribute shape can plausibly contain runtime values

Possible approaches:

  • generated provider classes emit per-attribute metadata indicating whether an attribute can ever contain resource references or runtime tokens
  • plain scalar or JSON-like attributes opt into a "never runtime-bearing" declaration
  • attach a cheap runtime-presence bit to known config containers during construction

This is more promising than making the existing recursive scan slightly faster.

2. Change The Stored Config Representation

Current behavior relies on repeatedly walking ordinary Python dicts, lists, and tuples.

Potential direction:

  • store config values in a representation that carries:
  • whether runtime resolution is needed
  • whether dependency edges exist
  • whether HCL key normalization is needed

If those facts are carried forward from construction, both creation and synth can avoid rediscovering them.

3. Create A Real Specialized Constructor Path

The generic constructor still mixes:

  • validation
  • scope lookup
  • provider lookup
  • hot-path config application
  • optional logging

A meaningful win likely requires more than a small inline fast path. A better approach would be:

  • a dedicated internal constructor or factory for generated resources and the explicit benchmark shape
  • minimal branching
  • prevalidated stack/type inputs
  • direct registration and config installation

This is higher risk than the current micro-optimizations, but more likely to move creation time materially.

4. Improve Benchmark Stability

Some experiments were close enough to the current baseline that run-to-run noise became the deciding factor.

Useful improvements:

  • automate multi-run median capture in the harness
  • record detached-clean-worktree runs by default when capturing history
  • control more of the local environment during comparisons

Better signal quality will make it easier to identify real sub-10ms wins.

5. Consider Native Acceleration Only After Structural Simplification

If Python-level structural changes are exhausted, the recursive runtime scan is the most plausible candidate for native acceleration.

That said, native code should be a last step:

  • first reduce invocation count
  • then simplify semantics
  • only then consider a Rust or C extension for the remaining pure scan work

Ideas That Are Unlikely To Help

Based on this pass, the following are not attractive next moves:

  • more local rebinding or hoisting inside _apply_config_bulk()
  • cosmetic branch reshuffles in normalize_hcl_attributes()
  • small constructor shortcuts that leave the generic control-flow shape intact
  • reworking _looks_like_dependency_reference_impl() without changing how often it is called

Current Recommendation

If another optimization round is needed, start here:

  1. reduce the number of runtime-scan invocations
  2. explore a richer config representation that carries runtime metadata forward
  3. only then revisit a specialized constructor or native scan implementation

That ordering matches both the profiler and the bytecode evidence from this effort.