1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//! Spectral energy-slope constant `mu` (PSP-8 System 2 / Gate G).
//!
//! For the quadratic residual energy `V(x) = x^T A x` with `A = B^T W B`, the
//! energy-slope constant `mu = 2 * lambda_min+(A)` is combinatorial rather than
//! embedding-dependent. In the identity-restriction case `A` reduces to the
//! weighted Laplacian of the verification graph and `mu` is twice its algebraic
//! connectivity (Fiedler value).
//!
//! `mu` is a diagnostic, not an input to the acceptance gate. It SHALL be
//! computed off the critical path and SHALL NOT block dispatch or the gate.
//! This module is therefore a pure, side-effect-free computation a runtime can
//! schedule on graph-revision commit or asynchronously.
use nalgebra::DMatrix;
use serde::{Deserialize, Serialize};
use crate::error::{check_positive_finite, Result, SdkError};
/// One weighted edge of the verification graph. An edge `(i, j)` couples the
/// local states of two nodes/verifiers; its weight is the residual weight
/// `w_e > 0`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VerificationEdge {
pub src: usize,
pub dst: usize,
pub weight: f64,
}
impl VerificationEdge {
pub fn new(src: usize, dst: usize, weight: f64) -> Self {
Self { src, dst, weight }
}
}
/// A verification graph over `node_count` local-state components.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct VerificationGraph {
pub node_count: usize,
pub edges: Vec<VerificationEdge>,
}
impl VerificationGraph {
pub fn new(node_count: usize) -> Self {
Self {
node_count,
edges: Vec::new(),
}
}
pub fn with_edge(mut self, src: usize, dst: usize, weight: f64) -> Self {
self.edges.push(VerificationEdge::new(src, dst, weight));
self
}
pub fn add_edge(&mut self, src: usize, dst: usize, weight: f64) {
self.edges.push(VerificationEdge::new(src, dst, weight));
}
/// Build the weighted graph Laplacian `A = B^T W B` (identity-restriction
/// case), an `n x n` symmetric positive-semidefinite matrix.
fn laplacian(&self) -> Result<DMatrix<f64>> {
if self.node_count == 0 {
return Err(SdkError::Spectral("verification graph has no nodes".into()));
}
let n = self.node_count;
let mut a = DMatrix::<f64>::zeros(n, n);
for e in &self.edges {
if e.src >= n || e.dst >= n {
return Err(SdkError::Spectral(format!(
"edge ({}, {}) out of range for {} nodes",
e.src, e.dst, n
)));
}
if e.src == e.dst {
return Err(SdkError::Spectral(format!("self-loop at node {}", e.src)));
}
check_positive_finite(e.weight, "edge weight")?;
let w = e.weight;
a[(e.src, e.src)] += w;
a[(e.dst, e.dst)] += w;
a[(e.src, e.dst)] -= w;
a[(e.dst, e.src)] -= w;
}
Ok(a)
}
/// Sorted ascending eigenvalues of the Laplacian.
fn eigenvalues_sorted(&self) -> Result<Vec<f64>> {
let a = self.laplacian()?;
// The Laplacian is symmetric; use the symmetric eigensolver.
let mut eigs: Vec<f64> = a.symmetric_eigenvalues().iter().copied().collect();
eigs.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
Ok(eigs)
}
/// Smallest non-zero eigenvalue `lambda_min+(A)` of the Laplacian.
///
/// Returns `None` when the graph is disconnected or empty of edges (the
/// spectral gap is then zero, so `mu` is not informative). Eigenvalues
/// within `tol` of zero are treated as zero.
pub fn smallest_nonzero_eigenvalue(&self, tol: f64) -> Result<Option<f64>> {
let eigs = self.eigenvalues_sorted()?;
Ok(eigs.into_iter().find(|&v| v > tol))
}
/// The spectral energy-slope constant `mu = 2 * lambda_min+(A)`.
///
/// Returns `None` for a disconnected verification graph, where the gap is
/// zero and `mu` is uninformative (a disconnected verifier component cannot
/// be driven to consensus by the others).
pub fn mu(&self, tol: f64) -> Result<Option<f64>> {
Ok(self
.smallest_nonzero_eigenvalue(tol)?
.map(|lambda| 2.0 * lambda))
}
/// Algebraic connectivity (Fiedler value) — the smallest non-zero
/// eigenvalue; `mu = 2 * fiedler`.
pub fn fiedler_value(&self, tol: f64) -> Result<Option<f64>> {
self.smallest_nonzero_eigenvalue(tol)
}
/// Change in `mu` produced by adding a candidate verifier edge.
///
/// An independent verifier that raises the spectral gap yields a positive
/// delta; a redundant verifier that does not yields ~0. Used to distinguish
/// independent from redundant verifiers (PSP-8 System 2).
pub fn edge_mu_sensitivity(
&self,
src: usize,
dst: usize,
weight: f64,
tol: f64,
) -> Result<f64> {
Ok(self.edge_sensitivity(src, dst, weight, tol)?.gap_delta)
}
/// Both of Lemma 2's levers for a candidate verifier edge (PSP-9
/// system 17): a new check helps insofar as it **raises**
/// `λ⁺_min(A)` *or shrinks* `ker(A)` — the safe set is exactly
/// `ker(A)`. For a coding workspace the second lever is the common
/// case: a verifier for a property nothing previously constrained
/// removes an unverified direction from the nominal safe set without
/// moving the gap at all. A verifier that changes neither is redundancy
/// in the exact sense Corollary 5.2 prices probabilistically.
pub fn edge_sensitivity(
&self,
src: usize,
dst: usize,
weight: f64,
tol: f64,
) -> Result<EdgeSensitivity> {
let gap_before = self.mu(tol)?.unwrap_or(0.0);
let nullity_before = self.nullity(tol)?;
let mut candidate = self.clone();
candidate.add_edge(src, dst, weight);
let gap_after = candidate.mu(tol)?.unwrap_or(0.0);
let nullity_after = candidate.nullity(tol)?;
Ok(EdgeSensitivity {
gap_delta: gap_after - gap_before,
nullity_before,
nullity_after,
})
}
/// Dimension of `ker(L)` — the unverified directions of the nominal
/// safe set. Eigenvalues within `tol` of zero count as zero.
pub fn nullity(&self, tol: f64) -> Result<usize> {
Ok(self
.eigenvalues_sorted()?
.into_iter()
.filter(|e| e.abs() <= tol)
.count())
}
}
/// Both deltas for one candidate edge (Paper II Lemma 2).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EdgeSensitivity {
/// Change in the spectral gap `λ⁺_min`.
pub gap_delta: f64,
/// `dim ker(A)` before and after: a shrink is Lemma 2's second lever.
pub nullity_before: usize,
pub nullity_after: usize,
}
impl EdgeSensitivity {
/// Whether the candidate verifier earns its cost by either lever.
pub fn earns_cost(&self, tol: f64) -> bool {
self.gap_delta > tol || self.nullity_after < self.nullity_before
}
}
#[cfg(test)]
mod tests {
use super::*;
const TOL: f64 = 1e-9;
#[test]
fn path_graph_has_expected_fiedler_value() {
// Unweighted path on 3 nodes: Laplacian eigenvalues are 0, 1, 3.
let g = VerificationGraph::new(3)
.with_edge(0, 1, 1.0)
.with_edge(1, 2, 1.0);
let fiedler = g.fiedler_value(TOL).unwrap().unwrap();
assert!((fiedler - 1.0).abs() < 1e-6, "fiedler={fiedler}");
let mu = g.mu(TOL).unwrap().unwrap();
assert!((mu - 2.0).abs() < 1e-6, "mu={mu}");
}
#[test]
fn complete_triangle_connectivity() {
// Unweighted triangle: eigenvalues 0, 3, 3 -> fiedler = 3.
let g = VerificationGraph::new(3)
.with_edge(0, 1, 1.0)
.with_edge(1, 2, 1.0)
.with_edge(0, 2, 1.0);
let fiedler = g.fiedler_value(TOL).unwrap().unwrap();
assert!((fiedler - 3.0).abs() < 1e-6, "fiedler={fiedler}");
}
#[test]
fn disconnected_graph_has_no_spectral_gap() {
// Two isolated edges over 4 nodes -> two zero eigenvalues, but the
// second smallest is still 0 -> disconnected.
let g = VerificationGraph::new(4)
.with_edge(0, 1, 1.0)
.with_edge(2, 3, 1.0);
// smallest nonzero exists (the within-component value) but the graph is
// disconnected: there are two zero eigenvalues. We detect disconnection
// by counting zeros.
let eigs = g.eigenvalues_sorted().unwrap();
let zeros = eigs.iter().filter(|&&v| v.abs() <= TOL).count();
assert_eq!(
zeros, 2,
"disconnected graph has multiplicity-2 zero eigenvalue"
);
}
#[test]
fn independent_verifier_raises_mu_more_than_redundant() {
// Base: path 0-1-2.
let g = VerificationGraph::new(3)
.with_edge(0, 1, 1.0)
.with_edge(1, 2, 1.0);
// Adding the closing edge 0-2 (independent cross-check) raises the gap.
let independent = g.edge_mu_sensitivity(0, 2, 1.0, TOL).unwrap();
// Strengthening an existing coupling 0-1 (redundant) raises it less.
let redundant = g.edge_mu_sensitivity(0, 1, 1.0, TOL).unwrap();
assert!(independent > 0.0);
assert!(
independent >= redundant,
"independent={independent} redundant={redundant}"
);
}
#[test]
fn weighted_edges_scale_gap() {
let g1 = VerificationGraph::new(2).with_edge(0, 1, 1.0);
let g2 = VerificationGraph::new(2).with_edge(0, 1, 2.0);
let m1 = g1.mu(TOL).unwrap().unwrap();
let m2 = g2.mu(TOL).unwrap().unwrap();
assert!((m2 - 2.0 * m1).abs() < 1e-6);
}
#[test]
fn rejects_self_loop_and_out_of_range() {
assert!(VerificationGraph::new(2)
.with_edge(0, 0, 1.0)
.mu(TOL)
.is_err());
assert!(VerificationGraph::new(2)
.with_edge(0, 5, 1.0)
.mu(TOL)
.is_err());
}
#[test]
fn a_connecting_verifier_shrinks_the_nullspace_even_without_moving_mu() {
// Two disconnected components: nullity 2. Connecting them removes an
// unverified direction — Lemma 2's second lever.
let g = VerificationGraph::new(4)
.with_edge(0, 1, 1.0)
.with_edge(2, 3, 1.0);
assert_eq!(g.nullity(TOL).unwrap(), 2);
let sensitivity = g.edge_sensitivity(1, 2, 1.0, TOL).unwrap();
assert_eq!(sensitivity.nullity_before, 2);
assert_eq!(sensitivity.nullity_after, 1);
assert!(sensitivity.earns_cost(TOL));
}
#[test]
fn a_redundant_verifier_changes_neither_lever() {
// Doubling an existing edge with negligible weight: no rank change,
// negligible gap change — redundancy in the Corollary 5.2 sense.
let g = VerificationGraph::new(2).with_edge(0, 1, 1.0);
let sensitivity = g.edge_sensitivity(0, 1, 1e-12, TOL).unwrap();
assert_eq!(sensitivity.nullity_before, sensitivity.nullity_after);
assert!(!sensitivity.earns_cost(1e-6));
}
}