Skip to content
This repository was archived by the owner on Aug 22, 2026. It is now read-only.

Commit 9b49795

Browse files
committed
style: apply rustfmt
1 parent 2069d09 commit 9b49795

12 files changed

Lines changed: 256 additions & 92 deletions

File tree

crates/bench/src/runner.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,9 @@ pub async fn run_benchmark(
115115
entries: &[BenchmarkEntry],
116116
config: &BenchmarkConfig,
117117
) -> Result<BenchmarkResults> {
118-
let embedder: Arc<dyn mempalace_core::embed::Embedder> =
119-
resolve_embedder(&config.embed_model).map_err(anyhow::Error::msg)?.into();
118+
let embedder: Arc<dyn mempalace_core::embed::Embedder> = resolve_embedder(&config.embed_model)
119+
.map_err(anyhow::Error::msg)?
120+
.into();
120121

121122
let mut metrics = BenchmarkMetrics::new(config.ks.clone());
122123
let mut per_type_results: std::collections::HashMap<_, _> = Default::default();
@@ -223,8 +224,11 @@ mod tests {
223224

224225
#[tokio::test]
225226
async fn test_rank_corpus_returns_sorted_indices() {
226-
let embedder: Arc<dyn mempalace_core::embed::Embedder> =
227-
Arc::from(resolve_embedder("all-MiniLM-L6-v2").map_err(anyhow::Error::msg).expect("resolve_embedder should succeed"));
227+
let embedder: Arc<dyn mempalace_core::embed::Embedder> = Arc::from(
228+
resolve_embedder("all-MiniLM-L6-v2")
229+
.map_err(anyhow::Error::msg)
230+
.expect("resolve_embedder should succeed"),
231+
);
228232
let docs = vec![
229233
"I worked on the auth migration today".to_string(),
230234
"I still remember the happy high school experiences".to_string(),

crates/core/src/cli.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -988,7 +988,10 @@ fn cmd_search(
988988
Some("vector") => Some(crate::palace::FusionMode::Vector),
989989
None => None,
990990
Some(other) => {
991-
eprintln!("error: unknown fusion mode '{}' (expected: vector, ppr, hybrid)", other);
991+
eprintln!(
992+
"error: unknown fusion mode '{}' (expected: vector, ppr, hybrid)",
993+
other
994+
);
992995
return Err(anyhow::anyhow!("invalid fusion mode"));
993996
}
994997
};

crates/core/src/embed/tract.rs

Lines changed: 71 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use anyhow::Context;
1010
use async_trait::async_trait;
1111
use ndarray::Array2;
1212
use tokenizers::Tokenizer;
13-
use tract_onnx::prelude::{Framework, Tensor, TValue, tvec};
13+
use tract_onnx::prelude::{tvec, Framework, TValue, Tensor};
1414

1515
use super::Embedder;
1616

@@ -22,7 +22,11 @@ fn huggingface_cache_dir() -> PathBuf {
2222
.join("hub")
2323
}
2424

25-
fn ensure_cached(model_name: &str, onnx_path: &PathBuf, tokenizer_path: &PathBuf) -> anyhow::Result<()> {
25+
fn ensure_cached(
26+
model_name: &str,
27+
onnx_path: &PathBuf,
28+
tokenizer_path: &PathBuf,
29+
) -> anyhow::Result<()> {
2630
if onnx_path.exists() && tokenizer_path.exists() {
2731
return Ok(());
2832
}
@@ -57,17 +61,19 @@ fn download_from_huggingface(repo: &str, path: &str, dest: &PathBuf) -> anyhow::
5761
.with_context(|| format!("tract: download {} from HF: {}", path, url))?
5862
.error_for_status()
5963
.with_context(|| format!("tract: HF download failed for {}: {}", path, url))?;
60-
let bytes = response.bytes()
64+
let bytes = response
65+
.bytes()
6166
.with_context(|| format!("tract: read body for {} from HF", path))?;
62-
std::fs::write(dest, bytes)
63-
.with_context(|| format!("tract: write {} to cache", path))?;
67+
std::fs::write(dest, bytes).with_context(|| format!("tract: write {} to cache", path))?;
6468
Ok(())
6569
}
6670

6771
fn normalize_l2(mut v: Vec<f32>) -> Vec<f32> {
6872
let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
6973
if norm > 1e-9 {
70-
for x in &mut v { *x /= norm; }
74+
for x in &mut v {
75+
*x /= norm;
76+
}
7177
}
7278
v
7379
}
@@ -78,19 +84,25 @@ fn probe_dimension(model_path: &PathBuf) -> anyhow::Result<usize> {
7884
let inference_model = tract_onnx::onnx()
7985
.model_for_path(model_path)
8086
.context("tract: load for probe")?;
81-
let runnable = inference_model.into_runnable().context("tract: build runnable for probe")?;
87+
let runnable = inference_model
88+
.into_runnable()
89+
.context("tract: build runnable for probe")?;
8290

8391
// Token IDs as f32 (most ONNX models expect float inputs for token IDs)
8492
let input_ids: Vec<f32> = vec![1.0, 2.0, 3.0];
8593
let input_tensor: Tensor = Array2::from_shape_vec((1, 3), input_ids)
8694
.map_err(|e| anyhow::anyhow!("tract: probe shape: {}", e))?
8795
.into();
8896
let input_tvalue: TValue = input_tensor.into();
89-
let result = runnable.run(tvec!(input_tvalue))
97+
let result = runnable
98+
.run(tvec!(input_tvalue))
9099
.map_err(|e| anyhow::anyhow!("tract: probe run: {}", e))?;
91-
let out = result.into_iter().next()
100+
let out = result
101+
.into_iter()
102+
.next()
92103
.ok_or_else(|| anyhow::anyhow!("tract: no probe output"))?;
93-
let view = out.to_array_view::<f32>()
104+
let view = out
105+
.to_array_view::<f32>()
94106
.map_err(|e| anyhow::anyhow!("tract: probe view: {}", e))?;
95107
let hidden = *view.shape().last().unwrap_or(&384);
96108
if hidden == 0 {
@@ -108,7 +120,10 @@ pub struct TractEmbedder {
108120
}
109121

110122
impl TractEmbedder {
111-
pub fn with_model(model_name: impl Into<String>, _cache_dir: Option<PathBuf>) -> anyhow::Result<Self> {
123+
pub fn with_model(
124+
model_name: impl Into<String>,
125+
_cache_dir: Option<PathBuf>,
126+
) -> anyhow::Result<Self> {
112127
let model_name_owned = model_name.into();
113128

114129
let cache = huggingface_cache_dir();
@@ -133,21 +148,32 @@ impl TractEmbedder {
133148

134149
#[async_trait]
135150
impl Embedder for TractEmbedder {
136-
fn dim(&self) -> usize { self.dim }
137-
fn fingerprint(&self) -> &str { &self.fingerprint }
151+
fn dim(&self) -> usize {
152+
self.dim
153+
}
154+
fn fingerprint(&self) -> &str {
155+
&self.fingerprint
156+
}
138157

139158
async fn embed(&self, text: &str) -> anyhow::Result<Vec<f32>> {
140159
let mut out = self.embed_batch(&[text]).await?;
141160
Ok(out.pop().unwrap_or_default())
142161
}
143162

144163
async fn embed_batch(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {
145-
if texts.is_empty() { return Ok(Vec::new()); }
164+
if texts.is_empty() {
165+
return Ok(Vec::new());
166+
}
146167

147168
let tokenizer_path = self.tokenizer_path.clone();
148169
let model_name = tokenizer_path
149170
.parent()
150-
.map(|p| p.file_name().unwrap_or_default().to_string_lossy().into_owned())
171+
.map(|p| {
172+
p.file_name()
173+
.unwrap_or_default()
174+
.to_string_lossy()
175+
.into_owned()
176+
})
151177
.unwrap_or_default();
152178

153179
let owned: Vec<String> = texts.iter().map(|s| (*s).to_owned()).collect();
@@ -185,11 +211,19 @@ fn run_embed_batch(
185211

186212
let encodings: Vec<_> = texts
187213
.iter()
188-
.map(|s| tokenizer.encode(s.as_str(), true)
189-
.map_err(|e| anyhow::anyhow!("tract: tokenize: {}", e)))
214+
.map(|s| {
215+
tokenizer
216+
.encode(s.as_str(), true)
217+
.map_err(|e| anyhow::anyhow!("tract: tokenize: {}", e))
218+
})
190219
.collect::<Result<Vec<_>, _>>()?;
191220

192-
let max_len = encodings.iter().map(|e| e.get_ids().len()).max().unwrap_or(1).min(DEFAULT_MAX_LEN);
221+
let max_len = encodings
222+
.iter()
223+
.map(|e| e.get_ids().len())
224+
.max()
225+
.unwrap_or(1)
226+
.min(DEFAULT_MAX_LEN);
193227
let batch_size = encodings.len();
194228
let mut input_ids = vec![0f32; batch_size * max_len];
195229
let mut attention_mask = vec![0f32; batch_size * max_len];
@@ -206,23 +240,30 @@ fn run_embed_batch(
206240
let input_ids_tensor: Tensor = Array2::from_shape_vec((batch_size, max_len), input_ids)
207241
.map_err(|e| anyhow::anyhow!("tract: input_ids: {}", e))?
208242
.into();
209-
let attention_mask_tensor: Tensor = Array2::from_shape_vec((batch_size, max_len), attention_mask)
210-
.map_err(|e| anyhow::anyhow!("tract: attention_mask: {}", e))?
211-
.into();
243+
let attention_mask_tensor: Tensor =
244+
Array2::from_shape_vec((batch_size, max_len), attention_mask)
245+
.map_err(|e| anyhow::anyhow!("tract: attention_mask: {}", e))?
246+
.into();
212247
let input_tvalue: TValue = input_ids_tensor.into();
213248
let mask_tvalue: TValue = attention_mask_tensor.into();
214249

215250
let result = runnable.run(tvec!(input_tvalue, mask_tvalue))?;
216251

217-
let output = result.into_iter().next()
252+
let output = result
253+
.into_iter()
254+
.next()
218255
.ok_or_else(|| anyhow::anyhow!("tract: no output tensor"))?;
219256

220-
let view = output.to_array_view::<f32>()
257+
let view = output
258+
.to_array_view::<f32>()
221259
.map_err(|e| anyhow::anyhow!("tract: output view: {}", e))?;
222260

223261
let shape = view.shape();
224262
if shape.len() != 3 {
225-
anyhow::bail!("tract: expected 3D output [batch, seq, dim], got {:?}", shape);
263+
anyhow::bail!(
264+
"tract: expected 3D output [batch, seq, dim], got {:?}",
265+
shape
266+
);
226267
}
227268

228269
let seq_len = shape[1];
@@ -233,11 +274,15 @@ fn run_embed_batch(
233274
let mut sum = vec![0f32; dim];
234275
let mut count = 0f32;
235276
for j in 0..valid_len {
236-
for k in 0..dim { sum[k] += view[[i, j, k]]; }
277+
for k in 0..dim {
278+
sum[k] += view[[i, j, k]];
279+
}
237280
count += 1.0;
238281
}
239282
if count > 0.0 {
240-
for x in &mut sum { *x /= count; }
283+
for x in &mut sum {
284+
*x /= count;
285+
}
241286
}
242287
embeddings.push(normalize_l2(sum));
243288
}

crates/core/src/knowledge_graph.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,8 @@ CREATE INDEX IF NOT EXISTS idx_triples_subject ON triples(subject);
174174
.execute("ALTER TABLE triples ADD COLUMN adapter_name TEXT", [])?;
175175
}
176176
if !names.iter().any(|n| n == "t_created") {
177-
self.conn.execute(
178-
"ALTER TABLE triples ADD COLUMN t_created TEXT",
179-
[],
180-
)?;
177+
self.conn
178+
.execute("ALTER TABLE triples ADD COLUMN t_created TEXT", [])?;
181179
}
182180
if !names.iter().any(|n| n == "t_expired") {
183181
self.conn
@@ -403,7 +401,10 @@ CREATE INDEX IF NOT EXISTS idx_triples_subject ON triples(subject);
403401
let te: Option<String> = row.get("t_expired")?;
404402
let vt: Option<String> = row.get("valid_to")?;
405403
let tc: Option<String> = row.get("t_created")?;
406-
eprintln!(" ROW: t_created={:?}, t_expired={:?}, valid_to={:?}", tc, te, vt);
404+
eprintln!(
405+
" ROW: t_created={:?}, t_expired={:?}, valid_to={:?}",
406+
tc, te, vt
407+
);
407408
results.push(self.row_to_entity_result(row, "outgoing", eid)?);
408409
}
409410
eprintln!("TRACE: returned {} rows", cnt);
@@ -708,7 +709,7 @@ CREATE INDEX IF NOT EXISTS idx_triples_subject ON triples(subject);
708709
AND (t.t_expired IS NULL OR t.t_expired >= ?3) \
709710
AND (t.valid_from IS NULL OR t.valid_from <= ?4) \
710711
AND (t.valid_to IS NULL OR t.valid_to >= ?5) \
711-
ORDER BY t.valid_from ASC LIMIT 100"
712+
ORDER BY t.valid_from ASC LIMIT 100",
712713
)?;
713714
let rows = stmt.query_map(params![eid, now, now, now, now], |row| {
714715
Ok(Triple {

crates/core/src/layers.rs

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -565,8 +565,10 @@ pub struct DeepSearchStatus {
565565
#[cfg(test)]
566566
mod tests {
567567
use super::*;
568-
use crate::palace::{DrawerId, MemoryScope, DrawerKind, MemoryTier, SearchScope, SearchHit, PalaceStore};
569568
use crate::embed::Embedder;
569+
use crate::palace::{
570+
DrawerId, DrawerKind, MemoryScope, MemoryTier, PalaceStore, SearchHit, SearchScope,
571+
};
570572
use async_trait::async_trait;
571573
use tempfile::tempdir;
572574

@@ -587,22 +589,38 @@ mod tests {
587589
async fn add_drawer(&self, _drawer: Drawer) -> anyhow::Result<DrawerId> {
588590
panic!("add_drawer not implemented in test adapter")
589591
}
590-
async fn remember(&self, _content: String, _scope: MemoryScope) -> anyhow::Result<DrawerId> {
592+
async fn remember(
593+
&self,
594+
_content: String,
595+
_scope: MemoryScope,
596+
) -> anyhow::Result<DrawerId> {
591597
panic!("remember not implemented in test adapter")
592598
}
593599
async fn forget(&self, _id: &DrawerId) -> anyhow::Result<bool> {
594600
panic!("forget not implemented in test adapter")
595601
}
596-
async fn search(&self, _query: &str, _scope: &SearchScope) -> anyhow::Result<Vec<SearchHit>> {
602+
async fn search(
603+
&self,
604+
_query: &str,
605+
_scope: &SearchScope,
606+
) -> anyhow::Result<Vec<SearchHit>> {
597607
panic!("search not implemented in test adapter")
598608
}
599-
async fn search_with_embedding(&self, _query_vec: &[f32], _scope: &SearchScope) -> anyhow::Result<Vec<SearchHit>> {
609+
async fn search_with_embedding(
610+
&self,
611+
_query_vec: &[f32],
612+
_scope: &SearchScope,
613+
) -> anyhow::Result<Vec<SearchHit>> {
600614
panic!("search_with_embedding not implemented in test adapter")
601615
}
602616
async fn related(&self, _id: &DrawerId, _depth: usize) -> anyhow::Result<Vec<SearchHit>> {
603617
panic!("related not implemented in test adapter")
604618
}
605-
async fn extract_from_transcript(&self, _transcript: &str, _session_id: &str) -> anyhow::Result<Vec<DrawerId>> {
619+
async fn extract_from_transcript(
620+
&self,
621+
_transcript: &str,
622+
_session_id: &str,
623+
) -> anyhow::Result<Vec<DrawerId>> {
606624
panic!("extract_from_transcript not implemented in test adapter")
607625
}
608626
async fn graph_stats(&self) -> anyhow::Result<crate::knowledge_graph::KgStats> {
@@ -617,7 +635,11 @@ mod tests {
617635
fn store(&self) -> &dyn PalaceStore {
618636
panic!("store not implemented in test adapter")
619637
}
620-
async fn get_drawers(&self, scope: Option<&SearchScope>, limit: Option<usize>) -> anyhow::Result<Vec<Drawer>> {
638+
async fn get_drawers(
639+
&self,
640+
scope: Option<&SearchScope>,
641+
limit: Option<usize>,
642+
) -> anyhow::Result<Vec<Drawer>> {
621643
let wing = scope.and_then(|s| s.wing.as_deref());
622644
let room = scope.and_then(|s| s.room.as_deref());
623645
let limit = limit.unwrap_or(usize::MAX);
@@ -632,8 +654,14 @@ mod tests {
632654
content,
633655
kind: DrawerKind::default(),
634656
tier: MemoryTier::default(),
635-
wing: metadata.get("wing").and_then(|v| v.as_str()).map(String::from),
636-
room: metadata.get("room").and_then(|v| v.as_str()).map(String::from),
657+
wing: metadata
658+
.get("wing")
659+
.and_then(|v| v.as_str())
660+
.map(String::from),
661+
room: metadata
662+
.get("room")
663+
.and_then(|v| v.as_str())
664+
.map(String::from),
637665
metadata,
638666
derived_from: Vec::new(),
639667
});

crates/core/src/lib.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,6 @@ pub mod mine_pid_guard;
100100
#[deprecated(since = "0.2.0", note = "use palace:: or embed:: API instead")]
101101
pub mod normalize;
102102
#[doc(hidden)]
103-
104103
#[doc(hidden)]
105104
#[deprecated(since = "0.2.0", note = "use palace:: or embed:: API instead")]
106105
pub mod palace_db;

crates/core/src/palace/store/embedvec.rs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,10 @@ impl PalaceStore for EmbedvecStore {
8989
return Ok(());
9090
}
9191

92-
let needs_write = self.model_name.is_some()
93-
&& self.palace_path.is_some()
94-
&& {
95-
let inner = self.inner.lock().await;
96-
inner.len() == 0
97-
};
92+
let needs_write = self.model_name.is_some() && self.palace_path.is_some() && {
93+
let inner = self.inner.lock().await;
94+
inner.len() == 0
95+
};
9896

9997
if needs_write {
10098
let manifest = EmbeddingManifest::from_embedder(
@@ -111,10 +109,9 @@ impl PalaceStore for EmbedvecStore {
111109
.into_iter()
112110
.enumerate()
113111
.map(|(i, d)| {
114-
let id = d
115-
.id
116-
.map(|di| di.0)
117-
.unwrap_or_else(|| format!("drawer-{}", i));
112+
let id =
113+
d.id.map(|di| di.0)
114+
.unwrap_or_else(|| format!("drawer-{}", i));
118115
(id, d.content)
119116
})
120117
.collect();

0 commit comments

Comments
 (0)