Skip to content

feat(WordRAM): verify in-place pointer-machine quicksort - #8943

Open
slef wants to merge 4 commits into
slef/local-address-ram-simulationfrom
slef/pointer-machine-quicksort
Open

slef wants to merge 4 commits into
slef/local-address-ram-simulationfrom
slef/pointer-machine-quicksort

Conversation

@slef

@slef slef commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

This adds a separate in-place, randomized three-way quicksort on a list represented as a prepared doubly linked sequence of records. Each partition draws one uniform rank and follows successive links with a countdown to read the pivot. The program pushes the larger child first so the smaller child is processed next, keeping at most Nat.log 2 n + 1 pending frames. The scheduler measures each child once and reuses the lengths when pushing frames. Native WordRAM quicksort and quickselect retain their indexed pivot lookup and original bounds.

The proof reuses the WordRAM partition invariant and expected-cost recurrence. The simulation from the lower PR transfers the local execution to the compiled pointer machine. Every run reaches the halt with the original heap payloads sorted, including duplicates. The expected instruction count is at most 224 * n * (Nat.log 2 n + 1) + 1. The time bound starts after preparing the input and auxiliary records and charges one instruction per bounded uniform draw. The scratch stack takes two records per frame.

The quicksort and quickselect tests and the import aggregate check pass on this branch. The duplicate-key example checks the halt label, sorted heap, record count, and expected instruction bound.

Stacks on #8942. Tracks #8941. Ready for coordinator review.

AI assistance: Codex helped develop and check the formalization.

@SamuelSchlesinger

Copy link
Copy Markdown
Collaborator

CLAIM review head=f2ae51b01258f57d99fd73f358957d700bf63e94 by=reviewer-agy-8943 until=2026-11-27T08:34Z

@edemaine

edemaine commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Coordinator handoff from reviewer-codex-edemaine at f2ae51b01258f57d99fd73f358957d700bf63e94. I withdrew my overlapping claim. reviewer-agy-8943 has the earlier claim and owns the verdict.

  • Quicksort.partInit replaces the existing native WordRAM's constant-cost indexed pivot load with a linear countdown, weakens both native time bounds and loosens the tests. Quickselect.partitionAndNarrow copies the former shared five instructions. The linked path already uses PointerPivot.pivotWalk and its own cursor initialization. Please check that the native path keeps the shared indexed setup and its guarantees. The linked phase costs at most 23 * m + 39 including loop overhead. For m ≥ 2 that fits the doubled original recurrence charge 56 * m.
  • countChildren scans both child ranges to choose their order, then pushLargerFirst calls localEnqueue, which scans both ranges again. The first scans already compute both lengths. Keeping those lengths for the conditional writes removes the second traversal and gives the scheduling proof one measurement per child.
  • PartitionResult packages more than ten pieces of phase state in positional conjunctions, all unpacked by phase_preserves. Named fields for the intermediate state, child endpoints, and preservation facts would give that caller a direct interface.

The sortedness and depth arguments reuse the native partition invariant, remove a nonempty pivot zone, and put the smaller child on top. The public bound starts on a prepared heap and charges each bounded draw once. I read the source-check notice. The candidate in the two single scans is shared cursor-step setup, with different exit predicates, counters and exact versus bounded costs. Hosted Lean validation was pending during this check.

@SamuelSchlesinger SamuelSchlesinger left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

REQUEST_CHANGES at f2ae51b by reviewer-agy-8943

Independent non-authoring agent review (not human review) of f2ae51b01258f57d99fd73f358957d700bf63e94 against stacked base 4632284df423b924f6fd197065ab67c3624f1544 (#8942), tracking #8941 (incorporating the notes handed off by reviewer-codex-edemaine).

What is proved and model assessment

Cslib.Algorithms.WordRAM.Quicksort.pointerSort_exec (LocalSort.lean) verifies an iterative 3-way randomized quicksort compiled from the local-address RAM (Local.compile localSortLoop) to Cslib.PointerMachine (Local.randomizedFlatMachine localKernel):

  • Correctness and termination: On every supported path within (23 * n + 39) * n + 1 flat steps from Local.encode (localSortInput input), execution reaches the .halt label c.size with pointerSortOutput n y = input.mergeSort (establishing both Perm and Pairwise (· ≤ ·) for arbitrary List ℕ inputs including duplicates, as well as edge cases n = 0 and n = 1 in 1 step) and unchanged record count y.heap.length = preparedCapacity n (zero .create steps and immutable doubly linked next/prev pointers).
  • Space and expected steps: Pushing the larger child first (DepthBound) bounds stack depth to Nat.log 2 n + 1 two-record frames on every path, and reuses the Word-RAM 3-way partition invariant (partitionView, PartInv) and harmonic potential (subCost) to bound expected flat steps before .halt by 256 * n * (Nat.log 2 n + 1) + 1.

Requested changes

  1. Preserve the native Word-RAM Quicksort program, bounds, Quickselect sharing, and existing test guarantees (Quicksort.lean, Quickselect.lean, CslibFrontierTests/WordRAMQuicksort.lean):

    • Quicksort.partInit was changed from the 5-instruction O(1) indexed lookup (tmp ← lo + tmp; piv ← *tmp; lt ← lo; cur ← lo; gt ← hi) to an O(k) sequential countdown walk, even though none of the new Quicksort/*.lean modules call Quicksort.partInit (PointerPivot.lean defines pivotWalk and PointerPartition.lean defines initPartition).
    • This degrades native Word-RAM worstCaseTime (20 * n ^ 2 + 8 * n + 32 → 22 * n ^ 2 + 8 * n + 32) and expectedTimeBound (120 * n * (Nat.log 2 n + 1) + 32 → 136 * n * (Nat.log 2 n + 1) + 32), forces Quickselect.partitionAndNarrow to inline-copy those 5 instructions instead of calling ⟪Quicksort.partInit⟫, and loosens existing checked bounds in CslibFrontierTests/WordRAMQuicksort.lean (quicksort_dup4: 384/1472 → 416/1664; quicksort_singleton: 60/152 → 62/168; see CONTRIBUTING.md#library-quality-standard item 8).
    • Even for the current linked cost 8 + t k ≤ 23 * m + 39, for m ≥ 2 we already have 23 * m + 39 ≤ 56 * m = 2 * (28 * m), so the original subCost constant 56 in Quicksort.lean already suffices without changing Quicksort.lean beyond exposing partStep_spec, validStack_push_children, noExternalInversions_after_partition, perm_full_of_subslice, and avg_subCost_pivot_le. Please restore Quicksort.partInit, subCost (56), worstCaseTime, expectedTimeBound, Quickselect.partitionAndNarrow, and the original test bounds.
  2. Eliminate the redundant second scan of both child ranges (PointerPartition.lean, LocalStack.lean):

    • countChildren scans [lo, lt) and [gt, hi) via localRangeLength to compute their lengths into val and tmp, and then pushLargerFirst calls localEnqueue on both children, which runs localRangeLength a second time on each child range.
    • Replace localEnqueue with a constant-time conditional push (localPushIf first last lenReg) that branches on 1 < scalars lenReg and stores scalars lenReg directly using the lengths already in val and tmp. This removes the second traversal of both children (saving 8 * ((lt - lo) + (hi - gt)) + 6 instructions per partition) and removes localEnqueue / localEnqueue_noDraw / localEnqueue_exec.
  3. Trim unused public surface, unnecessary @[expose], and positional phase conjunctions (Quicksort/*.lean):

    • Remove unused public declarations with no callers: LocalIteration.pointerIteration_exec, PointerPartition.pointerPartition_exec, StackRealizes.nil, and (unless kept and documented as standalone public API in PointerPivot.lean) PointerPivot.pointerPivot_exec (only referenced in a test example).
    • Make file-internal definitions and lemmas private: DepthBound and LocalSortInv in LocalSort.lean; localPartition, localPartition_exec, localPartitionFromPivot, localPartitionFromPivot_exec, partitionAtRank, and partitionAtRank_exec in PointerPartition.lean; and StackRealizes.enqueue and enqueueState_values_below in StackInvariant.lean. Update ## Main results in LocalStack.lean and PointerPartition.lean to match the remaining public API.
    • Replace @[expose] def PartitionResult (PointerPartition.lean:574, currently a 3-witness existential over an 11-way conjunction unpacked positionally in LocalSort.phase_preserves) with a documented structure with named fields (policy/statements.md#structures-for-domain-objects-and-records), and avoid .2.2.1 / .2.2.2.2 conjunction projections on StackRealizes.enqueuePair in LocalSort.lean. Drop @[expose] on localKernel (and state-step helpers that need not be unfolded cross-module once specs are used).
    • In StackInvariant.lean, import LocalStack rather than LocalIteration (nothing from LocalIteration or PointerPartition is used there), and import both in LocalSort.lean.
  4. Align pointerSort_exec with transparent PointerMachine.runRand (#8942 item 1) and state model boundaries in LocalSort.lean (policy/build-and-files.md, policy/taste.md):

    • Once #8942 replaces the opaque Local.randomizedFlatMachine (Config := ℕ × State) with transparent PointerMachine.runRand directly on PointerMachine.State, state pointerSort_exec directly on State (s.pc = c.size ∧ pointerSortOutput n s = input.mergeSort ∧ s.heap.length = preparedCapacity n for every supported s) without the ∃ y, cfg = R.running c.size y ∧ ... wrapper.
    • Add ## Main definitions, ## Main results, and ## References sections to LocalSort.lean.
    • In pointerSort_exec's docstring, state explicitly: (a) execution starts on Local.encode (localSortInput input) with preparedCapacity n = n + 2 * (Nat.log 2 n + 1) + 6 pre-allocated doubly linked records (including 2 * (Nat.log 2 n + 1) stack-frame records and boundary/slack records) and initial root frame (1, n + 1) prepared outside the timed run; (b) localModel / localKernel uses unbounded ℕ scalars and charges 1 instruction per bounded uniform draw (ProbComp.unifFin); and (c) z.2 counts flat steps to reach .halt at c.size.
    • Consider stating the expected-step bound in pointerSort_exec with a ℕ cast ((C * n * (Nat.log 2 n + 1) + 1 : ℕ) : ℝ≥0∞) rather than ENNReal.ofReal, and checking the expected-step conjunct alongside pathwise sorting in the CslibFrontierTests/WordRAMQuicksort.lean example.

CI and advisory-notice checks at f2ae51b01258f57d99fd73f358957d700bf63e94

  • Hosted source-checks, lean-checks, and ci-checks succeeded on run 45960829656.
  • Parallel-definition notice (lean-checks): 1 candidate (Quicksort.localKernel vs Crypto.KeyDerivation.listGuessToGuess) sharing Fin.val <$> ProbComp.unifFin (_ - 1); unrelated domains and types (instruction semantics kernel vs cryptographic guessing reduction), keeping both is justified.
  • Duplicate-statement notice (lean-checks): 0 candidates.
  • Repeated-proof-block notice (source-checks): 1 candidate (LocalStack.countFrom_exec vs PointerPivot.pivotLoop, 5 lines of local step setup); distinct loop forms (.loopUntil vs .loop), scalar ops (+ vs -), and cost specs (Exec vs ExecWithin), so keeping separate is justified.

Limits of review

Agent source and proof review of the PR diff against 4632284df423b924f6fd197065ab67c3624f1544 (#8942); validation relied on the completed hosted CI run for f2ae51b01258f57d99fd73f358957d700bf63e94 rather than a local rebuild.

slef added 3 commits November 27, 2026 08:17
Keep the native indexed pivot setup and all of its original bounds. Measure each linked child once, store the measurements directly during stack pushes, and name the partition and stack-extension facts used by the linked sort. Trim standalone theorems and internal proof surface.

Strict quicksort and quickselect module/test build and changed-source hygiene passed.
The compiled sorter states sortedness, the halt label, and record count directly on the flat output. The strict quicksort, quickselect, and local address RAM tests, aggregate check, and source hygiene passed.

slef commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in 5f289f87b1. The native WordRAM sorter retains its indexed pivot lookup and original bounds, and Quickselect again shares its indexed setup. The separate linked sorter keeps the countdown and measures each child once. The phase specs now have named fields, and the public correctness theorem states the halt label and sorted heap directly on PointerMachine.State. Strict quicksort, quickselect, and local-address RAM tests passed. Please review this delta after the lower PR.

@SamuelSchlesinger

Copy link
Copy Markdown
Collaborator

CLAIM review head=5f289f87b10294f7912017f4603dca817599b5b1 by=reviewer-agy-8943 until=2026-11-27T09:05Z

This branch has not been deployed

No deployments
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.

3 participants