Skip to content

perf(planner): memo hash-consing without JSON; SIL IntentFull planned once - #1565

Draft
zzylol wants to merge 4 commits into
feat/sil-intentfrom
feat/planner-typed-hashing-intent-once
Draft

zzylol wants to merge 4 commits into
feat/sil-intentfrom
feat/planner-typed-hashing-intent-once

Conversation

@zzylol

@zzylol zzylol commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: memo hash-consing confirmed typed equality by comparing JSON texts. On the 100-query backend workload (scaling/backend.s10000.n100), add_candidate ran serde_json on 1.5M pairs of typed-equal operators, which took about 1.4 s of planning CPU.
  • Change: a typed canonical form replaces the JSON. It is a serde serializer that writes a compact binary encoding of the serde data model straight into a hasher or a reused buffer, with floats compared as bit patterns. same_candidate now runs every typed comparison before it writes any canonical form.
  • Effect: the memo and every Stage 1 and Stage 2 candidate are byte-identical to the base on four workloads. Stages 0–2 on that backend workload drop from 11.15 s to 9.52 s of CPU (−15%), and full planning from 11.78 s to 10.38 s (−12%). SIL IntentFull now plans once, with its lightcone queries optional (planned with the others but never answered), instead of twice. On all 24 intents/configs/*.c1r1 configs the plan costs the same (12) or slightly less (12, e.g. slo 6.635858 → 6.635756 per second). Intent planning time summed over the configs drops 3.86 s → 2.62 s (−32%, release build); several configs with lightcone queries plan in about half the time (SB 0.114 → 0.057 s, drill_cnt 0.118 → 0.052 s).

Review guide

  • Base: feat/sil-intent (feat(sil): plan SIL intents: parse/check, lowering, hole guard, planning modes, group latency (L_G) #1553). This draft is stacked on it.
  • Read first:
    • crates/types/src/canonical_form.rs: the encoding and the float policy in its module doc;
    • crates/types/src/stages/logical/memo/hash_consing/mod.rs: same_value, same_expression, expression_hash, same_candidate.
  • Mechanical: memo/mod.rs keeps group ids per hash instead of (id, json). SketchParams' Hash feeds the canonical form instead of a JSON string.
  • Review carefully: whether "typed == and equal canonical form" is exactly "typed == and equal JSON" (Algorithm changes, Correctness).
  • Part 2 (commits test(sil)… and feat(sil)…): read crates/planner/src/intent.rs (plan_intents, IntentFull), crates/stage3-plan-selection/src/lib.rs (select_plan's optional_query_count), plan.rs and report.rs. About 15 files only add optional_query_count: 0 to struct literals (mechanical).

Behavior: before → after

The same command, run on the base and on this branch:

asap_planner --workload scaling/backend.s10000.n100.json --run-until stage3 \
  --deployment-capabilities costinputs/backend-deployment-capabilities.json --format json
  • Plans: the same.
  • Stage 2 output: byte-identical. The --run-until stage2 --verbose --format json output (memo, candidates, Stage 1 and Stage 2 lists) has sha256 b0af70a1… on both builds.
  • Time: planning takes 10.38 s of CPU instead of 11.78 s.

This serves the eval's planning-time measurements on backend-like workloads, where Stages 0–2 are most of the planning time.

Part 2: a SIL intent (intents/configs/OB.c1r1, under cost model 1):

  • Before: plan_intents(..., IntentFull) planned the intent twice, without and with one lightcone query per IN-list reader, and kept the cheaper plan. The plan with lightcones answered each lightcone query: it had a root and query text for each, and charged its small request cost. Planning took 0.412 s, at a cost of 11.720665 per second.
  • After: the intent is planned once, with the lightcone queries as the workload's last optional_query_count queries. Stages 0–2 see them, so the dependent queries may read the lightcone states, but Stage 3 never answers them. Planning takes 0.309 s, at a cost of 11.720562 per second. The plan's roots and query texts are the intent's queries only, and lightcone_query_indices is empty. The IntentPlan JSON schema is unchanged.

Interfaces

crates/types/src/canonical_form.rs (new module):

+/// How a float is written to the canonical form: as its bit pattern, with
+/// every NaN one value; signed zeros apart or together.
+pub enum FloatBits {
+    /// `0.0` and `-0.0` differ (as their JSON texts did): hash-consing.
+    SignedZeros,
+    /// `0.0` and `-0.0` are one value: a hash consistent with numeric `==`.
+    NumericEquality,
+}
+/// Feeds `value`'s canonical form to `hasher`; equal forms feed equal bytes.
+pub fn canonical_hash<T: Serialize + ?Sized, H: Hasher>(value: &T, floats: FloatBits, hasher: &mut H);
+/// Whether two values have one canonical form (false when either fails to serialize).
+pub fn same_canonical_form<T: Serialize + ?Sized>(left: &T, right: &T, floats: FloatBits) -> bool;

The memo's crate-private functions (hash_consing/mod.rs) change as follows. serialized_expression and same_serialized_expression are removed.

-pub(super) fn serialized_expression(expression: &Operator<MemoGroupId>) -> String;
-pub(super) fn expression_hash(serialized: &str) -> u64;
-pub(super) fn same_serialized_expression((left, left_serialized): (&Operator<MemoGroupId>, &str), (right, right_serialized): (&Operator<MemoGroupId>, &str)) -> bool;
+pub(super) fn expression_hash(expression: &Operator<MemoGroupId>) -> u64;
+pub(super) fn same_expression(left: &Operator<MemoGroupId>, right: &Operator<MemoGroupId>) -> bool;

crates/types/src/workload/query.rs, crates/types/src/workload/planning.rs:

 /// A workload's queries; the type stays.
 pub struct QueryWorkload {
     pub language: QueryLanguage,
     pub query_batch: Option<Vec<BatchEntry>>,
     pub repeating_queries: Option<Vec<RepeatingEntry>>,
     pub group_latency_bounds: Vec<GroupLatencyBound>,
+    /// How many of the last queries are optional: planned with the others (their states may be
+    /// shared) but not answered (no root, query text or cost). Default 0, omitted from JSON when 0.
+    pub optional_query_count: usize,
 }
 pub enum WorkloadError {
+    /// Bad input: `optional_query_count` is larger than the query count.
+    TooManyOptionalQueries { optional: usize, queries: usize },
 }

crates/stage3-plan-selection/src/lib.rs, report.rs:

 pub fn select_plan(
     physical: &PhysicalASAPMemoCandidates,
     entries: &[QueryWorkloadEntry],
     group_latency_bounds: &[GroupLatencyBound],
+    optional_query_count: usize,
     data: &DataWorkload,
     cost_inputs: &CostInputs,
     final_results_cache: FinalResultsCache,
 ) -> Result<(PhysicalASAPDAG, Selection), ErrorSelectingPlan>;
 pub enum ErrorSelectingPlan {
+    /// Bad input: an optional query has a scalar root (optional queries need operator roots,
+    /// so the other roots keep their positions).
+    OptionalScalarQuery { query: usize },
 }

Usage (part 1): nothing for a caller changes. Memo::find_or_add_group (Stage 0, the Pass 1 and Pass 2 rules) hashes the expression with canonical_hash, then confirms a bucket hit with typed == and same_canonical_form. Memo::add_candidate compares input requirements, the operator and θ with typed == first, then confirms with same_canonical_form. The planner's output is unchanged; see Behavior.

Usage (part 2): a SIL intent such as q1 EVERY 10s: ($Y, _) := SELECT host, count(*) … LIMIT 5; q2: SELECT user, count(*) FROM auth WHERE host IN $Y … is planned with plan_intents(.., IntentPlanningOptions::default()) (mode IntentFull).

  1. lower_intents appends one lightcone query per IN-list reader (SELECT host, user, count(*) FROM auth … GROUP BY host, user).
  2. IntentFull sets optional_query_count to the number of lightcone queries and calls plan_installable.
  3. Stage 3 builds its MILP over the first entries.len() - optional_query_count queries. q2 may read the (host, user) state that Pass 2 shares with the lightcone group.
  4. The returned IntentPlan has roots for q1 and q2 only, lightcone_query_indices: [], and the report's cost_per_second covers q1 and q2 (checked by three_modes_give_different_plans and optional_query_is_planned_but_not_answered).

Algorithm changes

Memo hash-consing equality

  • Problem: to confirm typed equality, the planner wrote both values as JSON. That meant escaping every string and formatting every float, on 1.5M pairs on b100.

  • Before: same_value(a, b) = a == b && json(a) == json(b), and the hash was SipHash of json(expr).

  • After: same_value(a, b) = a == b && canonical(a) == canonical(b), and the hash is SipHash fed the canonical form directly. The canonical form is a self-delimiting encoding with one tag byte per serde event:

    • a variant is its index;
    • a struct field is its name, then its value; a skipped field gets its own marker;
    • a string is its length, then its bytes;
    • a sequence or map is a start tag, one element tag per entry, then an end tag;
    • a float is its bit pattern.

    same_candidate checks input requirements, then operator ==, then θ ==, and only then the canonical forms. Most typed-equal operators belong to candidates that differ in θ, and these are now rejected without writing anything.

  • Correctness: the decision is the same as before on every pair of values:

    • The encoding is injective over one type. Two values of one type have equal canonical forms iff they produce the same serde event sequence, which is iff their JSON is equal, except for how floats are written.
    • Floats, given typed ==:
      • a NaN never passes typed ==;
      • ±∞ pass == and have equal bits, as their JSON nulls were equal;
      • +0 and −0 pass ==, but their bits differ, as 0.0 and -0.0 did in JSON;
      • any other typed-equal floats have equal bits.
    • Maps are written in iteration order, as JSON wrote them.
    • Tests: canonical_form::tests::decides_as_json_did_on_every_pair (every float class, skipped fields, strings that need escaping) and hash_consing::tests::same_expression_decides_as_json_did (memo expressions and DDSketch θ). End to end, the Stage 2 output is byte-identical on b100, n100, m8u and rh8.
  • Complexity: the same traversal as before, without string escaping or float formatting. Hashing allocates nothing; comparison reuses two thread-local buffers. The memo no longer stores one JSON string per shareable group.

    • Measured on b100, as the minimum of 3–5 alternating runs on a shared host at load 80–110:

      Scope Before (user CPU) After (user CPU) Change
      Stages 0–2 11.15 s 9.52 s −15%
      Whole planner 11.78 s 10.38 s −12%
    • On n100 the whole planner goes from 27.90 s to 27.18 s; the MILP is most of its time.

  • Assumptions and limits: SketchParams' Hash uses NumericEquality, so it is consistent with its derived ==. The JSON hash it replaces put +0 and −0 in different buckets.

SIL IntentFull: one plan with optional lightcone queries

  • Problem: IntentFull planned every intent with lightcone queries twice, once without them and once with all of them answered. That doubled planning time, and it could only keep all of the lightcones or none of them.

  • Before (plan_intents):

    1. lower without lightcones and plan;
    2. lower with lightcones and plan again;
    3. keep the cheaper of the two.
  • After:

    1. lower with lightcones;
    2. mark them optional (optional_query_count) and plan once.

    Stage 3 (select_plan) leaves every optional query unanswered: no (C) row, no root and no cost terms. Stages 0–2 still plan them, so the dependent queries may read their states. If that plan fails, the plan without lightcones is used, as before. Under cost model 3 the old two-plan comparison is kept.

  • Correctness: the one plan's feasible set contains both of the old plans' selections, minus the lightcone roots themselves:

    • The old plan without lightcones is still feasible, because the memo only gains groups.
    • The old plan with lightcones, minus its lightcone roots, is still feasible, because no answered query depends on a lightcone root.

    Answering an optional query only adds rows and non-negative terms, so leaving it unanswered is optimal, and the result is never dearer than either old plan. Checks:

    • intent_full_once_is_no_dearer_than_two_passes (SIL tests) and the ignored intent_full_once_is_no_dearer_on_intent_configs (all 24 *.c1r1 configs, 12 equal and 12 cheaper);
    • optional_query_is_planned_but_not_answered (facade).
  • Complexity: one planning run instead of two. Summed over the 24 configs, planning time goes from 3.86 s to 2.62 s (release build, combined branch). An earlier run of part 2 alone on another host measured 9.58 s → 6.33 s.

  • Assumptions and limits:

    • Optional queries come last in the workload and must have operator roots.
    • Under cost model 3 (lowest_mean_latency), select_plan refuses optional queries, and IntentFull keeps planning twice.

Decisions and open questions

  • Decided (2026-12-03, approved design):
    • The fix is exact, not heuristic.
    • It uses a serde-model canonical form, not derived Hash/Eq across the IR. About 40 IR fields are f64; deriving would need hand-written impls or wrapper types on each of them, and would change PartialEq elsewhere. The canonical form covers every type in a memo expression in one ~300-line module and decides exactly as the JSON did.
  • Needs reviewer decision: the plan answers no lightcone query. So under cost model 1, lightcone_query_indices is always empty and the plan has no lightcone roots or query texts; the dependent queries read the lightcone states directly. A consumer that expected lightcone roots in the plan must not rely on them. The alternative, keeping their roots, would charge their request cost for a query that is never issued.
  • Decided (2026-12-04): an optional query is never answered, rather than modelled as an optional (C) row (Σz ≤ 1). Answering only adds cost, so both give the same optimum, and never answering needs much less plumbing.
  • Decided (2026-12-04):
    • I tried a per-group candidate index (by hash of operator and θ) on top. It measured no gain on b100 (9.08 vs 9.19 s for Stages 0–2), so it was left out.
    • The call counter confirmed same_value from add_candidate as the hot site: 1,507,935 calls, 1.44 s. serialized_expression had 1,256 calls (1.5 ms), and SketchParams::hash was never called.

Verification

Scope Result Notes
cargo test -p asap-types --lib 223 passed 7 new tests; the test commit fails 5 of them against a todo!() canonical form
cargo clippy -p asap-types --all-targets --features test-support -D warnings clean
cargo fmt clean
cargo test -p asap-plan-selection --lib 57 passed (the crate is now asap-stage3-plan-selection). asap-stage0-memo: 9 passed; Pass 1: 41 passed; Pass 2: 40 passed. Part 1 tree
corpus_snapshots (release, including ignored) 11 passed (corpus_plans_match_snapshots, sketch_plans_match_snapshots, pruning_keeps_every_snapshot_optimum, …). Part 1 tree
Stage 2 JSON, base vs branch byte-identical b100, n100, m8u, rh8

| cargo test -p asap-planner --test planner -- sil_intents e2e_plan (combined tree) | 35 passed, 1 ignored | the ignored test needs ASAP_SIL_INTENT_CONFIGS |
| Part 2 alone: asap-stage3-plan-selection --lib, asap-types --lib, asap-planner and asap-planner-cli (all targets, including corpus snapshots), fmt, clippy | all passed | run on the part 2 tree before the cherry-pick |
| intent_full_once_is_no_dearer_on_intent_configs, release | 1 passed: 12 configs equal, 12 cheaper, none dearer (combined branch) | |
| The same, debug build | panics in a debug_assert at cost.rs:1100 ("candidates with the same family and θ fold different rows", an exact Count SummaryAgg vs a SummaryMerge) | The panic is in the test's old two-pass baseline (all lightcones answered), not in the new path. cost.rs is unchanged here. A follow-up issue should look at it. |

Planning time on the combined branch (whole planner, minimum of 3 alternating runs, shared host):

Workload Before: wall / user CPU After: wall / user CPU
b100 13.42 s / 11.77 s 11.79 s / 10.24 s
n100 27.90 s / 27.42 s 27.80 s / 27.07 s
intent suite (24 configs, summed, release test) 3.86 s 2.62 s

The Stage 2 output stays byte-identical on b100 and n100 with both parts applied.

New tests:

  • decides_as_json_did_on_every_pair: on every pair of sample values, the canonical decision equals the JSON decision, and equal canonical forms hash alike.
  • signed_zeros_differ_only_under_signed_zeros, every_nan_is_one_value: the float policy.
  • skipped_fields_keep_fields_apart, strings_and_sequences_are_delimited: injectivity.
  • same_expression_decides_as_json_did: the same equivalence on memo expressions (literals of every float class, quantiles, filters) and DDSketch θ.

Follow-ups

  • Deferred: under cost model 3 (lowest_mean_latency), IntentFull still plans twice, and select_plan refuses optional queries. Optional queries must come last and have operator roots. The debug-build debug_assert at cost.rs:1100 on intent configs is not addressed here.
  • Pass 2's fixpoint loops (item 5 of the speed study) and solving the MILP's independent blocks one at a time (item 1) are not in this PR.

🤖 Generated with Claude Code

zzylol and others added 2 commits December 3, 2026 22:58
… JSON did (canonical form failing)

The canonical form's tests (crates/types/src/canonical_form/tests.rs):
on every pair of sample values (every float class, skipped fields,
strings that need escaping) typed equality confirmed by equal canonical
forms decides as typed equality confirmed by equal JSON did, and equal
canonical forms hash alike; signed zeros differ only under SignedZeros;
every NaN is one value; skipped fields and adjacent strings stay apart.
The memo's same_expression_decides_as_json_did checks the same on memo
expressions and DDSketch θ. The canonical form is a todo!() stub here
(5 tests fail); hash-consing still compares JSON behind its new
signatures (its tests pass).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ot JSON

Memo hash-consing confirmed typed equality with equal JSON texts and
hashed expressions by their JSON: on a 100-query backend workload,
add_candidate's scan confirmed 1.5M typed-equal operators through
serde_json (about 1.4 s of planning CPU; find_or_add_group's
serialization was 1,256 calls, about 1.5 ms; SketchParams' hash was not
called).

- asap_types::canonical_form: a serde Serializer writing a compact,
  self-delimiting binary encoding of the serde data model into a hasher
  (canonical_hash) or two reused thread-local buffers
  (same_canonical_form). Floats as bit patterns: under SignedZeros +0 and
  -0 differ (as their JSON texts did) and every NaN is one value; under
  NumericEquality +0 and -0 are one value too (a hash consistent with ==).
  Typed == (which rejects NaN) confirmed by equal canonical forms decides
  exactly as typed == confirmed by equal JSON did.
- same_candidate runs every typed comparison (input requirements,
  operator, θ) before writing any canonical form: candidates of one
  group mostly share their operator and differ in θ.
- find_or_add_group keeps only group ids per hash, no serialized text.
- SketchParams' Hash feeds its canonical form (NumericEquality) to the
  hasher instead of hashing a JSON string.

The Stage 2 JSON output (memo, every candidate, Stage 1 and Stage 2
lists) is byte-identical to the base on four workloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@zzylol zzylol added canonicalization Canonical IR normalization and invariants optimizer Workload optimization and plan selection labels Dec 4, 2026
zzylol and others added 2 commits December 4, 2026 02:44
…n and answers no lightcone query (failing)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A workload's last QueryWorkload::optional_query_count queries are planned
with the others (Stages 0-2 see them, so the plan may read their states)
but Stage 3 does not answer them: the plan has no root, query text or cost
for them. Answering one is never cheaper (every cost term is non-negative
and an answer only adds rows and terms), so Stage 3 leaves them unanswered.

IntentFull under cost model 1 plans the intent once with its lightcone
queries optional instead of planning it with and without them: the plan is
no dearer than either, and lightcone_query_indices is empty. Under cost
model 3 it keeps the two plans and the better one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@zzylol zzylol added the workload Batch, repeating, or multi-query workload modeling label Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

canonicalization Canonical IR normalization and invariants optimizer Workload optimization and plan selection workload Batch, repeating, or multi-query workload modeling

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant