← Back to Pull requests

feat: query complexity model with combined history #685

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Jun 30, 2026 13:46 UTC
Author

This is PR #372 that appends the history of #401 as requested by the maintainers of CSLib. It preserves the design and code of #372, and mirrors a similar action performed on #401. It also upgrades #372 to more recent toolchains.

This PR includes as examples mergeSort, insertionSort, orderedInsertion, and a collection of examples in the tests files. It also includes the comparison sort lower bound, recently refined by @SamuelSchlesinger. The downstream repository algolean (including some of its PRs), which builds further on this approach, contains randomized quicksort, KMP, Boyer-Moore, Deutsch-Josza etc, through PRs made by the respective authors, and which might be suitable for CSLib.

In an earlier commit, mergeSort follows the structure of the TimeM variant in the main branch to provide a one-one comparison.

An explanation of the approach

Note : This entire description is hand-written by me (Shreyas).

Briefly : I am answering the question "how do you simultaneously allow formalisation of elementary algorithms and advanced algorithms in one unified framework, while not making the STOC paper wait for 80 years of prior work to be formalized first".

The Query Combinator Model : The basic theory

This is the original query-combinator model for algorithms theory within CSLib, first introduced in #201 and #275, and refined in #372 . Another, strictly later PR, #401, mimics this approach with minor implementation differences which imo are suboptimal in comparison to this PR. Below I explain the approach and attach my poster from the STOC'26 workshop "Can AI Do Theory" which succinctly summarizes it.

Algorithms exist in a variety of algorithmic models. These models are defined by the unit operations they care to count. For example:
1. The word-RAM model counts the number of RAM instructions such as word arithmetic, load, store, and boolean operations.
2. The cell probe model counts the number of memory cells read.
3. The cut-query model of graph algorithms counts the number of calls to the cut query.
4. Turing machines count the number of TM transitions.
5. The streaming model gets the next element of an input stream.
6. The LCA model queries a vertex of a graph to get its neighborhood structure.

Given any set of queries, these are sequentially combined using the same programmatic operations : conditionals, loops, procedure calls, recursion etc.

The _query combinator_ approach parametrises a combinator language over the type of unit operations, which we treat as queries answered by an oracle. An algorithm in this approach is an abstract syntax tree, whose internal nodes are combinators, and whose leaf nodes are unit operations or pure operations.

Our Implementation

1. We treat queries as values, specifically constructors of an inductive type. The inputs to a query are arguments of the constructor. The queries by themselves are uninterpreted atoms.
2. Models of a query type provide two functions evalQuery and time. The former provides the meaning of a query. The latter its cost. The cost type may be essentially any commutative monoid. We bundle costs and models together since these together define a computational model and we can speak of reductions between models using Progs.
3. Combinators: We re-use CSLib's FreeM, which are freer monads. We provide a suitable type abbreviation Prog. This provides a single combinator liftBind, which is a continuation, and a single leaf-node constructor pure. Since this happens to be a monad constructor, we get to reuse all of lean's combinators and constructions. This saves us the pain of reinventing substitution, procedure calls etc. This makes our framework more lightweight than a deeper embedding would allow.

Note: This is not necessarily the only possible combinator type. One could implement the IMP language for example. We choose this monadic approach for a few reasons listed further down.

What this PR can accomplish:

1. Formalize algorithms at the right level of abstraction. A frontier paper needn't be out of reach because we haven't formalized all prior algorithms it relies on. We can formalize papers upto prior literature by treating those algorithms as queries. This lets us focus on the mathematical content of the paper we are formalizing.

2. It helps us formalize a hierarchy of models, and reduce them all the way down to basic models.

3. Query types can play the role of Abstract Data Types for data structures.

4. A range of algorithmic models can be formalized in one framework with one set of API lemmas.

5. We can mix models through reductions. So for instance we can define "uniform" circuit classes, since we can talk about TMs and circuits, all in one framework.

6. Prove lower bounds for models using a model uniform approach. As long as there are sufficiently many correct models of a query that produce different outputs on the same input, a Prog must call the query enough times to distinguish between them. So a sorting algorithm that sorts n items must deal with $n!$ different potential orders among these items.

Why a monadic combinator and not a deeper embedding

This is a design decision. One can of course produce a deeper embedding by reinventing a combinator language, giving it a suitable memory model and restricting the non-query operations. This however comes with some trade-offs

1. Implementing a deeply embedded language is a non-trivial task. One has to reinvent the basic constructs, proofs of termination, recursion, variable binding, procedure calls, etc.
2. Choosing memory models and other implementation details is non-trivial and often beside the point of algorithms from the theory side.
3. If one is an algorithms theorist and wishes to rubber duck algorithms in lean, one usually wants to be able to write some operations they don't care about as pure operations.
4. Don't-care operations are fairly normal in the algorithms literature.

Why bundle evaluation and costs into models

1. Conceptually, a model is by definition a combination of its unit operations and their costs. For example, variants of RAM such as integer vs word ram and custom arithmetic models based on them. They support the same operations which evaluate the same way. They only differ in costs. These are meaningfully distinct models.

2. Query composition and reductions can be written in one place. Code for this exists already in Algolean. They are key to building the network of models which takes us from high level algorithms using one or more abstract ADTs for data structures to low level models. Not bundling them results in pointless repetition of the definitions and theorems of composition, reduction, and reduction of compositions of models.

How can one guard against subversion

1. In general an algorithm is part of the spec. If someone writes a definition named heapsort and then proceeds to write mergeSort in the body of the declaration, of course they would get the right complexity upper bounds and correctness proofs. This alone suggests that checking the algorithmic pseudocode is essential.

2. One could insist on theorems that produce a hard input instance.

3. Using pure operations from existing library code. One can block this by requiring correctness proofs to have uniform correctness guarantees. This means, if a sorting algorithm is written with a cmpLE query, it must be correct against all possible models le of this query it a total order. A correct Prog gets no ordering relation upfront. Thus it cannot cheat against an adversarially provided le with a pure function. This of course doesn't hold if for example if you have a determinant query and there is only one valid unique model for this query.

Closely relevant poster : main.pdf

Some attribution

This approach was partly inspired by a similar approach taken in the Agda DSL for synchronous hardware named PiWare by João Paulo Pizani Flor and Wouter Swierstra. There they parametrise a data type of circuit combinators with a cell library. We built on that idea but allowed algorithms to be expressed as ASTs over a set of basic operations. The goal was putting both basic and frontier algorithms within reach of formalization at a level of detail that algorithms theory papers actually use.

Diff: 650 lines (+487 / -163) across 8 files Reviewer: Shreyas4991 Review duration: 221500m
All Vouch review confidence checks passed
Residual risk 0.33 = Change Risk (0.59) × (1 − Review Confidence (0.45)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.59 · 650 lines diff across 8 files
0.59
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
0.02
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
44%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.388
Shallow Review Depth shallow_review_depth
0.344
Real PR Conversation Timeline
1 comments
"Review active on #685"
general weight: 0.35
Reviewers
Assignees
Unassigned
Labels
risk: low confidence: 44.7% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 59% (MEDIUM) · Higher = larger blast radius
59%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 44.7% · Lower = rushed or shallow review
44.7%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 32.6% · Safe to merge
32.6%