ruvector-tiny-dancer-node 2.3.0

Node.js bindings for Tiny Dancer neural routing via NAPI-RS
Documentation
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
//! Node.js bindings for Tiny Dancer neural routing via NAPI-RS
//!
//! High-performance Rust neural routing with zero-copy buffer sharing,
//! async/await support, and complete TypeScript type definitions.

#![allow(clippy::all)]
#![allow(clippy::pedantic)]

use napi::bindgen_prelude::*;
use napi_derive::napi;
use parking_lot::RwLock;
use ruvector_tiny_dancer_core::{
    types::{
        Candidate as CoreCandidate, RouterConfig as CoreRouterConfig,
        RoutingDecision as CoreRoutingDecision, RoutingRequest as CoreRoutingRequest,
        RoutingResponse as CoreRoutingResponse,
    },
    Router as CoreRouter,
};
use std::collections::HashMap;
use std::sync::Arc;

/// Router configuration
#[napi(object)]
#[derive(Debug, Clone)]
pub struct RouterConfig {
    /// Model path
    pub model_path: String,
    /// Confidence threshold (0.0 to 1.0)
    pub confidence_threshold: Option<f64>,
    /// Maximum uncertainty (0.0 to 1.0)
    pub max_uncertainty: Option<f64>,
    /// Enable circuit breaker
    pub enable_circuit_breaker: Option<bool>,
    /// Circuit breaker threshold
    pub circuit_breaker_threshold: Option<u32>,
    /// Enable quantization
    pub enable_quantization: Option<bool>,
    /// Database path
    pub database_path: Option<String>,
}

impl From<RouterConfig> for CoreRouterConfig {
    fn from(config: RouterConfig) -> Self {
        CoreRouterConfig {
            model_path: config.model_path,
            confidence_threshold: config.confidence_threshold.unwrap_or(0.85) as f32,
            max_uncertainty: config.max_uncertainty.unwrap_or(0.15) as f32,
            enable_circuit_breaker: config.enable_circuit_breaker.unwrap_or(true),
            circuit_breaker_threshold: config.circuit_breaker_threshold.unwrap_or(5),
            enable_quantization: config.enable_quantization.unwrap_or(true),
            database_path: config.database_path,
            // VoI escalation gate (ADR-331) is not yet exposed over NAPI.
            voi: None,
        }
    }
}

/// Candidate for routing
#[napi(object)]
#[derive(Clone)]
pub struct Candidate {
    /// Candidate ID
    pub id: String,
    /// Embedding vector
    pub embedding: Float32Array,
    /// Metadata (JSON string)
    pub metadata: Option<String>,
    /// Creation timestamp
    pub created_at: Option<i64>,
    /// Access count
    pub access_count: Option<u32>,
    /// Success rate (0.0 to 1.0)
    pub success_rate: Option<f64>,
}

impl Candidate {
    fn to_core(&self) -> Result<CoreCandidate> {
        let metadata: HashMap<String, serde_json::Value> = if let Some(ref meta_str) = self.metadata
        {
            serde_json::from_str(meta_str)
                .map_err(|e| Error::from_reason(format!("Invalid metadata JSON: {}", e)))?
        } else {
            HashMap::new()
        };

        Ok(CoreCandidate {
            id: self.id.clone(),
            embedding: self.embedding.to_vec(),
            metadata,
            created_at: self
                .created_at
                .unwrap_or_else(|| chrono::Utc::now().timestamp()),
            access_count: self.access_count.unwrap_or(0) as u64,
            success_rate: self.success_rate.unwrap_or(0.0) as f32,
        })
    }
}

/// Routing request
#[napi(object)]
pub struct RoutingRequest {
    /// Query embedding
    pub query_embedding: Float32Array,
    /// Candidates to score
    pub candidates: Vec<Candidate>,
    /// Optional metadata (JSON string)
    pub metadata: Option<String>,
}

impl RoutingRequest {
    fn to_core(&self) -> Result<CoreRoutingRequest> {
        let candidates: Result<Vec<CoreCandidate>> =
            self.candidates.iter().map(|c| c.to_core()).collect();

        let metadata = if let Some(ref meta_str) = self.metadata {
            Some(
                serde_json::from_str(meta_str)
                    .map_err(|e| Error::from_reason(format!("Invalid metadata JSON: {}", e)))?,
            )
        } else {
            None
        };

        Ok(CoreRoutingRequest {
            query_embedding: self.query_embedding.to_vec(),
            candidates: candidates?,
            metadata,
        })
    }
}

/// Routing decision
#[napi(object)]
#[derive(Debug, Clone)]
pub struct RoutingDecision {
    /// Candidate ID
    pub candidate_id: String,
    /// Confidence score (0.0 to 1.0)
    pub confidence: f64,
    /// Whether to use lightweight model
    pub use_lightweight: bool,
    /// Uncertainty estimate (0.0 to 1.0)
    pub uncertainty: f64,
}

impl From<CoreRoutingDecision> for RoutingDecision {
    fn from(decision: CoreRoutingDecision) -> Self {
        Self {
            candidate_id: decision.candidate_id,
            confidence: decision.confidence as f64,
            use_lightweight: decision.use_lightweight,
            uncertainty: decision.uncertainty as f64,
        }
    }
}

/// Routing response
#[napi(object)]
#[derive(Debug, Clone)]
pub struct RoutingResponse {
    /// Routing decisions
    pub decisions: Vec<RoutingDecision>,
    /// Total inference time in microseconds
    pub inference_time_us: u32,
    /// Number of candidates processed
    pub candidates_processed: u32,
    /// Feature engineering time in microseconds
    pub feature_time_us: u32,
}

impl From<CoreRoutingResponse> for RoutingResponse {
    fn from(response: CoreRoutingResponse) -> Self {
        Self {
            decisions: response.decisions.into_iter().map(Into::into).collect(),
            inference_time_us: response.inference_time_us as u32,
            candidates_processed: response.candidates_processed as u32,
            feature_time_us: response.feature_time_us as u32,
        }
    }
}

/// Tiny Dancer neural router
#[napi]
pub struct Router {
    inner: Arc<RwLock<CoreRouter>>,
}

#[napi]
impl Router {
    /// Create a new router with configuration
    ///
    /// # Example
    /// ```javascript
    /// const router = new Router({
    ///   modelPath: './models/fastgrnn.safetensors',
    ///   confidenceThreshold: 0.85,
    ///   maxUncertainty: 0.15,
    ///   enableCircuitBreaker: true
    /// });
    /// ```
    #[napi(constructor)]
    pub fn new(config: RouterConfig) -> Result<Self> {
        let core_config: CoreRouterConfig = config.into();
        let router = CoreRouter::new(core_config)
            .map_err(|e| Error::from_reason(format!("Failed to create router: {}", e)))?;

        Ok(Self {
            inner: Arc::new(RwLock::new(router)),
        })
    }

    /// Route a request through the neural routing system
    ///
    /// Returns routing decisions with confidence scores and model recommendations
    ///
    /// # Example
    /// ```javascript
    /// const response = await router.route({
    ///   queryEmbedding: new Float32Array([0.1, 0.2, ...]),
    ///   candidates: [
    ///     { id: '1', embedding: new Float32Array([...]) },
    ///     { id: '2', embedding: new Float32Array([...]) }
    ///   ]
    /// });
    /// console.log('Top decision:', response.decisions[0]);
    /// console.log('Inference time:', response.inferenceTimeUs, 'μs');
    /// ```
    #[napi]
    pub async fn route(&self, request: RoutingRequest) -> Result<RoutingResponse> {
        let core_request = request.to_core()?;
        let router = self.inner.clone();

        tokio::task::spawn_blocking(move || {
            let router = router.read();
            router.route(core_request)
        })
        .await
        .map_err(|e| Error::from_reason(format!("Task failed: {}", e)))?
        .map_err(|e| Error::from_reason(format!("Routing failed: {}", e)))
        .map(Into::into)
    }

    /// Reload the model from disk (hot-reload)
    ///
    /// # Example
    /// ```javascript
    /// await router.reloadModel();
    /// ```
    #[napi]
    pub async fn reload_model(&self) -> Result<()> {
        let router = self.inner.clone();

        tokio::task::spawn_blocking(move || {
            let router = router.read();
            router.reload_model()
        })
        .await
        .map_err(|e| Error::from_reason(format!("Task failed: {}", e)))?
        .map_err(|e| Error::from_reason(format!("Model reload failed: {}", e)))
    }

    /// Check circuit breaker status
    ///
    /// Returns true if the circuit is closed (healthy), false if open (unhealthy)
    ///
    /// # Example
    /// ```javascript
    /// const isHealthy = router.circuitBreakerStatus();
    /// ```
    #[napi]
    pub fn circuit_breaker_status(&self) -> Option<bool> {
        let router = self.inner.read();
        router.circuit_breaker_status()
    }
}

/// Get the version of the Tiny Dancer library
#[napi]
pub fn version() -> String {
    env!("CARGO_PKG_VERSION").to_string()
}

/// Hello function for testing bindings
#[napi]
pub fn hello() -> String {
    "Hello from Tiny Dancer Node.js bindings!".to_string()
}

/// One DRACO training row: a query embedding and the quality each model achieved
/// on it (model id → quality, 0..1). Matches `@metaharness/router`'s row shape.
#[napi(object)]
pub struct DracoRowJs {
    pub embedding: Vec<f64>,
    pub scores: std::collections::HashMap<String, f64>,
}

/// Options for `trainRouter`.
#[napi(object)]
pub struct TrainRouterOptions {
    /// Where to write the trained `.safetensors` model.
    pub output_path: String,
    /// Input feature dimension (must equal the embedding length).
    pub input_dim: u32,
    /// Hidden dimension (default 12).
    pub hidden_dim: Option<u32>,
    /// Training epochs (default 40).
    pub epochs: Option<u32>,
    /// Learning rate (default 0.05).
    pub learning_rate: Option<f64>,
    /// DRACO label tolerance: cheap model is "good enough" within this of the best
    /// (default 0.05).
    pub tolerance: Option<f64>,
}

/// Result of `trainRouter`.
#[napi(object)]
pub struct TrainRouterResult {
    pub epochs_run: u32,
    pub train_loss: f64,
    pub train_accuracy: f64,
    pub val_accuracy: f64,
    pub model_path: String,
    pub model_bytes: u32,
}

/// Train a FastGRNN router from a DRACO dataset and write it to a
/// `.safetensors` file consumable by `new Router({ modelPath })`.
///
/// ```javascript
/// const res = await trainRouter(rows, { haiku: 1, opus: 15 }, {
///   outputPath: './router.safetensors', inputDim: 8, epochs: 40,
/// });
/// const router = new Router({ modelPath: res.modelPath });
/// ```
#[napi]
pub async fn train_router(
    rows: Vec<DracoRowJs>,
    prices: std::collections::HashMap<String, f64>,
    options: TrainRouterOptions,
) -> Result<TrainRouterResult> {
    use ruvector_tiny_dancer_core::model::{FastGRNN, FastGRNNConfig};
    use ruvector_tiny_dancer_core::training::{DracoRow, Trainer, TrainingConfig, TrainingDataset};

    tokio::task::spawn_blocking(move || -> std::result::Result<TrainRouterResult, String> {
        let core_rows: Vec<DracoRow> = rows
            .into_iter()
            .map(|r| DracoRow {
                embedding: r.embedding.into_iter().map(|v| v as f32).collect(),
                scores: r.scores.into_iter().map(|(k, v)| (k, v as f32)).collect(),
            })
            .collect();
        let core_prices: std::collections::HashMap<String, f32> =
            prices.into_iter().map(|(k, v)| (k, v as f32)).collect();

        let tolerance = options.tolerance.unwrap_or(0.05) as f32;
        let dataset = TrainingDataset::from_draco(&core_rows, &core_prices, tolerance)
            .map_err(|e| format!("dataset: {e}"))?;

        let model_config = FastGRNNConfig {
            input_dim: options.input_dim as usize,
            hidden_dim: options.hidden_dim.unwrap_or(12) as usize,
            output_dim: 1,
            ..Default::default()
        };
        let train_config = TrainingConfig {
            learning_rate: options.learning_rate.unwrap_or(0.05) as f32,
            epochs: options.epochs.unwrap_or(40) as usize,
            early_stopping_patience: None,
            l2_reg: 0.0,
            ..Default::default()
        };

        let mut model = FastGRNN::new(model_config.clone()).map_err(|e| format!("model: {e}"))?;
        let metrics = Trainer::new(&model_config, train_config)
            .train(&mut model, &dataset)
            .map_err(|e| format!("train: {e}"))?;
        model
            .save(&options.output_path)
            .map_err(|e| format!("save: {e}"))?;

        let last = metrics.last().ok_or_else(|| "no metrics".to_string())?;
        let model_bytes = std::fs::metadata(&options.output_path)
            .map(|m| m.len() as u32)
            .unwrap_or(0);

        Ok(TrainRouterResult {
            epochs_run: metrics.len() as u32,
            train_loss: last.train_loss as f64,
            train_accuracy: last.train_accuracy as f64,
            val_accuracy: last.val_accuracy as f64,
            model_path: options.output_path,
            model_bytes,
        })
    })
    .await
    .map_err(|e| Error::from_reason(format!("Task failed: {}", e)))?
    .map_err(Error::from_reason)
}

/// Score a query embedding with a trained FastGRNN model (raw forward pass).
///
/// Loads the `.safetensors` produced by {@link train_router} and runs the model
/// directly on `embedding` (which must match the model's `input_dim`). Returns
/// the sigmoid output in 0..1 — high means "the cheap model is good enough"
/// (route to the cheaper model); low means route to a stronger model.
///
/// This is the inference path that matches `trainRouter` (trained on raw
/// embeddings); it does not run `Router`'s feature engineering.
#[napi]
pub async fn score(model_path: String, embedding: Vec<f64>) -> Result<f64> {
    use ruvector_tiny_dancer_core::model::FastGRNN;

    tokio::task::spawn_blocking(move || -> std::result::Result<f64, String> {
        let model = FastGRNN::load(&model_path).map_err(|e| format!("load: {e}"))?;
        let feats: Vec<f32> = embedding.into_iter().map(|v| v as f32).collect();
        let s = model
            .forward(&feats, None)
            .map_err(|e| format!("forward: {e}"))?;
        Ok(s as f64)
    })
    .await
    .map_err(|e| Error::from_reason(format!("Task failed: {}", e)))?
    .map_err(Error::from_reason)
}