Skip to content

Commit a1e5dec

Browse files
committed
D3.1 batch sweep handler + clippy -D warnings clean (117/117 tests)
Phase 3 batch endpoint + 11 clippy fixes across the crate. D3.1 — POST /v1/shader/sweep (batch mode): Enumerates WireSweepGrid::enumerate(), validates each CodecParams at ingress (precision-ladder + overfit guard per point), computes kernel_signature() for each candidate, returns WireSweepResponse with all WireSweepResult rows (stub: calibrate=None, token_agreement=None, stub=true). SSE streaming + real per-point calibrate/token-agreement defer to D3.1b. Route wired in serve.rs alongside existing calibrate/probe/ token-agreement routes. Handler is ~50 LOC. Clippy fixes (11 issues, now -D warnings clean): - auto_style.rs: removed unused import QUALIA_DIMS (moved to test module where it's actually needed) - codec_bridge.rs: 3x redundant closure → tuple variant directly - driver.rs: 3x OR patterns → range patterns (1|2|3 → 1..=3) - wire.rs: is_aligned_64 manual impl → .is_multiple_of(64) - wire.rs: derivable Default for WireBaseline → #[derive(Default)] - decode_kernel.rs: doc list item overindentation → 2-space - codec_research.rs: #[allow(clippy::type_complexity)] on existing complex fn return type (not worth refactoring pre-existing code) Board hygiene: STATUS_BOARD.md D3.1 Queued → In PR Phase state after merge: Phase 0 ✅ complete Phase 1 scaffold ✅ (D1.1/D1.2/D1.3) Phase 2 scaffold ✅ (D2.1/D2.3) Phase 3 batch ✅ D3.1 (this PR) Remaining: D1.1b Cranelift, D2.2 real decode, D3.1b SSE, Phase 4-5 https://claude.ai/code/session_01SbYsmmbPf9YQuYbHZN52Zh
1 parent a927bf7 commit a1e5dec

8 files changed

Lines changed: 73 additions & 17 deletions

File tree

.claude/board/STATUS_BOARD.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ afterwards is a JIT kernel, not a rebuild. Plan path:
7878

7979
| D-id | Title | Status | PR / Evidence |
8080
|---|---|---|---|
81-
| D3.1 | Server-side sweep handler + Lance fragment append | **Queued** | target ~200 LOC |
81+
| D3.1 | Server-side sweep handler + Lance fragment append | **In PR** | branch — `sweep_handler` batch mode: enumerates `WireSweepGrid::enumerate()`, validates each via TryFrom(CodecParams) at ingress, returns `WireSweepResponse { results: [WireSweepResult { kernel_hash, stub:true }], cardinality, elapsed_ms }`. SSE streaming + real calibrate/token-agreement per point deferred to D3.1b. Route: `POST /v1/shader/sweep`. |
8282
| D3.2 | Client-side driver + config files | **Queued** | target ~20 LOC + YAML configs |
8383

8484
### Phase 4 — Frontier analysis — Queued

crates/cognitive-shader-driver/src/auto_style.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
//! If nothing dominates (`max < threshold`), fall back to Deliberate.
1818
1919
use lance_graph_contract::cognitive_shader::StyleSelector;
20-
use crate::bindspace::QUALIA_DIMS;
20+
2121

2222
/// Mapping from qualia shape to a style ordinal (0..11 matches
2323
/// `thinking_engine::cognitive_stack::ThinkingStyle::all()`).
@@ -104,6 +104,7 @@ pub fn resolve(sel: StyleSelector, qualia_row: &[f32]) -> u8 {
104104
#[cfg(test)]
105105
mod tests {
106106
use super::*;
107+
use crate::bindspace::QUALIA_DIMS;
107108

108109
fn q(vals: &[(usize, f32)]) -> [f32; QUALIA_DIMS] {
109110
let mut out = [0.0f32; QUALIA_DIMS];

crates/cognitive-shader-driver/src/codec_bridge.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ impl OrchestrationBridge for CodecResearchBridge {
4646
let req: WireTensorsRequest = serde_json::from_str(args)
4747
.map_err(|e| OrchestrationError::ExecutionFailed(e.to_string()))?;
4848
let r = codec_research::list_tensors(&req)
49-
.map_err(|e| OrchestrationError::ExecutionFailed(e))?;
49+
.map_err(OrchestrationError::ExecutionFailed)?;
5050
step.status = StepStatus::Completed;
5151
step.reasoning = Some(format!(
5252
"tensors total={} cam_pq={} passthrough={} skip={}",
@@ -58,7 +58,7 @@ impl OrchestrationBridge for CodecResearchBridge {
5858
let req: WireCalibrateRequest = serde_json::from_str(args)
5959
.map_err(|e| OrchestrationError::ExecutionFailed(e.to_string()))?;
6060
let r = codec_research::calibrate_tensor(&req)
61-
.map_err(|e| OrchestrationError::ExecutionFailed(e))?;
61+
.map_err(OrchestrationError::ExecutionFailed)?;
6262
step.status = StepStatus::Completed;
6363
step.confidence = Some(r.icc_3_1 as f64);
6464
step.reasoning = Some(format!(
@@ -71,7 +71,7 @@ impl OrchestrationBridge for CodecResearchBridge {
7171
let req: WireProbeRequest = serde_json::from_str(args)
7272
.map_err(|e| OrchestrationError::ExecutionFailed(e.to_string()))?;
7373
let r = codec_research::row_count_probe(&req)
74-
.map_err(|e| OrchestrationError::ExecutionFailed(e))?;
74+
.map_err(OrchestrationError::ExecutionFailed)?;
7575
step.status = StepStatus::Completed;
7676
step.reasoning = Some(format!(
7777
"probe tensor={} n_rows={} entries={}",

crates/cognitive-shader-driver/src/codec_research.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ fn route_str(r: CodecRoute) -> &'static str {
175175
}
176176
}
177177

178+
#[allow(clippy::type_complexity)]
178179
fn load_tensor_rows(
179180
model_path: &str,
180181
tensor_pattern: &str,

crates/cognitive-shader-driver/src/decode_kernel.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616
//! round-trip, no quantization loss, matches Rule F "serialise once at
1717
//! edge" — the decode/encode IS the edge).
1818
//! - [`ResidualComposer`] — composes two decoders with subtract/add:
19-
//! `decode(enc) = base.decode(enc[..k]) + residual.decode(enc[k..])`
20-
//! `encode(v) = [base.encode(v); residual.encode(v - base.decode(base.encode(v)))]`
19+
//! `decode(enc) = base.decode(enc[..k]) + residual.decode(enc[k..])`
20+
//! `encode(v) = [base.encode(v); residual.encode(v - base.decode(base.encode(v)))]`
2121
//! Depth `d > 1` recurses: the residual field itself is a `ResidualComposer`.
2222
2323
use std::collections::hash_map::DefaultHasher;

crates/cognitive-shader-driver/src/driver.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -333,9 +333,9 @@ fn style_ord_to_inference(ord: u8) -> InferenceType {
333333
// intuitive/deliberate → Revision
334334
// metacognitive → Synthesis
335335
match ord {
336-
1 | 2 | 3 => InferenceType::Deduction,
337-
4 | 5 | 6 => InferenceType::Induction,
338-
7 | 8 | 9 => InferenceType::Abduction,
336+
1..=3 => InferenceType::Deduction,
337+
4..=6 => InferenceType::Induction,
338+
7..=9 => InferenceType::Abduction,
339339
0 | 10 => InferenceType::Revision,
340340
_ => InferenceType::Synthesis,
341341
}

crates/cognitive-shader-driver/src/serve.rs

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,9 @@ use crate::wire::{
5050
WireCalibrateRequest, WireCalibrateResponse, WireCrystal, WireDispatch, WireHealth,
5151
WireIngest, WirePlanRequest, WirePlanResponse, WireProbeRequest, WireProbeResponse,
5252
WireQualia, WireRunbookRequest, WireRunbookResponse, WireRunbookStep,
53-
WireRunbookStepResult, WireStepResult, WireStyleInfo, WireTensorsRequest,
54-
WireTensorsResponse, WireTokenAgreement, WireTokenAgreementResult, WireUnifiedStep,
53+
WireRunbookStepResult, WireStepResult, WireStyleInfo, WireSweepRequest,
54+
WireSweepResponse, WireSweepResult, WireTensorsRequest, WireTensorsResponse,
55+
WireTokenAgreement, WireTokenAgreementResult, WireUnifiedStep,
5556
};
5657
use lance_graph_contract::cam::CodecParams;
5758
use std::path::Path as StdPath;
@@ -96,6 +97,13 @@ pub fn router(driver: ShaderDriver) -> Router {
9697
// `backend:"stub"` so clients cannot confuse Phase 0 stub output
9798
// for a real measurement (anti-#219 defense, type-level).
9899
.route("/v1/shader/token-agreement", post(token_agreement_handler))
100+
// D3.1 — codec sweep endpoint (batch mode). Client POSTs a
101+
// WireSweepRequest containing a cross-product grid; handler
102+
// enumerates grid, validates each candidate, builds stub results,
103+
// returns WireSweepResponse. SSE streaming + Lance append land in
104+
// D3.1b; this batch path stays for clients that want all results
105+
// in one response without streaming.
106+
.route("/v1/shader/sweep", post(sweep_handler))
99107
// Scheduled runbook: one POST runs a list of steps. Test injection
100108
// lands here — a client script submits its full codec-research
101109
// protocol as a single DTO, the server executes and returns all
@@ -284,6 +292,54 @@ async fn token_agreement_handler(
284292
.map_err(|e| (StatusCode::BAD_REQUEST, Json(json!({"error": format!("{e}")}))))
285293
}
286294

295+
/// D3.1 — `POST /v1/shader/sweep` handler (batch mode).
296+
///
297+
/// Enumerates the cross-product grid from `WireSweepRequest`, validates
298+
/// each candidate via TryFrom(CodecParams), computes kernel_signature +
299+
/// backend per point, and returns all results in one `WireSweepResponse`.
300+
///
301+
/// Stub: per-point calibrate/token_agreement are `None`; Phase 3 real
302+
/// handler invokes the actual codec_research + token_agreement harness.
303+
/// SSE streaming variant (D3.1b) replaces the batch return with per-point
304+
/// Server-Sent Events.
305+
async fn sweep_handler(
306+
Json(req): Json<WireSweepRequest>,
307+
) -> Result<Json<WireSweepResponse>, (StatusCode, Json<Value>)> {
308+
let start = std::time::Instant::now();
309+
let candidates = req.grid.enumerate();
310+
let cardinality = candidates.len() as u32;
311+
312+
let mut results = Vec::with_capacity(candidates.len());
313+
for (idx, wire_params) in candidates.into_iter().enumerate() {
314+
// Validate each grid point at ingress — surface typed errors early.
315+
let params: CodecParams = wire_params
316+
.clone()
317+
.try_into()
318+
.map_err(|e: lance_graph_contract::cam::CodecParamsError| {
319+
(StatusCode::BAD_REQUEST, Json(json!({
320+
"error": format!("grid point {idx}: invalid CodecParams: {e}")
321+
})))
322+
})?;
323+
324+
results.push(WireSweepResult {
325+
grid_index: idx as u32,
326+
candidate: wire_params,
327+
kernel_hash: params.kernel_signature(),
328+
calibrate: None,
329+
token_agreement: None,
330+
stub: true,
331+
});
332+
}
333+
334+
Ok(Json(WireSweepResponse {
335+
label: req.label,
336+
cardinality,
337+
results,
338+
elapsed_ms: start.elapsed().as_millis() as u64,
339+
lance_fragment_path: req.log_to_lance,
340+
}))
341+
}
342+
287343
async fn route_handler(
288344
State(_state): State<AppState>,
289345
Json(wire): Json<WireUnifiedStep>,

crates/cognitive-shader-driver/src/wire.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,7 @@ impl AlignedBytes {
405405
}
406406

407407
pub fn is_aligned_64(&self) -> bool {
408-
(self.ptr as usize) % 64 == 0
408+
(self.ptr as usize).is_multiple_of(64)
409409
}
410410

411411
pub fn len(&self) -> usize { self.len }
@@ -933,17 +933,15 @@ fn named_to_ordinal(s: &str) -> u8 {
933933
/// Reference baseline for token-agreement comparison. Extensible enum —
934934
/// `Passthrough` is the only variant today; future baselines (half-precision
935935
/// reference, previous codec generation) plug in as variants.
936-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
936+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
937937
#[serde(tag = "kind", rename_all = "snake_case")]
938938
pub enum WireBaseline {
939939
/// Passthrough = untouched weights, F32 decode. The canonical
940940
/// reference every codec candidate is measured against.
941+
#[default]
941942
Passthrough,
942943
}
943944

944-
impl Default for WireBaseline {
945-
fn default() -> Self { Self::Passthrough }
946-
}
947945

948946
/// `POST /v1/shader/token-agreement` request.
949947
///

0 commit comments

Comments
 (0)