Skip to content

Commit 423761c

Browse files
committed
refactor: score sketch suggestions through kernal-api
1 parent be756d6 commit 423761c

8 files changed

Lines changed: 94 additions & 35 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,11 @@ homepage = "https://github.com/zackees/fastled-wasm"
1414

1515
[workspace.dependencies]
1616
clap = { version = "4", features = ["derive"] }
17-
kernal-api = { version = "=0.1.0", features = ["fs", "fs-watch", "hash-sha256", "archive", "http-client", "http-server", "event-stream", "secure-random"] }
17+
kernal-api = { version = "=0.1.0", features = ["fs", "fs-watch", "hash-sha256", "archive", "http-client", "http-server", "event-stream", "secure-random", "text-similarity"] }
1818
serde = { version = "1", features = ["derive"] }
1919
serde_json = "1"
2020
anyhow = "1"
2121
ctcb-core = "0.4.1"
22-
strsim = "0.11"
2322
crossterm = "0.28"
2423
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "fs", "signal"] }
2524
toml = "0.8"
@@ -36,7 +35,7 @@ strip = "none"
3635

3736
# Temporary migration override; replace with the verified published release.
3837
[patch.crates-io]
39-
kernal-api = { path = "../fastled-wasm-extern/kernal-api-temporary" }
38+
kernal-api = { path = "../fastled-wasm-extern/kernal-api-text" }
4039

4140
[profile.dev.package.kernal-api]
4241
codegen-units = 1

‎crates/fastled-cli/Cargo.toml‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ serde = { workspace = true }
2727
serde_json = { workspace = true }
2828
anyhow = { workspace = true }
2929
ctcb-core = { workspace = true }
30-
strsim = { workspace = true }
3130
crossterm = { workspace = true }
3231
tokio = { workspace = true }
3332
toml = { workspace = true }

‎crates/fastled-cli/src/lib.rs‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -412,16 +412,24 @@ mod tests {
412412
#[test]
413413
fn resolve_prompt_choice_accepts_default_selection() {
414414
let options = vec!["Blink".to_string(), "Noise".to_string()];
415-
match resolve_prompt_choice("", &options, 1) {
415+
match resolve_prompt_choice("", &options, 1).unwrap() {
416416
PromptChoice::Selected(choice) => assert_eq!(choice, "Noise"),
417417
_ => panic!("expected default selection"),
418418
}
419419
}
420420

421+
#[test]
422+
fn resolve_prompt_choice_propagates_similarity_limit_errors() {
423+
let options = vec!["examples/Blink".to_string(), "examples/Fire".to_string()];
424+
let error = resolve_prompt_choice(&"x".repeat(4097), &options, 0).unwrap_err();
425+
assert!(error.contains("score sketch-name suggestion"));
426+
assert!(error.contains("byte limit"));
427+
}
428+
421429
#[test]
422430
fn resolve_prompt_choice_accepts_numeric_selection() {
423431
let options = vec!["Blink".to_string(), "Noise".to_string()];
424-
match resolve_prompt_choice("2", &options, 0) {
432+
match resolve_prompt_choice("2", &options, 0).unwrap() {
425433
PromptChoice::Selected(choice) => assert_eq!(choice, "Noise"),
426434
_ => panic!("expected numeric selection"),
427435
}
@@ -434,7 +442,7 @@ mod tests {
434442
"Fire2012WithPalette".to_string(),
435443
"Blink".to_string(),
436444
];
437-
match resolve_prompt_choice("Fire", &options, 0) {
445+
match resolve_prompt_choice("Fire", &options, 0).unwrap() {
438446
PromptChoice::Narrowed(matches) => {
439447
assert_eq!(
440448
matches,
@@ -452,7 +460,7 @@ mod tests {
452460
"examples/BeatDetection".to_string(),
453461
"examples/Blink".to_string(),
454462
];
455-
match resolve_prompt_choice("beats", &options, 0) {
463+
match resolve_prompt_choice("beats", &options, 0).unwrap() {
456464
PromptChoice::Selected(choice) => {
457465
assert_eq!(choice, "examples/BeatDetection");
458466
}

‎crates/fastled-cli/src/project.rs‎

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -639,17 +639,18 @@ fn copy_dir_all(src: &Path, dest: &Path) -> Result<()> {
639639

640640
/// Find the best-matching sketch name from `candidates` for a given `query`.
641641
///
642-
/// Uses the Jaro-Winkler distance (via `strsim`) to score each candidate.
642+
/// Uses kernel-owned Jaro-Winkler similarity to score each candidate.
643643
/// Returns the candidate(s) with the highest score.
644644
///
645645
/// When `query` is an exact substring of a candidate that candidate is
646646
/// returned immediately (mirrors the Python `partial_name in sketch_str`
647647
/// fast-path in `sketch.py::find_sketch_by_partial_name`).
648648
///
649649
/// Returns an empty `Vec` when `candidates` is empty.
650-
pub fn best_sketch_match(query: &str, candidates: &[&str]) -> Vec<String> {
650+
/// Returns an error if fuzzy scoring exceeds the kernel's resource limits.
651+
pub fn best_sketch_match(query: &str, candidates: &[&str]) -> Result<Vec<String>> {
651652
if candidates.is_empty() {
652-
return Vec::new();
653+
return Ok(Vec::new());
653654
}
654655

655656
let q_lower = query.to_lowercase();
@@ -661,25 +662,29 @@ pub fn best_sketch_match(query: &str, candidates: &[&str]) -> Vec<String> {
661662
.filter(|c| c.to_lowercase().contains(&q_lower))
662663
.collect();
663664
if !substring_hits.is_empty() {
664-
return substring_hits.iter().map(|s| s.to_string()).collect();
665+
return Ok(substring_hits.iter().map(|s| s.to_string()).collect());
665666
}
666667

667668
// Fuzzy: Jaro-Winkler distance.
668669
let mut scored: Vec<(f64, &str)> = candidates
669670
.iter()
670-
.map(|c| (strsim::jaro_winkler(&q_lower, &c.to_lowercase()), *c))
671-
.collect();
671+
.map(|c| {
672+
let score = kernal_api::text::name_similarity(&q_lower, &c.to_lowercase())
673+
.context("score sketch-name suggestion")?;
674+
Ok((score, *c))
675+
})
676+
.collect::<Result<_>>()?;
672677

673678
// Sort descending by score.
674679
scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
675680

676681
let best_score = scored[0].0;
677682
// Return all candidates tied at the best score (within floating-point epsilon).
678-
scored
683+
Ok(scored
679684
.iter()
680685
.take_while(|(s, _)| (s - best_score).abs() < 1e-9)
681686
.map(|(_, name)| name.to_string())
682-
.collect()
687+
.collect())
683688
}
684689

685690
/// Find a sketch directory by partial name match using the Python-side rules.
@@ -1063,10 +1068,31 @@ mod tests {
10631068
// best_sketch_match (fuzzy matching)
10641069
// ------------------------------------------------------------------
10651070

1071+
#[test]
1072+
fn sketch_matching_preserves_substring_precedence_and_stable_ties() {
1073+
assert_eq!(
1074+
best_sketch_match("Blink", &["Blin", "BlinkFast", "Blink"]).unwrap(),
1075+
["BlinkFast", "Blink"]
1076+
);
1077+
assert_eq!(
1078+
best_sketch_match("BLNK", &["Blink", "BLINK", "Fire"]).unwrap(),
1079+
["Blink", "BLINK"]
1080+
);
1081+
}
1082+
1083+
#[test]
1084+
fn sketch_matching_reports_resource_errors_without_partial_ranking() {
1085+
let error = best_sketch_match(&"x".repeat(4097), &["Blink"]).unwrap_err();
1086+
assert!(format!("{error:#}").contains("byte limit"));
1087+
let candidate = "y".repeat(1024);
1088+
let error = best_sketch_match(&"x".repeat(1025), &["Blink", &candidate]).unwrap_err();
1089+
assert!(format!("{error:#}").contains("work limit"));
1090+
}
1091+
10661092
#[test]
10671093
fn test_best_sketch_match_exact_substring() {
10681094
let candidates = ["Blink", "BlinkFast", "Fire2012"];
1069-
let matches = best_sketch_match("Blink", &candidates);
1095+
let matches = best_sketch_match("Blink", &candidates).unwrap();
10701096
assert!(
10711097
matches.contains(&"Blink".to_owned()),
10721098
"Blink should match: {matches:?}"
@@ -1084,22 +1110,22 @@ mod tests {
10841110
#[test]
10851111
fn test_best_sketch_match_fuzzy_fallback() {
10861112
let candidates = ["Blink", "Fire2012", "Noise"];
1087-
let matches = best_sketch_match("blnk", &candidates);
1113+
let matches = best_sketch_match("blnk", &candidates).unwrap();
10881114
// Jaro-Winkler should rank "Blink" highest.
10891115
assert!(!matches.is_empty(), "fuzzy match should return results");
10901116
assert_eq!(matches[0], "Blink", "best fuzzy match should be Blink");
10911117
}
10921118

10931119
#[test]
10941120
fn test_best_sketch_match_empty_candidates() {
1095-
let matches = best_sketch_match("anything", &[]);
1121+
let matches = best_sketch_match("anything", &[]).unwrap();
10961122
assert!(matches.is_empty());
10971123
}
10981124

10991125
#[test]
11001126
fn test_best_sketch_match_case_insensitive() {
11011127
let candidates = ["Blink", "Fire2012"];
1102-
let matches = best_sketch_match("BLINK", &candidates);
1128+
let matches = best_sketch_match("BLINK", &candidates).unwrap();
11031129
assert!(
11041130
matches.contains(&"Blink".to_owned()),
11051131
"case-insensitive match: {matches:?}"

‎crates/fastled-cli/src/selection.rs‎

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,16 @@ fn option_basename(option: &str) -> &str {
2525
.unwrap_or(option)
2626
}
2727

28-
fn fuzzy_match_options(input: &str, options: &[String]) -> Vec<String> {
28+
fn fuzzy_match_options(input: &str, options: &[String]) -> Result<Vec<String>, String> {
2929
let basenames: Vec<String> = options
3030
.iter()
3131
.map(|option| option_basename(option).to_string())
3232
.collect();
3333
let basename_refs: Vec<&str> = basenames.iter().map(String::as_str).collect();
34-
let fuzzy_matches = project::best_sketch_match(input, &basename_refs);
34+
let fuzzy_matches =
35+
project::best_sketch_match(input, &basename_refs).map_err(|error| format!("{error:#}"))?;
3536
if fuzzy_matches.is_empty() {
36-
return Vec::new();
37+
return Ok(Vec::new());
3738
}
3839

3940
let mut results = Vec::new();
@@ -42,30 +43,30 @@ fn fuzzy_match_options(input: &str, options: &[String]) -> Vec<String> {
4243
results.push(options[index].clone());
4344
}
4445
}
45-
results
46+
Ok(results)
4647
}
4748

4849
pub fn resolve_prompt_choice(
4950
input: &str,
5051
options: &[String],
5152
default_index: usize,
52-
) -> PromptChoice {
53+
) -> Result<PromptChoice, String> {
5354
let trimmed = input.trim();
5455
if trimmed.is_empty() {
55-
return PromptChoice::Selected(options[default_index].clone());
56+
return Ok(PromptChoice::Selected(options[default_index].clone()));
5657
}
5758

5859
if let Ok(index) = trimmed.parse::<usize>() {
5960
if (1..=options.len()).contains(&index) {
60-
return PromptChoice::Selected(options[index - 1].clone());
61+
return Ok(PromptChoice::Selected(options[index - 1].clone()));
6162
}
6263
}
6364

6465
if let Some(exact) = options
6566
.iter()
6667
.find(|option| option.eq_ignore_ascii_case(trimmed))
6768
{
68-
return PromptChoice::Selected(exact.clone());
69+
return Ok(PromptChoice::Selected(exact.clone()));
6970
}
7071

7172
let input_lower = trimmed.to_lowercase();
@@ -75,17 +76,17 @@ pub fn resolve_prompt_choice(
7576
.cloned()
7677
.collect();
7778
match partial_matches.len() {
78-
1 => return PromptChoice::Selected(partial_matches[0].clone()),
79-
n if n > 1 => return PromptChoice::Narrowed(partial_matches),
79+
1 => return Ok(PromptChoice::Selected(partial_matches[0].clone())),
80+
n if n > 1 => return Ok(PromptChoice::Narrowed(partial_matches)),
8081
_ => {}
8182
}
8283

83-
let fuzzy_matches = fuzzy_match_options(trimmed, options);
84-
match fuzzy_matches.len() {
84+
let fuzzy_matches = fuzzy_match_options(trimmed, options)?;
85+
Ok(match fuzzy_matches.len() {
8586
1 => PromptChoice::Selected(fuzzy_matches[0].clone()),
8687
n if n > 1 => PromptChoice::Narrowed(fuzzy_matches),
8788
_ => PromptChoice::Retry,
88-
}
89+
})
8990
}
9091

9192
pub fn prepare_sketch_selection(
@@ -150,7 +151,7 @@ pub(crate) fn prompt_for_choice(
150151
.read_line(&mut input)
151152
.map_err(|err| format!("failed to read selection: {err}"))?;
152153

153-
match resolve_prompt_choice(&input, &current_options, current_default) {
154+
match resolve_prompt_choice(&input, &current_options, current_default)? {
154155
PromptChoice::Selected(choice) => return Ok(choice),
155156
PromptChoice::Narrowed(matches) => {
156157
let query = input.trim();

‎docs/kernal-api-migration.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -624,6 +624,30 @@ FastLED's full Rust workspace tests, strict all-target Clippy and formatting
624624
pass; Python tests pass (28 passed, one skipped). This remains local adoption,
625625
not an exact published dependency, and no build-speed improvement is claimed.
626626

627+
### Name-similarity adoption checkpoint
628+
629+
Issue https://github.com/zackees/kernal-api/issues/184 moves Jaro-Winkler scoring
630+
behind the opt-in kernel text capability. FastLED retains lowercase conversion,
631+
substring precedence, candidate selection, stable best-score ties and prompts.
632+
Direct `strsim` is removed and banned by the boundary test (observed RED then
633+
GREEN); the package remains transitive through the kernel and other consumers.
634+
635+
`best_sketch_match` and `resolve_prompt_choice` are now fallible public helpers.
636+
Scoring rejects inputs over 4096 UTF-8 bytes or scalar-count products over
637+
1,048,576. Errors propagate through the interactive prompt; no partial ranking,
638+
truncation or replacement score is used. Existing exact/substring fast paths
639+
remain application policy and do not invoke fuzzy scoring. Generic Unicode,
640+
score-vector and resource-limit tests live upstream; application tests cover
641+
substring precedence, stable ties and error propagation.
642+
643+
The current migration-only patch points at
644+
`../fastled-wasm-extern/kernal-api-text` on `feat/text-similarity`.
645+
Upstream focused and broad feature tests, default-feature check, strict Clippy
646+
and dependency-isolation checks pass locally. Python tests pass (28 passed,
647+
one skipped). Full application Rust tests and strict all-target Clippy pass;
648+
the cross-repository source review is clean. Publication and exact adoption remain required;
649+
no speed improvement is claimed.
650+
627651
### Final migration audit
628652

629653
The Axum baseline now has a raw-wire parity test for missing-file 404,

‎tests/unit/test_kernal_boundary.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ def test_migrated_capabilities_are_owned_by_kernal_api():
2525
assert "tower-http" not in dependencies
2626
assert "getrandom" not in dependencies
2727
assert "tempfile" not in dependencies
28+
assert "strsim" not in dependencies
2829
assert "tempfile" not in manifest.get("dev-dependencies", {})
2930
for backend in ("zip", "tar", "zstd", "flate2"):
3031
assert backend not in dependencies
@@ -41,6 +42,7 @@ def test_migrated_capabilities_are_owned_by_kernal_api():
4142
assert "dirs::" not in source.read_text(), source
4243
assert "getrandom::" not in source.read_text(), source
4344
assert "tempfile::" not in source.read_text(), source
45+
assert "strsim::" not in source.read_text(), source
4446
for backend in ("zip", "tar", "zstd", "flate2"):
4547
assert f"{backend}::" not in source.read_text(), source
4648

0 commit comments

Comments
 (0)