Skip to content

chore(code-quality): generalized code-quality refactoring - #1098

Merged
ndizazzo merged 2 commits into
mainfrom
chore/code-quality-review
Jul 28, 2026
Merged

chore(code-quality): generalized code-quality refactoring#1098
ndizazzo merged 2 commits into
mainfrom
chore/code-quality-review

Conversation

@ndizazzo

@ndizazzo ndizazzo commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Summary

Reduces duplicated routing, model-selection, capability-detection, and lifecycle code while preserving existing behavior and compatibility.

This work follows an audit of all 56 workspace crates and retains only reductions with measurable production-code or runtime benefits.

Changes

  • Share prefix-affinity TTL/LRU mechanics between host and client routing.
  • Consolidate model-artifact candidate ranking.
  • Reduce repeated model-capability matches and metadata scans.
  • Consolidate owner-control lifecycle request construction.
  • Replace duplicated model-target payload maps with lightweight indexes.
  • Add characterization coverage for ordering, precedence, expiry, eviction, errors, and mixed-version behavior.

Impact

  • Approximately 115 fewer raw production lines.
  • Approximately 120 fewer nonblank production lines.
  • Removes 30 if and 6 match nodes.
  • Avoids up to two full ModelTargetPayload clones per target.
  • Removes one duplicated prefix-affinity state machine.
  • No public API, mesh protocol, plugin protocol, Skippy ABI, serialization, or dependency-policy changes.

Total repository LoC increases because of the added characterization and integration tests.

Validation

  • Focused tests, package checks, and warning-denying Clippy checks passed.
  • cargo fmt --all --check and changed-file diagnostics passed.
  • just build passed.
  • Two-node client/serving routing smoke passed.
  • Mixed-version v0.72.0/v0.72.1 routing passed in both directions.
  • Mixed-version load, unload, ensure, drain, and legacy control_unsupported behavior passed.
  • A complete just test-all run passed.

Subsequent exact-final-state suite reruns encountered unrelated existing system and UI flakes. Each failing test passed in isolated repeated runs; none touches files changed by this PR.

Compatibility

This change is behavior-preserving:

  • Host and client request-key precedence remain distinct.
  • Host health, reputation, and auto-model state remain host-owned.
  • Lifecycle request IDs, timeouts, errors, and legacy fallback remain unchanged.
  • Model-target ordering and alias precedence remain unchanged.
  • Model selection, split-shard ordering, capability projections, and serialized output remain unchanged.

Summary by CodeRabbit

  • New Features

    • Streamlined control-plane model lifecycle commands (load/unload/ensure/drain) with consistent handling and preserved request tracking.
    • Enhanced prefix-based routing affinity, including TTL pruning, capacity eviction, and richer hit/miss/stale/learning counters.
  • Bug Fixes

    • More reliable model target resolution by name or reference, improving readiness/capacity reporting.
    • Deterministic model artifact selection with clearer rejection of unsupported artifacts.
  • Tests

    • Added/expanded integration and unit tests, including normalized terminal output assertions.

@ndizazzo ndizazzo self-assigned this Jul 28, 2026
@github-actions
github-actions Bot requested a review from michaelneale July 28, 2026 06:06
@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 505c4c70-34ad-4b44-a802-5ae55640f1cb

📥 Commits

Reviewing files that changed from the base of the PR and between 4215870 and 3770a3e.

📒 Files selected for processing (14)
  • crates/mesh-client/src/client/control_plane.rs
  • crates/mesh-client/src/network/affinity.rs
  • crates/mesh-client/tests/control_plane_lifecycle_client.rs
  • crates/mesh-llm-commands/src/setup/summary.rs
  • crates/mesh-llm-commands/src/terminal.rs
  • crates/mesh-llm-commands/src/uninstall.rs
  • crates/mesh-llm-host-runtime/src/api/mod.rs
  • crates/mesh-llm-host-runtime/src/api/model_targets.rs
  • crates/mesh-llm-host-runtime/src/api/split_readiness.rs
  • crates/mesh-llm-host-runtime/src/network/affinity.rs
  • crates/mesh-llm-routing/src/lib.rs
  • crates/mesh-llm-routing/src/prefix_affinity.rs
  • crates/mesh-llm-types/src/models/capabilities.rs
  • crates/model-artifact/src/lib.rs
🚧 Files skipped from review as they are similar to previous changes (13)
  • crates/mesh-llm-routing/src/lib.rs
  • crates/mesh-llm-host-runtime/src/api/split_readiness.rs
  • crates/mesh-llm-commands/src/setup/summary.rs
  • crates/mesh-llm-host-runtime/src/api/mod.rs
  • crates/mesh-llm-commands/src/terminal.rs
  • crates/mesh-client/tests/control_plane_lifecycle_client.rs
  • crates/mesh-client/src/client/control_plane.rs
  • crates/mesh-llm-host-runtime/src/api/model_targets.rs
  • crates/mesh-llm-routing/src/prefix_affinity.rs
  • crates/mesh-llm-types/src/models/capabilities.rs
  • crates/model-artifact/src/lib.rs
  • crates/mesh-llm-host-runtime/src/network/affinity.rs
  • crates/mesh-client/src/network/affinity.rs

📝 Walkthrough

Walkthrough

Changes

Control-plane lifecycle commands

Layer / File(s) Summary
Shared lifecycle request flow
crates/mesh-client/src/client/control_plane.rs
Lifecycle requests now share command construction, sending, and legacy error mapping.
Lifecycle round-trip validation
crates/mesh-client/tests/control_plane_lifecycle_client.rs
An iroh test server validates payloads, request IDs, and responses for all four commands.

Shared prefix affinity

Layer / File(s) Summary
Prefix affinity container
crates/mesh-llm-routing/src/prefix_affinity.rs, crates/mesh-llm-routing/src/lib.rs
A reusable TTL/LRU container tracks mappings, counters, learning, eviction, and stale entries.
Client affinity delegation
crates/mesh-client/src/network/affinity.rs
The client router delegates prefix state and statistics to PrefixAffinity.
Host runtime affinity delegation
crates/mesh-llm-host-runtime/src/network/affinity.rs
Host-runtime affinity uses the shared container while retaining auto-model tracking.

Model target lookup indexing

Layer / File(s) Summary
Indexed target lookup construction
crates/mesh-llm-host-runtime/src/api/model_targets.rs
Lookup maps store indexes into the shared target vector, with accessor methods and alias-resolution tests.
Target lookup consumers
crates/mesh-llm-host-runtime/src/api/mod.rs, crates/mesh-llm-host-runtime/src/api/split_readiness.rs
API paths use accessor methods with model-reference and model-name fallback.

Capability inference helpers

Layer / File(s) Summary
Capability level and signal processing
crates/mesh-llm-types/src/models/capabilities.rs
Capability reporting and metadata merging use centralized helpers with expanded tests.

Model artifact selection

Layer / File(s) Summary
Unified artifact ranking
crates/model-artifact/src/lib.rs
Primary and default artifact selection share deterministic ranking and rejection tests.

ANSI output test normalization

Layer / File(s) Summary
ANSI stripping helper
crates/mesh-llm-commands/src/terminal.rs
A test-only helper strips ANSI SGR styling while preserving plain and Unicode text.
Styled output assertions
crates/mesh-llm-commands/src/setup/summary.rs, crates/mesh-llm-commands/src/uninstall.rs
Command tests normalize styled output before comparing expected text.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

Suggested reviewers: michaelneale, i386

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.93% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is related to the change set, but it is too broad and generic to clearly describe the main refactoring work. Use a more specific title that names the primary theme, such as shared lifecycle, affinity, and model-selection refactoring.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/code-quality-review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (6)
crates/mesh-llm-routing/src/prefix_affinity.rs (2)

91-118: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Consider cloning only the target, not the whole entry.

self.entries.get(&key).cloned() clones AffinityEntry<T> (target + Instant) on every lookup, and the entry is then re-fetched mutably to refresh last_used. Cloning the target alone after the candidate check keeps the same semantics with one fewer copy.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/mesh-llm-routing/src/prefix_affinity.rs` around lines 91 - 118, Update
lookup to borrow the stored AffinityEntry while checking candidates, then clone
only its target for the returned value; avoid cloning the entire entry via
entries.get(&key).cloned(). Preserve the existing stale-entry removal,
touch_key, timestamp refresh, and hit/miss statistics behavior.

75-87: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff

LRU bookkeeping is O(n) per operation with a String clone each touch.

touch_key/remove_key linearly scan a VecDeque that can hold up to PREFIX_AFFINITY_MAX_ENTRIES (4096) AffinityKeys, each comparison including a String compare, and VecDeque::remove shifts elements. This runs on every lookup/learn, i.e. per routed request. Behavior matches the previous per-crate implementations, so this is not a regression, but now that the logic is centralized it is a good place to switch to a monotonic sequence counter (HashMap<AffinityKey, u64> order stamps + BTreeMap<u64, AffinityKey>) or an IndexMap/intrusive LRU to get O(log n)/O(1) touches.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/mesh-llm-routing/src/prefix_affinity.rs` around lines 75 - 87, Replace
the VecDeque-based LRU bookkeeping in touch_key and remove_key with an indexed
ordering structure that avoids linear scans, String comparisons, and element
shifting on each operation. Use monotonic order stamps with a
HashMap<AffinityKey, u64> and BTreeMap<u64, AffinityKey>, or an equivalent O(log
n)/O(1) LRU implementation, while preserving eviction order and existing
entry-removal behavior.
crates/mesh-client/src/network/affinity.rs (1)

126-145: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Mapping helper is duplicated in crates/mesh-llm-host-runtime/src/network/affinity.rs (lines 241-261).

The two affinity_stats_snapshot functions are identical apart from the extra target_reputation field. If the snapshot struct grows again, both copies must be updated. Optional: add a From<PrefixAffinityStats>-style constructor next to PrefixAffinityStats and let each crate extend it, or keep as-is since the two AffinityStatsSnapshot types are crate-local.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/mesh-client/src/network/affinity.rs` around lines 126 - 145, The
AffinityStatsSnapshot field mapping is duplicated between the two crate-local
affinity_stats_snapshot helpers. Consolidate the shared
PrefixAffinityStats-to-snapshot mapping through a reusable From-style
constructor or equivalent helper near PrefixAffinityStats, then have each
crate-specific snapshot builder reuse it while preserving the runtime crate’s
target_reputation field.
crates/mesh-llm-types/src/models/capabilities.rs (3)

13-34: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider const fn for the pure mapping helpers.

status/label/is_supported are total, side-effect-free mappings over a Copy enum; making them const fn matches the existing const fn as_str convention used elsewhere in the workspace (e.g. crates/mesh-llm-host-runtime/src/api/model_targets.rs:85) and allows const-context use.

♻️ Proposed tweak
-    fn is_supported(self) -> bool {
+    const fn is_supported(self) -> bool {
-        self == Self::Supported
+        matches!(self, Self::Supported)
     }
 
-    fn status(self) -> &'static str {
+    const fn status(self) -> &'static str {
 
-    fn label(self) -> Option<&'static str> {
+    const fn label(self) -> Option<&'static str> {

Note == isn't usable in const fn for derived PartialEq, hence the matches! swap.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/mesh-llm-types/src/models/capabilities.rs` around lines 13 - 34, Make
CapabilityLevel::is_supported, CapabilityLevel::status, and
CapabilityLevel::label const fn so they can be used in const contexts. Replace
the derived-PartialEq comparison in is_supported with a const-compatible
matches! check, leaving the existing mappings and return values unchanged.

236-295: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Vision special-case could fold into name_signal_level.

The audio/reasoning/tool-use branches share name_signal_level, while vision duplicates the same shape inline only to gate the "likely" tier. Passing the gate into the helper removes the asymmetry and keeps the precedence rule in one place.

♻️ Proposed refactor
 fn merge_name_signal(caps: &mut ModelCapabilities, value: &str, allow_likely_vision: bool) {
-    let vision = if strong_vision_name_signal(value) {
-        CapabilityLevel::Supported
-    } else if allow_likely_vision && likely_vision_name_signal(value) {
-        CapabilityLevel::Likely
-    } else {
-        CapabilityLevel::None
-    };
-    caps.upgrade_vision(vision);
+    caps.upgrade_vision(name_signal_level(
+        value,
+        strong_vision_name_signal,
+        likely_vision_name_signal,
+        allow_likely_vision,
+    ));
     caps.upgrade_audio(name_signal_level(
         value,
         strong_audio_name_signal,
         likely_audio_name_signal,
+        true,
     ));
@@
 fn name_signal_level(
     value: &str,
     strong: fn(&str) -> bool,
     likely: fn(&str) -> bool,
+    allow_likely: bool,
 ) -> CapabilityLevel {
     if strong(value) {
         CapabilityLevel::Supported
-    } else if likely(value) {
+    } else if allow_likely && likely(value) {
         CapabilityLevel::Likely
     } else {
         CapabilityLevel::None
     }
 }

Behavior is unchanged; config_model_type_preserves_likely_and_supported_levels still pins the vision-likely suppression for config-derived signals.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/mesh-llm-types/src/models/capabilities.rs` around lines 236 - 295,
Refactor name_signal_level to accept a boolean gate for its likely tier, then
use it in merge_name_signal for vision, audio, reasoning, and tool-use signals.
Preserve vision’s existing allow_likely_vision behavior while keeping supported
signals and config-derived likely suppression unchanged, including
config_model_type_preserves_likely_and_supported_levels.

500-520: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Test name overstates what is asserted.

strong_name_evidence_dominates_likely_and_existing_values asserts that vision stays Likely and audio stays Supported, i.e. it characterizes monotonic upgrade (never downgrade), not dominance. Something like name_signals_only_upgrade_existing_levels reads truer.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/mesh-llm-types/src/models/capabilities.rs` around lines 500 - 520, The
test function name strong_name_evidence_dominates_likely_and_existing_values
mischaracterizes the assertions; rename it to reflect that name signals only
upgrade existing capability levels, such as
name_signals_only_upgrade_existing_levels. Keep the test setup and assertions
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/mesh-client/src/network/affinity.rs`:
- Around line 126-145: The AffinityStatsSnapshot field mapping is duplicated
between the two crate-local affinity_stats_snapshot helpers. Consolidate the
shared PrefixAffinityStats-to-snapshot mapping through a reusable From-style
constructor or equivalent helper near PrefixAffinityStats, then have each
crate-specific snapshot builder reuse it while preserving the runtime crate’s
target_reputation field.

In `@crates/mesh-llm-routing/src/prefix_affinity.rs`:
- Around line 91-118: Update lookup to borrow the stored AffinityEntry while
checking candidates, then clone only its target for the returned value; avoid
cloning the entire entry via entries.get(&key).cloned(). Preserve the existing
stale-entry removal, touch_key, timestamp refresh, and hit/miss statistics
behavior.
- Around line 75-87: Replace the VecDeque-based LRU bookkeeping in touch_key and
remove_key with an indexed ordering structure that avoids linear scans, String
comparisons, and element shifting on each operation. Use monotonic order stamps
with a HashMap<AffinityKey, u64> and BTreeMap<u64, AffinityKey>, or an
equivalent O(log n)/O(1) LRU implementation, while preserving eviction order and
existing entry-removal behavior.

In `@crates/mesh-llm-types/src/models/capabilities.rs`:
- Around line 13-34: Make CapabilityLevel::is_supported,
CapabilityLevel::status, and CapabilityLevel::label const fn so they can be used
in const contexts. Replace the derived-PartialEq comparison in is_supported with
a const-compatible matches! check, leaving the existing mappings and return
values unchanged.
- Around line 236-295: Refactor name_signal_level to accept a boolean gate for
its likely tier, then use it in merge_name_signal for vision, audio, reasoning,
and tool-use signals. Preserve vision’s existing allow_likely_vision behavior
while keeping supported signals and config-derived likely suppression unchanged,
including config_model_type_preserves_likely_and_supported_levels.
- Around line 500-520: The test function name
strong_name_evidence_dominates_likely_and_existing_values mischaracterizes the
assertions; rename it to reflect that name signals only upgrade existing
capability levels, such as name_signals_only_upgrade_existing_levels. Keep the
test setup and assertions unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9f2a8c44-2e2b-41a1-a946-eebc9b20b4c0

📥 Commits

Reviewing files that changed from the base of the PR and between d91d62b and bf60e61.

📒 Files selected for processing (11)
  • crates/mesh-client/src/client/control_plane.rs
  • crates/mesh-client/src/network/affinity.rs
  • crates/mesh-client/tests/control_plane_lifecycle_client.rs
  • crates/mesh-llm-host-runtime/src/api/mod.rs
  • crates/mesh-llm-host-runtime/src/api/model_targets.rs
  • crates/mesh-llm-host-runtime/src/api/split_readiness.rs
  • crates/mesh-llm-host-runtime/src/network/affinity.rs
  • crates/mesh-llm-routing/src/lib.rs
  • crates/mesh-llm-routing/src/prefix_affinity.rs
  • crates/mesh-llm-types/src/models/capabilities.rs
  • crates/model-artifact/src/lib.rs

@ndizazzo
ndizazzo force-pushed the chore/code-quality-review branch from 4215870 to 3770a3e Compare July 28, 2026 18:44
@ndizazzo
ndizazzo merged commit 060cf33 into main Jul 28, 2026
26 checks passed
@ndizazzo
ndizazzo deleted the chore/code-quality-review branch July 28, 2026 19:17
michaelneale added a commit that referenced this pull request Jul 29, 2026
…-retention

* origin/main:
  Refresh llama.cpp upstream patch queue (#1105)
  Revert "Refresh llama.cpp upstream patch queue (#1099)"
  Refresh llama.cpp upstream patch queue (#1099)
  chore(code-quality): generalized code-quality refactoring (#1098)
  Document canonical Homebrew tap (#1102)
  Rename the Node SDK npm package scope (#1101)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant