-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.rs
More file actions
1523 lines (1366 loc) · 51.8 KB
/
Copy pathserver.rs
File metadata and controls
1523 lines (1366 loc) · 51.8 KB
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2025 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
// SPDX-License-Identifier: MPL-2.0
//! HTTP API server for ECHIDNA
//!
//! Provides REST API and WebSocket endpoints for theorem proving
use anyhow::Result;
use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
};
use colored::Colorize;
use echidna::agent::meta_controller::{MetaController, Plan};
use echidna::agent::AgenticGoal;
use echidna::core::{Goal, ProofState, Tactic, TacticResult, Term};
use echidna::diagnostics::HealthStatus;
use echidna::dispatch::ProverDispatcher;
use echidna::provers::ProverOutcome;
use echidna::verification::StatisticsTracker;
use echidna::{ProverBackend, ProverConfig, ProverKind};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, RwLock};
use tower_http::cors::CorsLayer;
use tracing::{debug, info, instrument};
/// Application state shared across handlers
#[derive(Clone)]
struct AppState {
/// Active proof sessions (session_id -> ProofSession)
sessions: Arc<RwLock<HashMap<String, Arc<Mutex<ProofSession>>>>>,
/// HTTP client for Julia ML API
ml_client: Client,
/// Julia ML API base URL
ml_api_url: String,
/// MetaController — shared (prover × coprocessor) planner with persistent
/// StatisticsTracker. Survives request boundaries so the Bayesian routing
/// state accumulates across the server's lifetime. All handlers that
/// perform goal-aware dispatch share this single instance.
meta_controller: Arc<MetaController>,
/// Shared proof-outcome statistics used by MetaController for Bayesian
/// routing and exported to Julia for GNN online learning.
stats: Arc<RwLock<StatisticsTracker>>,
/// Prover dispatcher for trust-hardening pipeline and health monitoring
dispatcher: Arc<ProverDispatcher>,
}
/// A proof session
struct ProofSession {
prover: Box<dyn ProverBackend>,
state: Option<ProofState>,
history: Vec<String>,
}
const DEFAULT_ML_API_URL: &str = "http://127.0.0.1:8090";
/// Start the HTTP server
pub async fn start_server(port: u16, host: String, enable_cors: bool) -> Result<()> {
// Create HTTP client for Julia ML API
let ml_client = Client::builder().timeout(Duration::from_secs(10)).build()?;
let ml_api_url =
std::env::var("ECHIDNA_ML_API_URL").unwrap_or_else(|_| DEFAULT_ML_API_URL.to_string());
// Security: Validate that the ML API URL is either local or explicitly allowed
if !ml_api_url.starts_with("http://127.0.0.1") && !ml_api_url.starts_with("http://localhost") {
info!("⚠ Untrusted ML API URL detected: {}. Baseline security policy requires local or trusted endpoint.", ml_api_url);
}
// Test Julia ML connection
match ml_client.get(format!("{}/health", ml_api_url)).send().await {
Ok(resp) if resp.status().is_success() => {
info!("✓ Connected to Julia ML API at {}", ml_api_url);
},
_ => {
info!(
"⚠ Julia ML API not available at {} (will use fallback)",
ml_api_url
);
},
}
// Shared stats tracker — MetaController uses it for Bayesian routing;
// the background GNN sync task pushes snapshots to Julia for online learning.
let stats = Arc::new(RwLock::new(StatisticsTracker::new()));
let meta_controller = Arc::new(MetaController::new().with_stats(stats.clone()));
// Create prover dispatcher with default configuration.
// When compiled with --features verisim, attach the VeriSimDB writer so
// every HTTP proof attempt (including parse failures) feeds the S4 learning
// loop. The writer runs fire-and-forget; a VeriSimDB outage never blocks
// or alters a dispatch result.
let dispatcher = {
let d = ProverDispatcher::new();
#[cfg(feature = "verisim")]
let d = {
let url = std::env::var("VERISIM_URL")
.unwrap_or_else(|_| "http://localhost:8080".to_string());
info!("✓ VeriSim writer attached at {}", url);
d.with_verisim_writer(&url)
};
Arc::new(d)
};
info!("✓ Initialized prover dispatcher for trust-hardening pipeline");
let state = AppState {
sessions: Arc::new(RwLock::new(HashMap::new())),
ml_client,
ml_api_url,
meta_controller,
stats,
dispatcher,
};
// GNN training sync — background task that pushes accumulated proof-outcome
// stats to Julia's /training/update endpoint every 60 seconds.
// Only fires when >= 10 new outcomes have accumulated since the last push,
// so idle servers incur no traffic. Errors are logged at debug level and
// do not affect the main server loop (fire-and-forget).
{
let sync_stats = state.stats.clone();
let sync_client = state.ml_client.clone();
let sync_url = state.ml_api_url.clone();
tokio::spawn(async move {
let mut last_push_count: u64 = 0;
let mut interval = tokio::time::interval(Duration::from_secs(60));
interval.tick().await; // consume the immediate first tick; wait 60s before first push
loop {
interval.tick().await;
let (total, records) = {
let guard = sync_stats.read().await;
(guard.total_attempts(), guard.export_records())
};
if total < last_push_count + 10 || records.is_empty() {
continue;
}
last_push_count = total;
let url = format!("{}/training/update", sync_url);
let payload = json!({ "records": records });
match sync_client.post(&url).json(&payload).send().await {
Ok(resp) if resp.status().is_success() => {
info!(
"GNN training sync: {} records pushed to Julia",
records.len()
);
},
Ok(resp) => {
debug!("GNN training sync: Julia returned {}", resp.status());
},
Err(e) => {
debug!("GNN training sync: Julia unavailable ({})", e);
},
}
}
});
}
// Build router
let mut app = Router::new()
// Groove discovery endpoint — returns capability manifest for service mesh.
// See Groove.idr echidnaManifest for the canonical ABI definition.
.route("/.well-known/groove", get(groove_manifest))
// REST API endpoints
.route("/api/health", get(health_check))
.route("/api/diagnostics/health", get(diagnostics_health_handler))
.route("/api/provers", get(list_provers))
.route("/api/prove", post(prove_handler))
.route("/api/verify", post(verify_handler))
.route("/api/verify_parallel", post(verify_parallel_handler))
.route("/api/verify_raw", post(verify_raw_handler))
.route("/api/suggest", post(suggest_handler))
.route("/api/search", get(search_handler))
.route("/api/session/create", post(create_session))
.route("/api/session/:id/state", get(get_session_state))
.route("/api/session/:id/apply", post(apply_tactic_handler))
.route("/api/session/:id/tree", get(get_proof_tree))
// Additional UI-specific endpoints
.route("/api/agent/plan", post(agent_plan_handler))
.route("/api/aspect-tags", get(get_aspect_tags))
.route("/api/tactics/suggest", post(suggest_tactics_ui))
.route("/api/theorems/search", get(search_theorems_ui))
// WebSocket endpoint (disabled - requires axum ws feature)
// .route("/ws/interactive", get(websocket_handler))
.with_state(state);
// Add CORS if enabled
if enable_cors {
app = app.layer(CorsLayer::permissive());
}
// Bind server
let addr: SocketAddr = format!("{}:{}", host, port).parse()?;
println!(
"{}",
"╔═══════════════════════════════════════════════════════════╗".cyan()
);
println!(
"{}",
"║ ECHIDNA HTTP API Server ║"
.cyan()
.bold()
);
println!(
"{}",
"╚═══════════════════════════════════════════════════════════╝".cyan()
);
println!();
println!(
"Server listening on: {}",
format!("https://{}", addr).green().bold()
);
println!();
println!("{}", "Endpoints:".yellow().bold());
println!(" GET /.well-known/groove - Groove discovery manifest");
println!(" GET /api/health - Health check");
println!(" GET /api/provers - List available provers");
println!(" POST /api/prove - Prove a theorem");
println!(" POST /api/verify - Verify a proof");
println!(" POST /api/suggest - Get tactic suggestions");
println!(" GET /api/search?q=<pattern> - Search theorems");
println!(" POST /api/session/create - Create proof session");
println!(" GET /api/session/:id/state - Get session state");
println!(" POST /api/session/:id/apply - Apply tactic to session");
println!(" WS /ws/interactive - WebSocket live proof session");
println!();
println!("Press Ctrl+C to stop the server");
println!();
// Start server
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}
// ========== Agent Planning ==========
/// Request to `POST /api/agent/plan`.
///
/// Asks the MetaController to plan a proof attempt: which prover to use,
/// which coprocessor preconditions to run first, and the Bayesian-estimated
/// timeout. The response is a `Plan` that callers can inspect before
/// deciding whether to submit a full `/api/verify` or `/api/prove` request.
///
/// `aspects` drive the coprocessor routing (e.g. `"arithmetic.factorisation"`
/// triggers a Math precondition; `"algebra.groebner.basis"` triggers Singular).
/// `preferred_prover` and `candidates` are both optional — omitting both lets
/// the Pareto ranker pick freely from Z3 as the default.
#[derive(Debug, Deserialize)]
struct AgentPlanRequest {
/// Goal aspect tags (e.g. `["arithmetic.factorisation", "crypto.hash.sha256"]`).
#[serde(default)]
aspects: Vec<String>,
/// Client's preferred prover, if any. Overridden by Pareto ranking when
/// `candidates` is non-empty.
preferred_prover: Option<ProverKind>,
/// Candidate provers to rank. When empty, `preferred_prover` (or Z3)
/// is selected directly without Pareto scoring.
#[serde(default)]
candidates: Vec<ProverKind>,
/// Default timeout hint (ms) used when no historical data is available.
#[serde(default = "default_timeout_ms")]
default_timeout_ms: u64,
}
fn default_timeout_ms() -> u64 {
30_000
}
/// `POST /api/agent/plan` — return a MetaController plan for the given goal aspects.
///
/// Does not execute any provers or coprocessors; it only plans. Callers use
/// the returned `coprocessor_preconditions` to understand what computational
/// preparation the system recommends before submitting the proof content.
async fn agent_plan_handler(
State(state): State<AppState>,
Json(req): Json<AgentPlanRequest>,
) -> impl IntoResponse {
// Build a minimal AgenticGoal from the request metadata. The goal target
// is a placeholder (`Term::Const("?")`) because planning doesn't inspect
// the proof content — only the aspects and prover preferences matter here.
use echidna::agent::Priority;
let goal = AgenticGoal {
goal: Goal {
id: uuid::Uuid::new_v4().to_string(),
target: Term::Const("?".to_string()),
hypotheses: vec![],
},
priority: Priority::Medium,
attempts: 0,
max_attempts: 3,
preferred_prover: req.preferred_prover,
aspects: req.aspects,
parent: None,
};
let plan: Plan = if req.candidates.is_empty() {
state.meta_controller.plan(&goal).await
} else {
use echidna::verification::confidence::TrustLevel;
state
.meta_controller
.plan_with_pareto(
&goal,
&req.candidates,
req.default_timeout_ms,
TrustLevel::Level2,
)
.await
};
Json(json!({
"prover": format!("{:?}", plan.prover),
"estimated_timeout_ms": plan.estimated_timeout_ms,
"rationale": plan.rationale,
"coprocessor_preconditions": plan.coprocessor_preconditions
.iter()
.map(|p| json!({
"kind": format!("{:?}", p.kind),
"aspect": p.aspect,
}))
.collect::<Vec<_>>(),
}))
}
// ========== Groove Discovery ==========
/// Groove capability manifest for ECHIDNA.
///
/// Returns the service's capabilities in the standard Groove format so that
/// Gossamer, PanLL, and other groove-aware systems can discover ECHIDNA by
/// probing GET /.well-known/groove. See Groove.idr echidnaManifest for the
/// canonical ABI definition.
///
/// Capabilities offered:
/// - theorem-proving: Multi-backend theorem proving (48 provers)
///
/// Capabilities consumed:
/// - octad-storage (VeriSimDB): Persist proof artifacts as octad entities
/// - scanning (Hypatia): Trigger re-verification after codebase changes
async fn groove_manifest() -> Json<serde_json::Value> {
let core_count = echidna::ProverKind::all_core().len();
let advertised_count = echidna::ProverKind::all().len();
Json(json!({
"groove_version": "1",
"service_id": "echidna",
"service_version": env!("CARGO_PKG_VERSION"),
"capabilities": {
"theorem_proving": {
"type": "theorem-proving",
"description": format!(
"Neurosymbolic theorem proving — {} core / {} advertised prover backends",
core_count, advertised_count
),
"protocol": "http",
"endpoint": "/api/prove",
"requires_auth": false,
"panel_compatible": true
}
},
"consumes": ["octad-storage", "scanning"],
"endpoints": {
"provers": "/api/provers",
"prove": "/api/prove",
"verify": "/api/verify",
"health": "/api/health"
},
"health": "/api/health",
"applicability": ["individual", "team"]
}))
}
// ========== REST API Handlers ==========
/// Health check endpoint
async fn health_check() -> Json<HealthResponse> {
Json(HealthResponse {
status: "ok".to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
})
}
/// Detailed diagnostics health endpoint
/// Returns full HealthStatus snapshot from dispatcher with prover metrics and degradation mode
async fn diagnostics_health_handler(State(app_state): State<AppState>) -> Json<HealthStatus> {
let health = app_state.dispatcher.health_status();
Json(health)
}
/// List available provers
async fn list_provers() -> Json<ProversResponse> {
let provers = ProverKind::all_core()
.into_iter()
.map(|prover| ProverInfo {
name: format!("{:?}", prover),
tier: prover.tier(),
complexity: prover.complexity(),
})
.collect();
Json(ProversResponse { provers })
}
/// Prove theorem endpoint
async fn prove_handler(
State(app_state): State<AppState>,
Json(req): Json<ProveRequest>,
) -> Result<Json<ProveResponse>, AppError> {
info!("Prove request for prover: {:?}", req.prover);
// Route through the full dispatch pipeline when the verisim feature is
// active. This fires the VeriSimDB writer for every HTTP proof (parse
// failures and final results), closing the S4 learning loop. The writer
// runs fire-and-forget — a VeriSimDB outage never blocks or alters a
// result. Response shape (success/goals/message) is preserved.
#[cfg(feature = "verisim")]
{
let result = app_state
.dispatcher
.verify_proof(req.prover, &req.content)
.await
.map_err(|e| AppError::VerificationError(e.to_string()))?;
return Ok(Json(ProveResponse {
success: result.verified,
goals: result.goals_remaining,
message: result.message,
}));
}
// Non-verisim path: direct factory + prover call (existing behaviour).
#[cfg(not(feature = "verisim"))]
{
// Create prover
let config = ProverConfig {
timeout: req.timeout.unwrap_or(300),
neural_enabled: req.neural.unwrap_or(true),
..ProverConfig::default()
};
let prover = echidna::provers::ProverFactory::create(req.prover, config)
.map_err(|e| AppError::InternalError(e.to_string()))?;
// Parse proof
let state = prover
.parse_string(&req.content)
.await
.map_err(|e| AppError::ParseError(e.to_string()))?;
// Fail-fast on empty parse results (fixes false-positive: unrecognised
// content produced an empty ProofState that re-exported to an empty file
// which the backend prover then happily accepted).
if is_empty_state(&state) && !req.content.trim().is_empty() {
let outcome = ProverOutcome::InvalidInput {
reason: "Parse produced no goals, theorems, definitions, or axioms — \
content not recognised by the selected prover backend"
.to_string(),
location: None,
};
app_state
.dispatcher
.record_prover_result(req.prover, &outcome, 0);
return Ok(Json(ProveResponse {
success: false,
goals: 0,
message: "Parse produced no goals, theorems, definitions, or axioms — \
content not recognised by the selected prover backend"
.to_string(),
}));
}
// Verify proof and record health metrics
let verify_start = Instant::now();
let valid = prover
.verify_proof(&state)
.await
.map_err(|e| AppError::VerificationError(e.to_string()))?;
let verify_elapsed_ms = verify_start.elapsed().as_millis() as u64;
let outcome = if valid {
ProverOutcome::Proved {
elapsed_ms: verify_elapsed_ms,
}
} else {
ProverOutcome::NoProofFound {
elapsed_ms: verify_elapsed_ms,
reason: Some("Proof verification failed".to_string()),
}
};
app_state
.dispatcher
.record_prover_result(req.prover, &outcome, verify_elapsed_ms);
Ok(Json(ProveResponse {
success: valid,
goals: state.goals.len(),
message: if valid {
"Proof verified successfully".to_string()
} else {
"Proof verification failed".to_string()
},
}))
}
}
/// Verify proof endpoint
async fn verify_handler(Json(req): Json<VerifyRequest>) -> Result<Json<VerifyResponse>, AppError> {
info!("Verify request for prover: {:?}", req.prover);
// SMT query mode: when users send raw SMT-LIB with (check-sat) to Z3/CVC5,
// run passthrough evaluation instead of proof-obligation negation semantics.
if should_passthrough_smt_eval(&req) {
let Json(raw) = verify_raw_handler(Json(req.clone())).await?;
let smt_status =
extract_smt_status(&raw.stdout).or_else(|| extract_smt_status(&raw.stderr));
let goals_remaining = if matches!(smt_status.as_deref(), Some("unsat")) {
0
} else {
1
};
let outcome_str = if raw.valid {
"PROVED"
} else {
"NO_PROOF_FOUND"
};
return Ok(Json(VerifyResponse {
valid: raw.valid,
outcome: outcome_str.to_string(),
goals_remaining,
tactics_used: 0,
mode: Some("smt-query".to_string()),
smt_status,
}));
}
// Create prover
let config = ProverConfig::default();
let prover = echidna::provers::ProverFactory::create(req.prover, config)
.map_err(|e| AppError::InternalError(e.to_string()))?;
// Parse proof — parse errors surface as INVALID_INPUT in the outcome.
// We intentionally don't forward the raw error message to the response
// body (it may leak internal paths or prover internals).
let state = match prover.parse_string(&req.content).await {
Ok(s) => s,
Err(_) => {
return Ok(Json(VerifyResponse {
valid: false,
outcome: "INVALID_INPUT".to_string(),
goals_remaining: 0,
tactics_used: 0,
mode: None,
smt_status: None,
}));
},
};
// Fail-fast on empty parse results (see prove_handler comment).
if is_empty_state(&state) && !req.content.trim().is_empty() {
return Ok(Json(VerifyResponse {
valid: false,
outcome: "INVALID_INPUT".to_string(),
goals_remaining: 0,
tactics_used: 0,
mode: None,
smt_status: None,
}));
}
// NOTE: a richer `.check()` call returning a `ProverOutcome` taxonomy
// lived here until 2026-04-17 but the typed-outcome module was never
// committed (see z3.rs note). Reverted to `verify_proof()` so the HTTP
// API is no worse than it was before the dropped refactor; the outcome
// string is a two-valued approximation of the planned taxonomy.
// Tracked in AI-WORK-todo.md phase-2 followups.
let valid = prover
.verify_proof(&state)
.await
.map_err(|e| AppError::VerificationError(e.to_string()))?;
Ok(Json(VerifyResponse {
valid,
outcome: if valid {
"PROVED".to_string()
} else {
"NO_PROOF_FOUND".to_string()
},
goals_remaining: if valid { 0 } else { state.goals.len() },
tactics_used: state.proof_script.len(),
mode: None,
smt_status: None,
}))
}
/// `/api/verify_parallel` — L2 Chapel parallel dispatch.
///
/// Fans out to multiple prover backends simultaneously (when the `chapel`
/// Cargo feature is compiled in and the Chapel runtime is available).
/// Returns the first successful result through the standard trust pipeline.
/// Falls back to sequential `select_prover` heuristic when Chapel is
/// unavailable. Callers that want a specific prover should use `/api/verify`.
async fn verify_parallel_handler(
Json(req): Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, AppError> {
let content = req
.get("content")
.and_then(|v| v.as_str())
.ok_or_else(|| AppError::BadRequest("Missing 'content' field".to_string()))?;
info!("verify_parallel request ({} bytes)", content.len());
let dispatcher = ProverDispatcher::new();
let result = dispatcher
.verify_proof_parallel(content)
.await
.map_err(|e| AppError::VerificationError(e.to_string()))?;
Ok(Json(serde_json::json!({
"valid": result.verified,
"outcome": result.outcome.status_str(),
"provers_used": result.provers_used,
"trust_level": result.trust_level as u8,
"proof_time_ms": result.proof_time_ms,
"goals_remaining": result.goals_remaining,
"cross_checked": result.cross_checked,
"message": result.message,
})))
}
/// `/api/verify_raw` — writes the original `content` to a temp file with
/// the right extension for the prover, then invokes the backend binary
/// directly. Bypasses `parse_string`/`export` round-trip entirely — the
/// content you send is the content the prover sees.
///
/// This is the real fix for the parse+export round-trip bug: no
/// information is lost between the wire and the prover binary.
/// Currently supports: z3, cvc5, coq, lean, agda, idris2, vampire,
/// eprover. Other provers fall through to the legacy verify_handler path.
#[instrument(skip(req))]
async fn verify_raw_handler(
Json(req): Json<VerifyRequest>,
) -> Result<Json<VerifyRawResponse>, AppError> {
use tokio::process::Command;
info!("Verify_raw request for prover: {:?}", req.prover);
if req.content.trim().is_empty() {
return Ok(Json(VerifyRawResponse {
valid: false,
exit_code: -1,
stdout: String::new(),
stderr: String::new(),
message: "empty content".to_string(),
}));
}
type Interpret = fn(i32, &str, &str) -> (bool, String);
let (ext, program, args, interpret): (&str, &str, Vec<String>, Interpret) = match req.prover {
echidna::provers::ProverKind::Z3 => (
"smt2",
"z3",
vec!["-smt2".to_string()],
|rc, stdout, _stderr| {
let produced = stdout.contains("sat")
|| stdout.contains("unsat")
|| stdout.contains("unknown");
(rc == 0 && produced, format!("exit={} smt-output", rc))
},
),
echidna::provers::ProverKind::CVC5 => ("smt2", "cvc5", vec![], |rc, stdout, _stderr| {
let produced =
stdout.contains("sat") || stdout.contains("unsat") || stdout.contains("unknown");
(rc == 0 && produced, format!("exit={} smt-output", rc))
}),
echidna::provers::ProverKind::Coq => (
"v",
"coqc",
vec!["-q".to_string()],
|rc, _stdout, _stderr| (rc == 0, format!("exit={}", rc)),
),
echidna::provers::ProverKind::Lean => ("lean", "lean", vec![], |rc, _stdout, _stderr| {
(rc == 0, format!("exit={}", rc))
}),
echidna::provers::ProverKind::Agda => ("agda", "agda", vec![], |rc, _stdout, _stderr| {
(rc == 0, format!("exit={}", rc))
}),
echidna::provers::ProverKind::Idris2 => (
"idr",
"idris2",
vec!["--check".to_string()],
|rc, _stdout, _stderr| (rc == 0, format!("exit={}", rc)),
),
echidna::provers::ProverKind::Vampire => (
"p",
"vampire",
vec!["--mode".to_string(), "casc".to_string()],
|rc, stdout, _stderr| {
let theorem = stdout.contains("SZS status Theorem")
|| stdout.contains("SZS status Unsatisfiable");
(rc == 0 || theorem, "szs-status".to_string())
},
),
echidna::provers::ProverKind::EProver => (
"p",
"eprover",
vec!["--auto-schedule".to_string()],
|rc, stdout, _stderr| {
let theorem = stdout.contains("SZS status Theorem")
|| stdout.contains("SZS status Unsatisfiable")
|| stdout.contains("SZS status ContradictoryAxioms");
(rc == 0 && theorem, "szs-status".to_string())
},
),
_ => {
return Ok(Json(VerifyRawResponse {
valid: false,
exit_code: -1,
stdout: String::new(),
stderr: String::new(),
message: format!(
"verify_raw not yet implemented for {:?} — use /api/verify",
req.prover
),
}));
},
};
// Write content to a unique temp file with the right extension.
let tmpdir = std::env::temp_dir().join(format!("echidna_verify_raw_{}", std::process::id()));
if let Err(e) = tokio::fs::create_dir_all(&tmpdir).await {
return Ok(Json(VerifyRawResponse {
valid: false,
exit_code: -1,
stdout: String::new(),
stderr: String::new(),
message: format!("tmpdir create failed: {}", e),
}));
}
let filename = format!("Input.{}", ext);
let path = tmpdir.join(&filename);
if let Err(e) = tokio::fs::write(&path, req.content.as_bytes()).await {
return Ok(Json(VerifyRawResponse {
valid: false,
exit_code: -1,
stdout: String::new(),
stderr: String::new(),
message: format!("write failed: {}", e),
}));
}
// Run the prover. cd to tmpdir for provers that care about module
// name = filename (agda, coq, idris2, lean).
let mut cmd = Command::new(program);
cmd.current_dir(&tmpdir);
for arg in &args {
cmd.arg(arg);
}
cmd.arg(&filename);
let output_result = cmd.output().await;
// Best-effort cleanup; ignore errors.
let _ = tokio::fs::remove_dir_all(&tmpdir).await;
match output_result {
Ok(output) => {
let exit_code = output.status.code().unwrap_or(-1);
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
let (valid, message) = interpret(exit_code, &stdout, &stderr);
Ok(Json(VerifyRawResponse {
valid,
exit_code,
stdout: stdout.chars().take(1024).collect(),
stderr: stderr.chars().take(1024).collect(),
message,
}))
},
Err(e) => Ok(Json(VerifyRawResponse {
valid: false,
exit_code: -1,
stdout: String::new(),
stderr: String::new(),
message: format!("spawn failed: {} (is the '{}' binary on PATH?)", e, program),
})),
}
}
/// Return true if the parsed ProofState contains no meaningful structure.
/// Used to detect the parse+export round-trip bug: a prover backend's
/// `parse_string` returns an empty state on unrecognised input, then
/// `verify_proof` regenerates an empty file which the real backend binary
/// then accepts vacuously (false positive).
fn is_empty_state(state: &echidna::core::ProofState) -> bool {
state.goals.is_empty()
&& state.context.theorems.is_empty()
&& state.context.axioms.is_empty()
&& state.context.definitions.is_empty()
&& state.context.variables.is_empty()
}
fn should_passthrough_smt_eval(req: &VerifyRequest) -> bool {
matches!(req.prover, ProverKind::Z3 | ProverKind::CVC5)
&& req.content.to_ascii_lowercase().contains("(check-sat")
}
fn extract_smt_status(text: &str) -> Option<String> {
let lower = text.to_ascii_lowercase();
if lower.contains("unsat") {
Some("unsat".to_string())
} else if lower.contains("sat") {
Some("sat".to_string())
} else if lower.contains("unknown") {
Some("unknown".to_string())
} else {
None
}
}
/// Get tactic suggestions
async fn suggest_handler(
State(state): State<AppState>,
Json(req): Json<SuggestRequest>,
) -> Result<Json<SuggestResponse>, AppError> {
info!("Suggest request for prover: {:?}", req.prover);
// Try Julia ML API first
let julia_req = json!({
"goal": req.content,
"prover": format!("{:?}", req.prover),
"top_k": req.limit.unwrap_or(5)
});
match state
.ml_client
.post(format!("{}/suggest", state.ml_api_url))
.json(&julia_req)
.send()
.await
{
Ok(resp) if resp.status().is_success() => {
if let Ok(ml_resp) = resp.json::<serde_json::Value>().await {
if let Some(suggestions_arr) = ml_resp["suggestions"].as_array() {
let suggestions: Vec<String> = suggestions_arr
.iter()
.filter_map(|s| s["tactic"].as_str().map(|t| t.to_string()))
.collect();
if !suggestions.is_empty() {
info!("✓ Got {} ML suggestions", suggestions.len());
return Ok(Json(SuggestResponse { suggestions }));
}
}
}
},
_ => {
info!("ML API unavailable, using prover fallback");
},
}
// Fallback: Use prover's built-in suggestions
let config = ProverConfig::default();
let prover = echidna::provers::ProverFactory::create(req.prover, config)
.map_err(|e| AppError::InternalError(e.to_string()))?;
let state = prover
.parse_string(&req.content)
.await
.map_err(|e| AppError::ParseError(e.to_string()))?;
let tactics = prover
.suggest_tactics(&state, req.limit.unwrap_or(5))
.await
.map_err(|e| AppError::InternalError(e.to_string()))?;
let suggestions = tactics.iter().map(|t| format!("{:?}", t)).collect();
Ok(Json(SuggestResponse { suggestions }))
}
/// Search theorems
async fn search_handler(
Query(params): Query<HashMap<String, String>>,
) -> Result<Json<SearchResponse>, AppError> {
let pattern = params
.get("q")
.ok_or_else(|| AppError::BadRequest("Missing query parameter 'q'".to_string()))?;
let prover_name = params.get("prover");
info!(
"Search request: pattern={}, prover={:?}",
pattern, prover_name
);
let mut all_results = Vec::new();
// Determine which provers to search
let provers: Vec<ProverKind> = if let Some(name) = prover_name {
vec![parse_prover_kind(name)?]
} else {
vec![
ProverKind::Agda,
ProverKind::Coq,
ProverKind::Lean,
ProverKind::Isabelle,
]
};
// Search each prover
for prover_kind in provers {
let config = ProverConfig::default();
if let Ok(prover) = echidna::provers::ProverFactory::create(prover_kind, config) {
if let Ok(results) = prover.search_theorems(pattern).await {
all_results.extend(results);
}
}
}
// Cross-prover layer (see main.rs::search_command for rationale).
// Folds VeriSimDB matches into the same response so REST clients
// see results from backends without native search commands too.
let verisim_url =
std::env::var("VERISIM_URL").unwrap_or_else(|_| "http://localhost:8080".to_string());
if let Ok(cross) = echidna::vcl_ut::cross_prover_search_names(&verisim_url, pattern, 50).await {
all_results.extend(cross);
}
let count = all_results.len();
Ok(Json(SearchResponse {
results: all_results,
count,
}))
}
/// Create a new proof session
async fn create_session(
State(state): State<AppState>,
Json(req): Json<CreateSessionRequest>,
) -> Result<Json<CreateSessionResponse>, AppError> {
info!("Creating session for prover: {:?}", req.prover);
// Create prover
let config = ProverConfig::default();
let prover = echidna::provers::ProverFactory::create(req.prover, config)
.map_err(|e| AppError::InternalError(e.to_string()))?;
// Create session
let session_id = uuid::Uuid::new_v4().to_string();
let session = ProofSession {
prover,
state: None,
history: Vec::new(),
};
// Store session
state
.sessions
.write()
.await
.insert(session_id.clone(), Arc::new(Mutex::new(session)));
Ok(Json(CreateSessionResponse { session_id }))
}
/// Get session state
async fn get_session_state(
State(state): State<AppState>,
Path(session_id): Path<String>,
) -> Result<Json<SessionStateResponse>, AppError> {
let sessions = state.sessions.read().await;
let session = sessions
.get(&session_id)
.ok_or_else(|| AppError::NotFound(format!("Session not found: {}", session_id)))?;
let session = session.lock().await;
Ok(Json(SessionStateResponse {
goals: session
.state
.as_ref()
.map(|s| s.goals.len())
.unwrap_or_else(|| 0),
complete: session
.state
.as_ref()
.map(|s| s.is_complete())