Debian Codegraph @

debian/rust-vendor/smawk/AGENTS.md

raw
1 # Project Overview
2
3 The `smawk` crate offers a highly efficient Rust implementation of the **SMAWK
4 algorithm**. This algorithm is designed to find the smallest element in each row
5 of a special type of matrix known as a **totally monotone matrix**.
6
7 The key advantage of the SMAWK algorithm is its ability to reduce the time
8 complexity of certain problems from O(n²) to O(n), transforming a potentially
9 slow quadratic-time operation into a much faster linear-time one. A practical
10 application of this is finding optimal line breaks in a paragraph of text, a
11 feature utilized by the `textwrap` crate.
12
13 ## Core Concepts
14
15 - **Totally Monotone Matrix**: A matrix where every 2x2 submatrix
16 `[[a, b], [c, d]]` satisfies `a + d <= b + c`. The algorithms in this crate
17 are optimized for these matrices.
18 - **Monge Property**: A condition stronger than total monotonicity, where for
19 any `i < i'` and `j < j'`, `M[i, j] + M[i', j'] <= M[i, j'] + M[i', j]`.
20 Matrices with this property are guaranteed to be totally monotone.
21
22 ## Key Features
23
24 - **SMAWK Algorithm**: The primary offering of the crate, providing efficient
25 computation of row and column minima.
26 - **Online Algorithm**: An "online" version of the column minima algorithm is
27 available, where matrix values can be computed based on previously determined
28 minima.
29 - **Matrix Abstraction**: A `Matrix` trait allows the algorithms to work with
30 different matrix representations, with a default implementation for
31 `Vec<Vec<T>>`.
32 - **`ndarray` Integration**: Optional integration with the popular `ndarray`
33 crate for efficient matrix operations.
34 - **`no_std` Compatibility**: The core library is `#![no_std]` compatible,
35 making it suitable for embedded environments. Maintain this compatibility and
36 ensure no `std`-only dependencies are introduced to the core library.
37
38 ## Building and Running the Project
39
40 The `smawk` crate follows standard Rust and Cargo conventions.
41
42 ### Building
43
44 To build the project, use the following command:
45
46 ```bash
47 cargo build
48 ```
49
50 To build with `ndarray` support:
51
52 ```bash
53 cargo build --features ndarray
54 ```
55
56 ### Running Tests
57
58 Execute the test suite with:
59
60 ```bash
61 cargo test
62 ```
63
64 To ensure all features are tested, run:
65
66 ```bash
67 cargo test --all-features
68 ```
69
70 This will run all unit and integration tests, ensuring the correctness of the
71 algorithms.
72
73 ### Running Benchmarks
74
75 The crate uses [Divan](https://github.com/nvzqz/divan) for benchmarking, which
76 measures both execution time and memory allocations.
77
78 To run all benchmarks, use:
79
80 ```bash
81 cargo bench --features ndarray
82 ```
83
84 #### Available Benchmark Suites
85
86 1. **`comparison`**: Compares the brute force, recursive, and SMAWK
87 implementations of `row_minima` and `column_minima` across different matrix
88 sizes (`50`, `100`, `200`, `400`, `800`).
89 2. **`online`**: Benchmarks the `online_column_minima` algorithm across the same
90 sizes.
91
92 #### Running Specific Benchmarks
93
94 You can run a specific benchmark suite or filter by benchmark name and const
95 sizes:
96
97 ```bash
98 # Run only the online benchmark suite
99 cargo bench --bench online --features ndarray
100
101 # Filter to run a specific size (e.g., size 800) in the online benchmark
102 cargo bench --bench online --features ndarray -- smawk_online_column_minima/800
103 ```
104
105 ## Development Conventions
106
107 The `smawk` project adheres to modern Rust development practices.
108
109 ### Code Style
110
111 - **Formatting**: The code is formatted using `dprint`, which is configured in
112 `dprint.json`. It invokes tools like `rustfmt` to format the Rust code.
113 - **Clippy**: The project uses `clippy` for linting and enforcing idiomatic
114 Rust.
115
116 ### Code Safety
117
118 - **No Panics**: Avoid introducing code that can panic, such as using
119 `.unwrap()` on `Option` or `Result` types. The goal is to write very safe code
120 with no runtime crashes.
121
122 ## Performance and Optimization Invariants
123
124 The primary focus of optimization in this crate is the **online SMAWK
125 algorithm** (`online_column_minima`), which is critical for downstream consumers
126 like `textwrap`.
127
128 This is because optimal paragraph layout (such as the Knuth-Plass line-breaking
129 algorithm) is solved using dynamic programming, where the cost of breaking a
130 line at word $j$ depends on the already-computed optimal breaking costs of all
131 words $i < j$. Because these cost values are computed dynamically based on
132 previous column minima, the matrix cannot be populated upfront. It must be
133 queried online, making `online_column_minima` the only algorithm applicable.
134
135 The library is optimized to achieve O(1) heap allocation and O(n) execution
136 speed. To maintain these performance characteristics:
137
138 - **Zero-Cost Abstractions**: The `Matrix` trait and lookup closures are generic
139 parameters (`M`). This allows Rust to monomorphize the implementation at
140 compile time and inline the caller's indexing logic directly into the inner
141 loops, eliminating closure allocation and function call overhead.
142 - **Inlining**: Internal helper functions (like `scratchpads` and
143 `scratchpads_empty`) must be marked `#[inline(always)]` to ensure LLVM
144 flattens their allocations into the callers.
145 - **Bounds Check Elimination**: Because the index math inside `smawk_inner`
146 depends on runtime matrix comparisons, LLVM's loop optimizer (Scalar
147 Evolution) cannot automatically prove that array lookups stay in bounds. We
148 use **upfront maximum index assertions** at the start of the function.
149 Asserting the maximum index accessed in each vector beforehand allows LLVM to
150 prove all smaller index accesses in the loops are in bounds, eliminating
151 bounds checking inside the hot loops.
152 - **Direct Call Sites**: Prefer calling generic functions directly rather than
153 wrapping them in unnecessary closures or macros when possible, keeping the
154 code simple and avoiding borrow checker complications.
155
156 ### Unsafe Performance Gap
157
158 An experimental version utilizing fully unchecked indexing (using
159 `get_unchecked` and `uget` throughout the matrix and scratchpad accesses) was
160 tested. This unsafe version achieved a median runtime of **26.6 µs** (a **~25%
161 reduction in runtime** compared to the safe optimized version's **35.6 µs**).
162
163 This gap exists because LLVM cannot safely eliminate the remaining bounds checks
164 in the matrix coordinate lookups and slice indices. These lookups rely on
165 indices that are **values loaded from memory** (e.g., loading `stack_top` from
166 `rows_scratch` and passing it to `matrix(stack_top, col)`). Even though we
167 asserted the scratchpad bounds beforehand, LLVM cannot statically prove that the
168 _values_ stored inside the mutable scratchpad memory are less than the matrix
169 dimensions or the length of the `minima` slice. Tracking value-range invariants
170 of dynamically populated arrays is beyond LLVM's static analysis, making these
171 remaining bounds checks inevitable in safe Rust.
172
173 #### Potential Avenues to Close the Gap
174
175 To safely eliminate the remaining data-dependent bounds checks without resorting
176 to unsafe code, future revisions could investigate:
177
178 - **Dynamic Re-slicing (Sub-slicing)**: Instead of tracking a mutable integer
179 `stack_len` to index the scratchpads, represent the active stack and columns
180 as subslices (e.g.,
181 `active_stack = &mut rows_scratch[stack_start..stack_start + stack_len]`). By
182 shrinking these subslices during a pop (e.g.,
183 `active_stack = &mut active_stack[..len - 1]`), we can access the stack top
184 via `active_stack[len - 1]`. Because `len - 1` is always less than the slice's
185 own length `len` (when non-empty), LLVM can statically prove bounds safety on
186 every iteration without needing to track the data-dependent loop invariants.
187 - **Consolidating the Scratchpads**: Storing row and column index pairs together
188 rather than in separate `rows_scratch` and `cols_scratch` arrays. This would
189 halve the number of bounds check branches by retrieving both values in a
190 single index lookup.
191 - **Safe Cursor Abstraction**: Wrapping the scratchpad access in a simple, local
192 cursor struct that uses raw pointers internally but exposes a safe interface
193 to `smawk_inner`, isolating the unsafe code to a tiny, verified boundary.
194
195 ## Verifying Assembly and Bounds Check Elimination
196
197 When optimizing core hot loops, you must verify that LLVM successfully optimizes
198 away bounds checks and panic branches. Do not guess; compile and analyze the raw
199 assembly output.
200
201 #### 1. Emitting Assembly
202
203 To emit assembly for the benchmarks (where the generic functions are
204 monomorphized with concrete types), run:
205
206 ```bash
207 cargo rustc --release --bench online --features ndarray -- --emit=asm
208 ```
209
210 _Note: Because the core SMAWK functions (`smawk_inner`, `row_minima`,
211 `column_minima`) are generic over the element type `T` and the matrix type `M`,
212 Rust cannot generate machine code/assembly for them when compiling the library
213 itself. They are only monomorphized and compiled to machine code inside the
214 final binaries (like benchmarks, tests, or examples) that instantiate them with
215 concrete types. Therefore, you must always inspect the assembly of a concrete
216 caller (like the benchmarks)._
217
218 #### 2. Locating Assembly Files
219
220 The generated assembly files (`.s`) are stored in the Cargo target output
221 directory. You can locate them using:
222
223 ```bash
224 ls target/release/deps/online-*.s
225 # or
226 ls target/release/deps/libsmawk-*.s
227 ```
228
229 #### 3. Analyzing the Assembly
230
231 When a bounds check fails or an assertion is triggered in Rust, it branches to
232 panic/bounds-check handlers. Search the assembly file for these indicator
233 symbols:
234
235 - **`panic_bounds_check`**: Called when a slice/array indexing operation is out
236 of bounds (e.g., `core::panicking::panic_bounds_check`).
237 - **`panic` / `panic_fmt`**: Standard panic entry points.
238 - **`ud2`**: The "Undefined Instruction" opcode. In release/optimized builds, if
239 LLVM can prove a panic path is inevitable or if panic-on-abort is configured,
240 it replaces the call to the panic handler with a `ud2` trap instruction.
241
242 You can run `grep` to check for occurrences:
243
244 ```bash
245 grep -E "panic_bounds_check|panic_fmt|ud2" target/release/deps/online-*.s
246 ```
247
248 #### 4. Isolating Specific Functions
249
250 Because some panics might remain in other parts of the binary (like benchmark
251 setup/teardown code), the presence of panic symbols in the file does not
252 necessarily mean the hot loop has them. You must verify the specific function:
253
254 1. Search the assembly file for the mangled function name label (e.g.,
255 `_ZN5smawk11smawk_inner` or simply `smawk_inner`).
256 2. Read the assembly instructions block until the next function label.
257 3. Verify that there are no `call` instructions targeting panic functions and no
258 `ud2` instructions inside the block of instructions for that function.
259
260 ### Testing
261
262 - **Unit Tests**: Each module contains a `tests` submodule with unit tests for
263 the functions in that module.
264 - **Integration Tests**: The `tests` directory contains integration tests that
265 cover the public API of the crate.
266 - **Brute-Force and Recursive Implementations**: The `brute_force.rs` and
267 `recursive.rs` modules provide alternative, less efficient implementations of
268 the row and column minima algorithms. These are used for testing the
269 correctness of the main SMAWK algorithm.
270
271 ### Continuous Integration
272
273 The project uses GitHub Actions for continuous integration. The workflows in
274 `.github/workflows` define the CI pipeline, which includes:
275
276 - **Building and Testing**: On every push and pull request.
277 - **Code Coverage**: Measured and uploaded to Codecov.
278 - **Release Automation**: Automated publishing of new releases to crates.io.