Skip to content

Ordering Phase 2: carry sortedness / positivity hints for adaptive sort #145

Closed

Description

@godofecht

Summary

From Goal v1.7.0: new array optimization flags (FlagPositive, FlagDescending) plus preserving flags through group/key ops. That is a concrete technique for adaptive algorithm selection — something Flow’s ordering PRD already wants (docs/language/ordering.md “Later”, docs/project/Questions.md Phase 2).

Proposal

When lowering |> sort / sortBy (and later adaptive), optionally track cheap provenance hints on arrays or SSA values:

Hint Use
already ascending / descending skip sort or reverse only
all non-negative (or bounded range) counting / radix / specialize compares
unique prefix length after unique avoid stale-tail confusion (ties to open unique length question)

Hints need not be user-visible initially; compiler/runtime metadata is enough. User-facing policies (adaptive, parallel, …) remain parsed stubs until a selector exists.

Why

  • Goal shows flag preservation pays off even when only a few ops consume the flags.
  • Flow already does in-place insertion sort; the next win is not sorting when unnecessary and picking better algos for numeric keys.
  • Fits “Portable > Fast” if hints are optional and default path stays simple C.

Acceptance

  • Design note: where hints live (AST annotation vs C runtime header vs provenance in typecheck)
  • At least one consumed hint (e.g. skip-sort when input proven sorted)
  • Hook documented for Phase 2 adaptive selector
  • No change to Phase 1 user-visible semantics unless documented

Related

Activity

  1. godofecht commented on Aug 6, 2026

    @godofecht
    ContributorAuthor

    Landed on branch lang/plans-and-ordering.

    Where hints live

    src/flow/ordering_hints.py, a pass over the AST before codegen. It walks a function body in source order and tracks, per array variable:

    order      "asc" / "asc_strict" / "desc" / "desc_strict" / "unknown"
    key_range  [lo, hi] when every element came from an integer literal
    

    Two things create a fact: an array literal whose elements are all numeric literals, and a |> sort in straight-line code. Facts are written back onto the SortExpr / FindExpr nodes as hint_input_order and hint_key_range, where the C generator reads them.

    Facts are dropped on any assignment to the variable or one of its elements, on the variable being passed to a call (it decays to a pointer, so the callee could reorder it), and on anything inside a loop, conditional or match arm. A short initializer says nothing either, because array<i32, 512> = [0, 0] zero-fills the tail. The pass never guesses: a missed hint costs a general plan, a wrong hint skips a sort that was needed, and 19 of the pass's unit tests are about invalidation for that reason.

    A third source needs no analysis at all. A u8 array bounds every key to [0, 255] and a bool array to [0, 1] straight from the element type, which is the positivity hint this issue asks for.

    Hints consumed

    Six sort plans, chosen by the cost selector in #147:

    Plan Applies when Cost
    already_ordered Provenance proves the input is in the requested order 0
    reverse_in_place Provenance proves it is strictly reversed n/2
    counting Whole-element integer key, proven non-negative range of at most 4096 2n + 2k
    insertion Always n²/4, or n when known ordered
    natural_merge n ≥ 16, scratch fits n + extension + n·log2(runs)
    bottom_up_merge Always n + n·log2(n)

    reverse_in_place needs a strict reversal precisely because reversing a run of equal keys would not be stable. All six are stable. Compiler scratch is capped at 256 KiB because the merge plans buffer on the C stack; past that they are rejected and --explain names the budget.

    The hint also crosses constructs. After xs |> sort, a xs |> find(t) on the next line drops from a linear scan to a binary search. Put a call taking xs between them and it goes back to scanning, and --explain says why.

    Measured

    benchmarks/ordering/adaptive_sort_bench.flow, run with benchmarks/ordering/run.sh 5. Apple M4 Max, macOS 26.2, Apple clang 17, -O2. 100 sorts of 32768 elements, five runs, median, copy baseline (0.00012 s) subtracted. The general column pins the general-purpose bottom-up merge with the new general policy.

    input general (s) selected (s) plan speedup
    already sorted 0.04138 0.00105 natural_merge 39.4x
    reverse sorted 0.04109 0.00146 natural_merge 28.1x
    sawtooth, 512 runs 0.07933 0.06221 natural_merge 1.3x
    few unique (8 values) 0.07221 0.05945 natural_merge 1.2x
    random 0.10443 0.09038 natural_merge 1.2x
    random u8 0.08380 0.00179 counting 46.8x

    run.sh prints the selected plan for every site from the same build as the timings, so the plan column cannot drift from the numbers beside it.

    Two honest notes. Random input coming out 12 percent ahead was not what the cost model predicted: building 32-element runs by insertion stays in cache while a merge pass streams the whole array, which a comparison-counting estimate misses. The model is now calibrated to that measurement (RUN_EXTENSION_WEIGHT), and the consequence is that the run-detecting merge is the default above the insertion crossover rather than something adaptive has to ask for. And the compile-time provenance path is not in the table at all, because a hint strong enough to prove the input sorted removes the sort entirely and there is nothing left to time.

    Acceptance

    What is left

    The unique prefix-length question is untouched: unique still compacts a prefix and leaves the tail stale. The hint vocabulary is only sortedness and integer range; nothing yet tracks a unique-prefix length. And the two policies parallel and gpu are still parse-only.

    New: tests/lang/test_sort_plans.flow drives one program through all eight plans and checks results rather than emitted text, so a cost-model change that swaps a plan still has to produce the same answer.

  2. added 2 commits that reference this issue on Aug 9, 2026
    9e27d25
    aa21c02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions