vela_protocol/analysis/frontier_bound.rs
1//! Typed frontier bounds — the "current best / value-to-beat" of an open
2//! problem as a FIRST-CLASS object rather than prose buried in
3//! `assertion_text`.
4//!
5//! Today the Erdős atlas adapter (`atlas_adapters::read_erdos_deep`) folds each
6//! problem's `current_best` record into the free-text assertion. No consumer
7//! (foundry targets, attack ranking) can read it as a value-to-beat. This module
8//! gives the bound a typed shape that mirrors a per-family records catalog
9//! (`frontiers/<family>/records.json`):
10//! a per-problem record with the bound prose, an optional parsed numeric value,
11//! a direction (lower/upper), and an `accepted` flag that is `false` until a
12//! human attests it.
13//!
14//! The Erdős `current_best` field is prose (a sentence from the problem page),
15//! so `source_text` is authoritative and `value`/`direction` are a best-effort
16//! parse — never fabricated. A bound whose prose does not yield a clean
17//! `>=`/`<=`/numeric form keeps `value: None` and `direction: Unknown`, and the
18//! consumer falls back to the prose. This is the honest typed surface: the value
19//! is present only when it is mechanically extractable, the prose always is.
20
21use serde::{Deserialize, Serialize};
22
23/// The schema tag written into a typed bounds sidecar.
24pub const FRONTIER_BOUNDS_SCHEMA: &str = "vela.frontier-bounds.v1";
25
26/// Which side of the open quantity the bound constrains.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
28#[serde(rename_all = "lowercase")]
29pub enum BoundDirection {
30 /// A lower bound (e.g. a construction: "best known >= 7").
31 Lower,
32 /// An upper bound (e.g. an impossibility: "<= 12").
33 Upper,
34 /// The prose did not yield a direction; `source_text` is authoritative.
35 #[default]
36 Unknown,
37}
38
39impl BoundDirection {
40 pub fn as_str(self) -> &'static str {
41 match self {
42 BoundDirection::Lower => "lower",
43 BoundDirection::Upper => "upper",
44 BoundDirection::Unknown => "unknown",
45 }
46 }
47}
48
49/// One typed bound for an open problem — the value-to-beat a foundry / attack
50/// ranking reads. Mirrors a Sidon `bounds[]` row in shape (a `problem`
51/// reference, a typed `value`/`direction`, and an `accepted` flag), but keeps
52/// the authoritative `source_text` prose because the Erdős corpus states its
53/// records in words.
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55pub struct FrontierBound {
56 /// Problem reference, e.g. `"erdos/12"` (namespace/id).
57 pub problem: String,
58 /// Best-effort parsed numeric value, when the prose yields one cleanly.
59 /// `None` keeps the bound honest — the value was not mechanically extractable.
60 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub value: Option<f64>,
62 /// Which side the bound constrains (lower/upper/unknown).
63 pub direction: BoundDirection,
64 /// The authoritative prose the bound was read from (the problem's
65 /// `current_best` field). Always present.
66 pub source_text: String,
67 /// `false` until a human key-custody holder attests the bound. An adapter
68 /// only ever emits unattested (`false`) bounds.
69 pub accepted: bool,
70}
71
72impl FrontierBound {
73 /// Build a typed bound from a problem reference and the prose `current_best`
74 /// record. The numeric value + direction are a best-effort parse of the
75 /// prose; never fabricated (absent when not cleanly extractable). The bound
76 /// is unattested (`accepted: false`) — an adapter cannot accept its own work.
77 pub fn from_prose(problem: impl Into<String>, source_text: impl Into<String>) -> Self {
78 let source_text = source_text.into();
79 let (value, direction) = parse_bound_prose(&source_text);
80 FrontierBound {
81 problem: problem.into(),
82 value,
83 direction,
84 source_text,
85 accepted: false,
86 }
87 }
88}
89
90/// The bounds sidecar document — a typed mirror of a Sidon `bounds.json`,
91/// holding the per-problem typed bounds for a frontier/source.
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93pub struct FrontierBoundsDoc {
94 /// Always `vela.frontier-bounds.v1`.
95 pub schema: String,
96 /// The source/frontier these bounds were derived from (a tag, not a path).
97 pub source: String,
98 /// Free-form note describing provenance + the unattested-by-default rule.
99 #[serde(default, skip_serializing_if = "String::is_empty")]
100 pub note: String,
101 /// The typed bounds, deterministically ordered by `problem`.
102 pub bounds: Vec<FrontierBound>,
103}
104
105impl FrontierBoundsDoc {
106 pub fn new(
107 source: impl Into<String>,
108 note: impl Into<String>,
109 mut bounds: Vec<FrontierBound>,
110 ) -> Self {
111 bounds.sort_by(|a, b| a.problem.cmp(&b.problem));
112 FrontierBoundsDoc {
113 schema: FRONTIER_BOUNDS_SCHEMA.to_string(),
114 source: source.into(),
115 note: note.into(),
116 bounds,
117 }
118 }
119}
120
121/// Best-effort parse of a `current_best` prose record into (value, direction).
122///
123/// Honest by construction: returns `(Some(v), Lower|Upper)` only when the prose
124/// carries an explicit comparator (`>=`, `>`, `<=`, `<`, or LaTeX `\geq`/`\leq`/
125/// `\gg`/`\ll`) immediately governing a number; otherwise `(None, Unknown)`.
126/// Never guesses a direction from a bare number. The caller keeps `source_text`
127/// as the authoritative prose regardless.
128pub fn parse_bound_prose(text: &str) -> (Option<f64>, BoundDirection) {
129 // Normalize the common LaTeX comparators to ascii so one scanner handles both.
130 let norm = text
131 .replace("\\geqslant", ">=")
132 .replace("\\leqslant", "<=")
133 .replace("\\geq", ">=")
134 .replace("\\leq", "<=")
135 .replace("\\ge", ">=")
136 .replace("\\le", "<=")
137 .replace("\\gg", ">=")
138 .replace("\\ll", "<=");
139 let bytes = norm.as_bytes();
140 let mut i = 0;
141 while i < bytes.len() {
142 let (dir, skip) = match bytes[i] {
143 b'>' => {
144 let s = if bytes.get(i + 1) == Some(&b'=') {
145 2
146 } else {
147 1
148 };
149 (BoundDirection::Lower, s)
150 }
151 b'<' => {
152 let s = if bytes.get(i + 1) == Some(&b'=') {
153 2
154 } else {
155 1
156 };
157 (BoundDirection::Upper, s)
158 }
159 _ => {
160 i += 1;
161 continue;
162 }
163 };
164 // Scan forward past whitespace / LaTeX cruft to the first number.
165 let mut j = i + skip;
166 while j < bytes.len() && !bytes[j].is_ascii_digit() {
167 // Stop if we hit a letter that isn't LaTeX glue — the comparator
168 // governs a symbol, not a number (e.g. ">= N"); keep direction but
169 // no value.
170 if bytes[j].is_ascii_alphabetic() {
171 break;
172 }
173 j += 1;
174 }
175 if j < bytes.len() && bytes[j].is_ascii_digit() {
176 let start = j;
177 while j < bytes.len() && (bytes[j].is_ascii_digit() || bytes[j] == b'.') {
178 j += 1;
179 }
180 if let Ok(v) = norm[start..j].parse::<f64>() {
181 return (Some(v), dir);
182 }
183 }
184 // Comparator present but no clean number: record the direction, no value.
185 return (None, dir);
186 }
187 (None, BoundDirection::Unknown)
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193
194 #[test]
195 fn parses_lower_bound_with_geq() {
196 let (v, d) = parse_bound_prose("best known >= 7");
197 assert_eq!(v, Some(7.0));
198 assert_eq!(d, BoundDirection::Lower);
199 }
200
201 #[test]
202 fn parses_latex_geq() {
203 let (v, d) = parse_bound_prose("the best known bound is $\\geq 24$");
204 assert_eq!(v, Some(24.0));
205 assert_eq!(d, BoundDirection::Lower);
206 }
207
208 #[test]
209 fn parses_upper_bound() {
210 let (v, d) = parse_bound_prose("establishing an upper bound of <= 12");
211 assert_eq!(v, Some(12.0));
212 assert_eq!(d, BoundDirection::Upper);
213 }
214
215 #[test]
216 fn prose_without_comparator_is_unknown() {
217 let (v, d) = parse_bound_prose("Sawhney has provided the following proof.");
218 assert_eq!(v, None);
219 assert_eq!(d, BoundDirection::Unknown);
220 }
221
222 #[test]
223 fn comparator_over_symbol_keeps_direction_no_value() {
224 let (v, d) = parse_bound_prose("constructed such that |A| >= N");
225 assert_eq!(v, None);
226 assert_eq!(d, BoundDirection::Lower);
227 }
228
229 #[test]
230 fn from_prose_is_unattested_and_keeps_source_text() {
231 let b = FrontierBound::from_prose("erdos/12", "best known >= 7");
232 assert!(!b.accepted);
233 assert_eq!(b.problem, "erdos/12");
234 assert_eq!(b.source_text, "best known >= 7");
235 assert_eq!(b.value, Some(7.0));
236 assert_eq!(b.direction, BoundDirection::Lower);
237 }
238
239 #[test]
240 fn doc_round_trips_and_sorts_by_problem() {
241 let doc = FrontierBoundsDoc::new(
242 "erdos-problems",
243 "test",
244 vec![
245 FrontierBound::from_prose("erdos/20", "upper bound <= 5"),
246 FrontierBound::from_prose("erdos/3", "best known >= 9"),
247 ],
248 );
249 // sorted by problem (lexicographic): erdos/20 < erdos/3
250 assert_eq!(doc.bounds[0].problem, "erdos/20");
251 assert_eq!(doc.bounds[1].problem, "erdos/3");
252 let s = serde_json::to_string(&doc).unwrap();
253 let back: FrontierBoundsDoc = serde_json::from_str(&s).unwrap();
254 assert_eq!(doc, back);
255 assert_eq!(back.schema, FRONTIER_BOUNDS_SCHEMA);
256 }
257}