lemmaly 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +238 -0
- package/cli/gen-agents-md.js +60 -0
- package/cli/gen-rule-docs.js +885 -0
- package/cli/lemmaly.js +162 -0
- package/commands/benchmark.md +40 -0
- package/commands/budget.md +53 -0
- package/commands/complexity.md +26 -0
- package/commands/cut.md +27 -0
- package/commands/hotpath.md +22 -0
- package/commands/invariant.md +22 -0
- package/commands/n-plus-one.md +20 -0
- package/commands/profile.md +34 -0
- package/commands/regress.md +43 -0
- package/commands/scale-check.md +37 -0
- package/commands/ship-check.md +26 -0
- package/package.json +48 -0
- package/rules/cpp.json +46 -0
- package/rules/csharp.json +38 -0
- package/rules/go.json +46 -0
- package/rules/java.json +38 -0
- package/rules/javascript.json +102 -0
- package/rules/php.json +38 -0
- package/rules/python.json +62 -0
- package/rules/ruby.json +38 -0
- package/rules/rust.json +38 -0
- package/rules/shell.json +38 -0
- package/rules/sql.json +54 -0
- package/skills/complexity-cuts/SKILL.md +259 -0
- package/skills/invariant-guard/SKILL.md +310 -0
- package/skills/lemmaly/AGENTS.md +1869 -0
- package/skills/lemmaly/SKILL.md +365 -0
- package/skills/lemmaly/references/async.md +135 -0
- package/skills/lemmaly/references/complexity.md +66 -0
- package/skills/lemmaly/references/hot-paths.md +87 -0
- package/skills/lemmaly/references/memory.md +118 -0
- package/skills/lemmaly/references/n-plus-one.md +139 -0
- package/skills/lemmaly/rules/cpp-map-double-lookup.md +38 -0
- package/skills/lemmaly/rules/cpp-range-loop-copy.md +33 -0
- package/skills/lemmaly/rules/cpp-raw-new.md +36 -0
- package/skills/lemmaly/rules/cpp-string-concat-in-loop.md +45 -0
- package/skills/lemmaly/rules/cpp-vector-push-no-reserve.md +40 -0
- package/skills/lemmaly/rules/cs-async-void.md +45 -0
- package/skills/lemmaly/rules/cs-disposable-no-using.md +32 -0
- package/skills/lemmaly/rules/cs-list-contains-in-loop.md +36 -0
- package/skills/lemmaly/rules/cs-string-concat-in-loop.md +42 -0
- package/skills/lemmaly/rules/go-defer-in-loop.md +39 -0
- package/skills/lemmaly/rules/go-err-not-checked.md +38 -0
- package/skills/lemmaly/rules/go-loop-var-capture.md +47 -0
- package/skills/lemmaly/rules/go-slice-append-no-cap.md +39 -0
- package/skills/lemmaly/rules/go-string-concat-in-loop.md +44 -0
- package/skills/lemmaly/rules/java-arraylist-remove-in-for-i.md +44 -0
- package/skills/lemmaly/rules/java-bare-catch-exception.md +42 -0
- package/skills/lemmaly/rules/java-list-contains-in-loop.md +40 -0
- package/skills/lemmaly/rules/java-string-concat-in-loop.md +42 -0
- package/skills/lemmaly/rules/js-anonymous-handler-jsx.md +31 -0
- package/skills/lemmaly/rules/js-array-key-index.md +29 -0
- package/skills/lemmaly/rules/js-async-in-foreach.md +43 -0
- package/skills/lemmaly/rules/js-await-in-for-loop.md +41 -0
- package/skills/lemmaly/rules/js-deep-clone-via-json.md +33 -0
- package/skills/lemmaly/rules/js-helper-call-in-iterator.md +41 -0
- package/skills/lemmaly/rules/js-includes-in-iterator.md +37 -0
- package/skills/lemmaly/rules/js-inline-object-jsx-prop.md +35 -0
- package/skills/lemmaly/rules/js-nested-for-loops.md +45 -0
- package/skills/lemmaly/rules/js-spread-in-reduce.md +38 -0
- package/skills/lemmaly/rules/js-unique-via-indexof.md +35 -0
- package/skills/lemmaly/rules/js-useeffect-missing-deps.md +33 -0
- package/skills/lemmaly/rules/php-count-in-for-condition.md +45 -0
- package/skills/lemmaly/rules/php-in-array-in-loop.md +42 -0
- package/skills/lemmaly/rules/php-loose-equality.md +35 -0
- package/skills/lemmaly/rules/php-query-in-loop.md +47 -0
- package/skills/lemmaly/rules/py-bare-except.md +39 -0
- package/skills/lemmaly/rules/py-django-loop-without-eager.md +42 -0
- package/skills/lemmaly/rules/py-in-list-literal.md +37 -0
- package/skills/lemmaly/rules/py-mutable-default-arg.md +39 -0
- package/skills/lemmaly/rules/py-open-without-with.md +33 -0
- package/skills/lemmaly/rules/py-range-len.md +35 -0
- package/skills/lemmaly/rules/py-string-concat-in-loop.md +43 -0
- package/skills/lemmaly/rules/rb-bare-rescue.md +41 -0
- package/skills/lemmaly/rules/rb-include-in-iterator.md +37 -0
- package/skills/lemmaly/rules/rb-n-plus-one-activerecord.md +39 -0
- package/skills/lemmaly/rules/rb-string-concat-in-loop.md +39 -0
- package/skills/lemmaly/rules/rs-clone-in-loop.md +38 -0
- package/skills/lemmaly/rules/rs-string-push-no-capacity.md +43 -0
- package/skills/lemmaly/rules/rs-unwrap-in-prod.md +36 -0
- package/skills/lemmaly/rules/rs-vec-push-no-capacity.md +42 -0
- package/skills/lemmaly/rules/sh-for-ls.md +41 -0
- package/skills/lemmaly/rules/sh-set-e-no-pipefail.md +37 -0
- package/skills/lemmaly/rules/sh-unquoted-var.md +35 -0
- package/skills/lemmaly/rules/sh-useless-cat-pipe.md +32 -0
- package/skills/lemmaly/rules/sql-leading-wildcard-like.md +34 -0
- package/skills/lemmaly/rules/sql-not-in-subquery.md +38 -0
- package/skills/lemmaly/rules/sql-or-in-where.md +35 -0
- package/skills/lemmaly/rules/sql-select-no-limit.md +37 -0
- package/skills/lemmaly/rules/sql-select-star.md +29 -0
- package/skills/lemmaly/rules/sql-update-no-where.md +35 -0
- package/skills/mathguard/SKILL.md +277 -0
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: mathguard
|
|
3
|
+
description: Use when working with large-scale data, similarity search, deduplication, top-K / heavy-hitters, streaming analytics, cardinality estimation, embeddings, recommender systems, signal/image processing, polynomial or big-integer arithmetic, convolution, graph distance, computational geometry, randomized algorithms, or any problem with n >= 10^6 where exact computation is wasteful. Recognizes when classical algorithms hit their lower bound and an approximate or math-heavy technique (Bloom filter, HyperLogLog, Count-Min Sketch, MinHash/LSH, FFT/NTT, Johnson-Lindenstrauss projection, sweep line, kd-tree/BVH, fast exponentiation, monoid parallel reduction, amortized potential method) gives an asymptotic win. Load after lemmaly when a classical O(n log n) is the floor but smarter math wins.
|
|
4
|
+
metadata:
|
|
5
|
+
priority: 3
|
|
6
|
+
role: math-escalation
|
|
7
|
+
pathPatterns:
|
|
8
|
+
- '**/*.{js,jsx,ts,tsx,mjs,cjs}'
|
|
9
|
+
- '**/*.py'
|
|
10
|
+
- '**/*.rs'
|
|
11
|
+
- '**/*.go'
|
|
12
|
+
- '**/*.{cpp,cc,cxx,hpp,hh,hxx}'
|
|
13
|
+
- '**/*.java'
|
|
14
|
+
- '**/*.cs'
|
|
15
|
+
importPatterns:
|
|
16
|
+
- 'numpy'
|
|
17
|
+
- 'scipy'
|
|
18
|
+
- 'torch'
|
|
19
|
+
- 'sklearn'
|
|
20
|
+
- 'faiss'
|
|
21
|
+
- 'annoy'
|
|
22
|
+
- 'hnswlib'
|
|
23
|
+
chainTo:
|
|
24
|
+
- skill: lemmaly
|
|
25
|
+
when: 'classical algorithm has not been ruled out yet'
|
|
26
|
+
- skill: invariant-guard
|
|
27
|
+
when: 'need to state ε-bounds as part of the postcondition'
|
|
28
|
+
- skill: complexity-cuts
|
|
29
|
+
when: 'baseline code exists and bottleneck is CPU/memory, not approximation'
|
|
30
|
+
retrieval:
|
|
31
|
+
aliases:
|
|
32
|
+
- probabilistic-structures
|
|
33
|
+
- approximate-algorithms
|
|
34
|
+
- math-heavy
|
|
35
|
+
intents:
|
|
36
|
+
- approximate at scale
|
|
37
|
+
- bloom filter or hll
|
|
38
|
+
- similarity search at large n
|
|
39
|
+
- fft convolution
|
|
40
|
+
- dimensionality reduction
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
# mathguard — Math-Heavy Optimization for AI Code
|
|
44
|
+
|
|
45
|
+
lemmaly makes you pick the right classical algorithm. mathguard kicks in when the classical algorithm is already optimal but **mathematics gives a better bound** — usually by accepting bounded approximation, exploiting structure, or moving to a smarter algebraic space.
|
|
46
|
+
|
|
47
|
+
The model knows these techniques. It almost never proposes them spontaneously. mathguard fixes that.
|
|
48
|
+
|
|
49
|
+
**Violating the letter of these rules is violating the spirit of the skill.** A Bloom filter where the caller assumed exact answers is a production incident, not an optimization.
|
|
50
|
+
|
|
51
|
+
## The Iron Law
|
|
52
|
+
|
|
53
|
+
```text
|
|
54
|
+
NO APPROXIMATE STRUCTURE WITHOUT WRITTEN ε/δ AND EXPLICIT CALLER ACCEPTANCE
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Probabilistic data structures (Bloom, HyperLogLog, Count-Min, MinHash/LSH, t-digest), randomized projections (JL), and lossy transforms (floating FFT) all change the answer's meaning. Before proposing one:
|
|
58
|
+
|
|
59
|
+
1. Write the error parameter the caller will see (false-positive rate, relative error, distortion bound).
|
|
60
|
+
2. Identify the caller and state, in one sentence, that they tolerate this kind of wrong answer.
|
|
61
|
+
3. If you cannot identify the caller, or they need exact (auth checks, billing, dedup keys, deduplication for correctness, anything that flows into a primary key), DO NOT propose the approximate structure. Keep classical, or escalate to a sharded/streaming exact design.
|
|
62
|
+
|
|
63
|
+
This rule has saved more incidents than any other in this skill. Do not soften it.
|
|
64
|
+
|
|
65
|
+
## Non-negotiable rules
|
|
66
|
+
|
|
67
|
+
1. **Declare exact vs approximate up front.** Before suggesting a math-level technique, state:
|
|
68
|
+
- `mode: exact` or `mode: approximate`
|
|
69
|
+
- If approximate: the error parameter (ε, δ, false-positive rate) and a sentence on whether the caller can tolerate it.
|
|
70
|
+
- If the caller needs exact and there is no exact win, say so and stop — do not silently degrade to approximate.
|
|
71
|
+
|
|
72
|
+
2. **Cite the technique by name.** Never describe a probabilistic or numerical trick in vague terms. Name it: `Bloom filter`, `HyperLogLog`, `Count-Min Sketch`, `MinHash + LSH`, `Johnson–Lindenstrauss projection`, `FFT`, `NTT`, `fast exponentiation`, `Karatsuba`, `Strassen`, `sweep line`, `kd-tree`, `BVH`, `union-find with path compression`, `Floyd's cycle detection`, `Boyer-Moore majority`, `reservoir sampling`, `Knuth shuffle`, `Aho-Corasick`, `suffix automaton`, `segment tree with lazy propagation`, `Fenwick tree`, `monoid scan / parallel prefix`. A named technique is auditable; "a smart approximation" is not.
|
|
73
|
+
|
|
74
|
+
3. **State the trade you are making.** Every math-level optimization buys something at a cost. In one line:
|
|
75
|
+
- Buys: `space`, `time`, `wall-clock`, `parallelism`.
|
|
76
|
+
- Costs: `accuracy ε=?`, `code complexity`, `dependency`, `non-determinism`, `numerical stability`.
|
|
77
|
+
- If the cost is invisible to the caller, write "callers see no change".
|
|
78
|
+
|
|
79
|
+
4. **Justify the asymptotic win.** Do not propose a math technique without a one-line bound argument:
|
|
80
|
+
- "HyperLogLog: count uniques in O(log log n) bits at standard error 1.04/√m."
|
|
81
|
+
- "FFT: polynomial multiplication O(n log n) vs schoolbook O(n²)."
|
|
82
|
+
- "JL projection: preserves pairwise distances within (1±ε) using O(log n / ε²) dimensions."
|
|
83
|
+
- "Sweep line: rectangle overlap from O(n²) pair checks to O(n log n) events."
|
|
84
|
+
No bound, no proposal.
|
|
85
|
+
|
|
86
|
+
5. **Forbid math cargo-culting.** Do not introduce these techniques when:
|
|
87
|
+
- n is small enough that a linear scan finishes in microseconds (n < ~10⁴ unless it is a hot path).
|
|
88
|
+
- The problem is I/O-bound — the math win disappears behind network/disk.
|
|
89
|
+
- Exact answers are required and no exact technique exists.
|
|
90
|
+
- The team will not maintain it (write that down: "team familiarity: ?").
|
|
91
|
+
|
|
92
|
+
## The pre-proposal protocol
|
|
93
|
+
|
|
94
|
+
Before suggesting a math-level technique, your message must contain — in this order:
|
|
95
|
+
|
|
96
|
+
1. **The classical floor** — what is the best non-mathy algorithm and its Big-O? ("Hash join is O(n+m); we're already there.")
|
|
97
|
+
2. **Why classical is not enough** — n too large, space blows up, real-time deadline, etc.
|
|
98
|
+
3. **The math technique** — named (rule 2).
|
|
99
|
+
4. **Exact or approximate** — with ε if approximate (rule 1).
|
|
100
|
+
5. **The new bound** — with one-line derivation (rule 4).
|
|
101
|
+
6. **The trade** — buys/costs (rule 3).
|
|
102
|
+
7. **When NOT to use this** — at least one disqualifier.
|
|
103
|
+
8. **The code or pseudocode.**
|
|
104
|
+
|
|
105
|
+
If any of 1–7 is missing, do not propose the technique.
|
|
106
|
+
|
|
107
|
+
## Playbook — math technique → problem → win → caveat
|
|
108
|
+
|
|
109
|
+
### Sketches and probabilistic structures (massive data, approximate)
|
|
110
|
+
|
|
111
|
+
| Problem | Classical | Math technique | Win | Caveat |
|
|
112
|
+
|---|---|---|---|---|
|
|
113
|
+
| Membership: "have I seen this key?" at scale | `Set<id>`, O(n) space | **Bloom filter** | O(n) bits at chosen ε false-positive | False positives only; cannot remove (use Cuckoo if needed) |
|
|
114
|
+
| Count distinct values in a stream | `Set` to count, O(unique) space | **HyperLogLog** | O(log log n) bits, ~1% relative error | Approximate; cannot list elements |
|
|
115
|
+
| Top-K / heavy hitters in a stream | full counter, O(unique) space | **Count-Min Sketch** + heap | O(log(1/δ)·1/ε) space | Overestimates; choose ε,δ deliberately |
|
|
116
|
+
| Document / set similarity at scale | full Jaccard, O(n·m) | **MinHash + LSH** | Sub-linear ANN query | Tunes recall vs precision; param search |
|
|
117
|
+
| k-NN in high-dim vectors | brute O(n·d) | **JL projection → HNSW / IVF** | O(log n) per query, (1±ε) distortion | Index build cost; recall < 1 |
|
|
118
|
+
| Reservoir of size k from a stream of unknown length | buffer all, O(n) space | **Reservoir sampling** | O(k) space, uniform sample | Single-pass only |
|
|
119
|
+
| Find majority element | counter map | **Boyer-Moore majority vote** | O(1) space, O(n) time | Requires majority exists; verify pass |
|
|
120
|
+
| Quantiles in a stream | sort, O(n log n) | **t-digest / GK** | O(1/ε) space, ε-accurate quantiles | Approximate |
|
|
121
|
+
|
|
122
|
+
### Fast arithmetic / transforms (numeric and combinatorial)
|
|
123
|
+
|
|
124
|
+
| Problem | Classical | Math technique | Win | Caveat |
|
|
125
|
+
|---|---|---|---|---|
|
|
126
|
+
| Multiply two polynomials / big integers | O(n²) | **FFT / NTT / Karatsuba** | O(n log n) | Floating FFT loses precision — use NTT for integers |
|
|
127
|
+
| Convolution of two signals | O(n·m) | **FFT-based convolution** | O((n+m) log(n+m)) | Numerical noise at very small magnitudes |
|
|
128
|
+
| `pow(a, b) mod p`, b large | O(b) multiplications | **Fast exponentiation (square-and-multiply)** | O(log b) | Watch for overflow inside; use modular arithmetic |
|
|
129
|
+
| GCD of large integers | repeated subtraction | **Euclidean algorithm** | O(log min) | Standard; AI sometimes still writes the subtraction loop |
|
|
130
|
+
| Matrix multiplication, n large | O(n³) | **Strassen** (then Coppersmith-Winograd family) | O(n^2.81) | High constant; only wins for very large dense |
|
|
131
|
+
| Solving Ax=b for sparse A | O(n³) dense | **Conjugate gradient / sparse LU** | O(nnz · iterations) | Numerical conditioning matters |
|
|
132
|
+
| Modular inverse | brute force | **Extended Euclidean** or **Fermat** when p prime | O(log p) | p must be prime for Fermat |
|
|
133
|
+
|
|
134
|
+
### Dimensionality reduction and linear algebra
|
|
135
|
+
|
|
136
|
+
| Problem | Classical | Math technique | Win | Caveat |
|
|
137
|
+
|---|---|---|---|---|
|
|
138
|
+
| Similarity in d-dim, d large | O(n·d) brute | **JL projection** to k = O(log n / ε²) | O(n·k) at (1±ε) distortion | Random; verify on validation set |
|
|
139
|
+
| Recommender from rating matrix | iterate full matrix | **Truncated SVD / matrix factorization** | O(k·(n+m)) for rank-k | Choose k; refresh strategy |
|
|
140
|
+
| Document-term similarity | TF-IDF O(n·m) | **LSA via SVD** | rank-k approximation | Latent dims are not interpretable |
|
|
141
|
+
| PCA on n samples in d dims | O(n·d²) | **Randomized SVD** | O(n·d·k) for rank-k | Randomized; set oversampling |
|
|
142
|
+
|
|
143
|
+
### Geometry (spatial queries)
|
|
144
|
+
|
|
145
|
+
| Problem | Classical | Math technique | Win | Caveat |
|
|
146
|
+
|---|---|---|---|---|
|
|
147
|
+
| Range / nearest-neighbor in 2D-3D | O(n) per query | **kd-tree / R-tree / BVH** | O(log n) per query | Degrades in high d; use ANN instead |
|
|
148
|
+
| Rectangle / interval overlap pairs | O(n²) pair check | **Sweep line + active set (BBST)** | O((n+k) log n) | k = output size; segment tree variant exists |
|
|
149
|
+
| Polygon point-in-polygon at scale | O(n·v) | **BSP / monotone decomposition / R-tree** | O(log v) per query after build | Build cost |
|
|
150
|
+
| Convex hull of n points | O(n²) gift wrap | **Graham scan / Andrew's monotone chain** | O(n log n) | Numerical robustness for collinear |
|
|
151
|
+
| Closest pair of points | O(n²) | **Divide and conquer** | O(n log n) | Carefully merge across the strip |
|
|
152
|
+
|
|
153
|
+
### Graph and algebraic tricks
|
|
154
|
+
|
|
155
|
+
| Problem | Classical | Math technique | Win | Caveat |
|
|
156
|
+
|---|---|---|---|---|
|
|
157
|
+
| Connected components under merges | recompute BFS each merge | **Union-Find with path compression + rank** | α(n) ≈ O(1) per op amortized | Inverse Ackermann is effectively constant |
|
|
158
|
+
| Range sum / update on array | O(n) per query | **Fenwick tree** | O(log n) per op | Inclusive ranges; off-by-one risk |
|
|
159
|
+
| Range query with monoid (sum/min/max/gcd) | O(n) per query | **Segment tree (with lazy if range updates)** | O(log n) | More code than Fenwick; more general |
|
|
160
|
+
| LCA in a tree, many queries | O(n) per query | **Binary lifting** or **Euler tour + RMQ** | O(log n) or O(1) per query | Preprocessing cost |
|
|
161
|
+
| Shortest path on DAG | Dijkstra | **Topo sort + relax** | O(V+E) | Only works on DAG |
|
|
162
|
+
| Detect cycle in linked list | hash visited | **Floyd's tortoise and hare** | O(1) space | Same big-O time, dramatic space win |
|
|
163
|
+
| Parallel reduction over n items | sequential fold | **Monoid + parallel scan** | O(n/p + log p) on p cores | Operation must be associative; verify it |
|
|
164
|
+
|
|
165
|
+
### Amortized and online algorithms
|
|
166
|
+
|
|
167
|
+
| Problem | Classical | Math technique | Win | Caveat |
|
|
168
|
+
|---|---|---|---|---|
|
|
169
|
+
| "Dynamic array push is expensive" | per-op O(n) on resize | **Amortized analysis (doubling)** | O(1) amortized | This is what `ArrayList` / `vec` already do; just defend it |
|
|
170
|
+
| Streaming median | re-sort | **Two heaps (max-heap + min-heap)** | O(log n) per insert | Maintain size invariant |
|
|
171
|
+
| Online interval scheduling | re-sort by deadline | **Greedy with priority queue** | O(log n) per arrival | Specific objective; check problem fit |
|
|
172
|
+
| Sliding-window max | O(n·k) | **Monotonic deque** | O(n) total | Window invariant subtle to maintain |
|
|
173
|
+
|
|
174
|
+
## Canonical example — counting distinct users
|
|
175
|
+
|
|
176
|
+
**Problem.** Count unique users seen across a 24-hour event stream. ~2B events/day, ~50M unique users. Reported on a dashboard, ±2% is acceptable.
|
|
177
|
+
|
|
178
|
+
<Bad>
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
// "Just use a Set" — silently OOMs the box at ~50M strings
|
|
182
|
+
const seen = new Set<string>();
|
|
183
|
+
for await (const event of stream) {
|
|
184
|
+
seen.add(event.userId);
|
|
185
|
+
}
|
|
186
|
+
return seen.size; // exact, but the process died at row 41M
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Or worse — proposed *with* a HyperLogLog "for performance" but plugged into the billing pipeline, which keys off the result. Billing then sees 49.7M instead of 50.0M users and a fraction never get charged.
|
|
190
|
+
|
|
191
|
+
</Bad>
|
|
192
|
+
|
|
193
|
+
<Good>
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
// Classical floor: O(unique) memory for an exact Set. At 50M strings × ~50B each, ~2.5GB.
|
|
197
|
+
// Why classical is not enough: dashboard box has 512MB and refreshes every minute.
|
|
198
|
+
// Technique: HyperLogLog (HLL).
|
|
199
|
+
// Mode: approximate. ε ≈ 1.04/√m. With m=2^14 registers → ~0.8% relative error.
|
|
200
|
+
// Trade: buys O(log log n)-bit space (~12KB); costs ±0.8% on the displayed count.
|
|
201
|
+
// When NOT to use: anything that flows into billing, primary keys, or per-user actions.
|
|
202
|
+
// Caller acceptance: confirmed — dashboard product owner accepts ±2%, written in PR.
|
|
203
|
+
|
|
204
|
+
import { createHLL } from 'hyperloglog-lite';
|
|
205
|
+
const hll = createHLL({ precision: 14 });
|
|
206
|
+
for await (const event of stream) {
|
|
207
|
+
hll.add(event.userId);
|
|
208
|
+
}
|
|
209
|
+
return hll.estimate(); // 49.6M ± 0.4M; dashboard reads ~50M
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
</Good>
|
|
213
|
+
|
|
214
|
+
The Bad version is not "no HLL" — it is "HLL without writing down ε and who tolerates it." The Good version is identical in technique but auditable: ε is in the comment, the caller is named, the disqualifier (billing) is explicit.
|
|
215
|
+
|
|
216
|
+
## Output discipline
|
|
217
|
+
|
|
218
|
+
Code that uses a math-level technique must include:
|
|
219
|
+
|
|
220
|
+
- One comment naming the technique with a doc link or one-line citation.
|
|
221
|
+
- The exact error parameters chosen (ε, δ, bits, dimensions, etc.) and why those values.
|
|
222
|
+
- A measured or asymptotic justification next to the chosen parameters.
|
|
223
|
+
- An exact-mode fallback path, if the caller might need it.
|
|
224
|
+
|
|
225
|
+
## When to escalate or redirect
|
|
226
|
+
|
|
227
|
+
- The bottleneck is I/O, not CPU/memory → go back to lemmaly rule 4; math will not help.
|
|
228
|
+
- You need bit-exact reproducibility → avoid floating FFT, randomized projections, and probabilistic structures.
|
|
229
|
+
- The result is consumed by a downstream system that assumes exact → keep classical or wrap with a validation pass.
|
|
230
|
+
- You need a correctness proof (not just a bound) → load **invariant-guard** after picking the technique.
|
|
231
|
+
|
|
232
|
+
## Rationalizations to watch for
|
|
233
|
+
|
|
234
|
+
These are real verbatim thoughts captured from a controlled test where the model noticed a probabilistic structure was needed but still shipped the naive answer:
|
|
235
|
+
|
|
236
|
+
| Excuse | Reality |
|
|
237
|
+
| --- | --- |
|
|
238
|
+
| "A `set` works — I'll flag the memory issue in a comment." | Noticing the problem is not solving it. If memory is the budget, ship the structure that respects it. |
|
|
239
|
+
| "Probabilistic structures sound fancy / academic." | Cloudflare runs Bloom filters in the request path. Redis ships HyperLogLog. These are production-tested, not academic. |
|
|
240
|
+
| "Approximate is risky — I'll do exact and let it OOM later." | Silent OOM at 3am is riskier than a stated 0.81% error. State the ε, pick parameters, ship. |
|
|
241
|
+
| "I'll just shard the set across machines." | Sharding multiplies your infra cost; HLL solves it in 12KB on one box. Ask whether you actually need exact. |
|
|
242
|
+
| "FFT is overkill for this." | True 99% of the time. But state the n. At n ≥ ~64 for polynomial mult, schoolbook is already losing. |
|
|
243
|
+
| "JL projection feels too lossy for embeddings." | At ε = 0.1, JL preserves pairwise distances within 10%. For ANN this is almost always fine — measure recall, do not eyeball. |
|
|
244
|
+
|
|
245
|
+
If any of these sound familiar mid-thought: stop, run the eight-step protocol, pick parameters with derivation.
|
|
246
|
+
|
|
247
|
+
## Red flags — STOP
|
|
248
|
+
|
|
249
|
+
- Proposing a probabilistic structure without stating ε and δ.
|
|
250
|
+
- Saying "we can use FFT here" without writing the n at which FFT actually beats schoolbook.
|
|
251
|
+
- Using `JSON.parse(JSON.stringify(...))` to deep-clone when `structuredClone` exists, then claiming it as an optimization.
|
|
252
|
+
- Recommending Strassen on a 100×100 matrix.
|
|
253
|
+
- Switching to approximate output without the caller having agreed to it.
|
|
254
|
+
- Naming a technique you cannot derive the bound for.
|
|
255
|
+
- Math optimization where n is small and not on a hot path.
|
|
256
|
+
- "Should be O(log n) on average" with no average-case argument.
|
|
257
|
+
|
|
258
|
+
All of these mean: back up, re-run the eight-step pre-proposal protocol, or fall back to lemmaly's classical playbook.
|
|
259
|
+
|
|
260
|
+
## Verification checklist
|
|
261
|
+
|
|
262
|
+
Before shipping code that uses a math-level technique:
|
|
263
|
+
|
|
264
|
+
- [ ] The technique is named (no "a smart approximation").
|
|
265
|
+
- [ ] If approximate: ε and δ (or the equivalent error parameter) are written in code or in the PR description.
|
|
266
|
+
- [ ] The caller has been identified and their tolerance for that error is stated.
|
|
267
|
+
- [ ] A one-line bound derivation is present (asymptotic or measured).
|
|
268
|
+
- [ ] At least one disqualifier ("when NOT to use this") is documented.
|
|
269
|
+
- [ ] An exact-mode fallback exists, OR a one-line note explains why exact is impossible.
|
|
270
|
+
- [ ] If randomized: the seed strategy is documented (fixed for reproducibility, or stated as non-deterministic).
|
|
271
|
+
- [ ] Downstream consumers that assume exactness (joins on this value, billing, auth, primary keys) have been audited.
|
|
272
|
+
|
|
273
|
+
Cannot check every box? The technique is not ready to ship. Keep classical, or stop and ask.
|
|
274
|
+
|
|
275
|
+
## The thesis, in one line
|
|
276
|
+
|
|
277
|
+
> **When classical algorithms hit their floor, mathematics still has another floor below. mathguard makes the model reach for it instead of accepting the first answer.**
|