Skip to content

Commit de442d9

Browse files
committed
fix(causal_tree): resolve clippy violations in CTE code
- Add const fn to 22 functions (branch/engine/metrics/policy/state) - Replace .expect() with .map_err()? in prometheus CTE metrics - Add #[allow] to all CTE test modules (indexing_slicing etc.) - Fix unnested or-patterns, doc indent, Debug impl, map_or - Fix production indexing with .get().map_or() safe access
1 parent f7266bb commit de442d9

13 files changed

Lines changed: 58 additions & 39 deletions

File tree

src/causal_tree/branch.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ pub enum BranchLabel {
1616

1717
impl BranchLabel {
1818
/// Human-readable short name for logging / tracing.
19-
pub fn as_str(&self) -> &'static str {
19+
pub const fn as_str(self) -> &'static str {
2020
match self {
2121
Self::DirectAnswer => "direct_answer",
2222
Self::RetrieveThenAnswer => "retrieve_then_answer",
@@ -139,6 +139,7 @@ pub struct PathCommitDecision {
139139
}
140140

141141
#[cfg(test)]
142+
#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used)]
142143
mod tests {
143144
use super::*;
144145

src/causal_tree/engine.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,12 @@ impl CausalTreeEngine {
7474
}
7575

7676
/// Returns `true` if the CTE is enabled in the configuration.
77-
pub fn is_enabled(&self) -> bool {
77+
pub const fn is_enabled(&self) -> bool {
7878
self.config.enabled
7979
}
8080

8181
/// Returns a reference to the engine's configuration.
82-
pub fn config(&self) -> &CausalTreeConfig {
82+
pub const fn config(&self) -> &CausalTreeConfig {
8383
&self.config
8484
}
8585

@@ -279,6 +279,7 @@ impl CausalTreeEngine {
279279
}
280280

281281
#[cfg(test)]
282+
#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used)]
282283
mod tests {
283284
use super::*;
284285
use crate::causal_tree::branch::BranchLabel;

src/causal_tree/expander.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,17 @@ fn intent_contains_any(intent: &str, keywords: &[&str]) -> bool {
4343
return false;
4444
}
4545
// Check left boundary: start of string or non-alphanumeric.
46-
let left_ok = i == 0 || !text_bytes[i - 1].is_ascii_alphanumeric();
46+
let left_ok = i == 0
47+
|| text_bytes
48+
.get(i - 1)
49+
.map(|b| !b.is_ascii_alphanumeric())
50+
.unwrap_or(true);
4751
// Check right boundary: end of string or non-alphanumeric.
48-
let right_ok = i + klen == text_bytes.len() || !text_bytes[i + klen].is_ascii_alphanumeric();
52+
let right_ok = i + klen == text_bytes.len()
53+
|| text_bytes
54+
.get(i + klen)
55+
.map(|b| !b.is_ascii_alphanumeric())
56+
.unwrap_or(true);
4957
left_ok && right_ok
5058
})
5159
})
@@ -96,7 +104,7 @@ pub struct DefaultTreeExpander {
96104

97105
impl DefaultTreeExpander {
98106
/// Create a new expander with its sequence counter reset to zero.
99-
pub fn new() -> Self {
107+
pub const fn new() -> Self {
100108
Self {
101109
seq: std::sync::atomic::AtomicU64::new(0),
102110
}
@@ -193,7 +201,7 @@ impl DefaultTreeExpander {
193201
}
194202
matches!(
195203
state.max_risk_level(),
196-
Some(RiskLevel::High) | Some(RiskLevel::Critical)
204+
Some(RiskLevel::High | RiskLevel::Critical)
197205
)
198206
}
199207
}
@@ -319,6 +327,7 @@ impl TreeExpander for DefaultTreeExpander {
319327
// ---------------------------------------------------------------------------
320328

321329
#[cfg(test)]
330+
#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used, clippy::needless_collect)]
322331
mod tests {
323332
use super::*;
324333
use crate::causal_tree::state::{BudgetState, RiskFlag};

src/causal_tree/feedback.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ pub struct LogFeedbackWriter;
7777

7878
impl LogFeedbackWriter {
7979
/// Create a new [`LogFeedbackWriter`].
80-
pub fn new() -> Self {
80+
pub const fn new() -> Self {
8181
Self
8282
}
8383
}
@@ -123,7 +123,7 @@ pub struct NoopFeedbackWriter;
123123

124124
impl NoopFeedbackWriter {
125125
/// Create a new [`NoopFeedbackWriter`].
126-
pub fn new() -> Self {
126+
pub const fn new() -> Self {
127127
Self
128128
}
129129
}
@@ -145,6 +145,7 @@ impl FeedbackWriter for NoopFeedbackWriter {
145145
// ---------------------------------------------------------------------------
146146

147147
#[cfg(test)]
148+
#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used)]
148149
mod tests {
149150
use super::*;
150151
use crate::causal_tree::branch::{BranchLabel, CausalBranch, CommitPolicy, CostEstimate, RehearsalLevel};

src/causal_tree/metrics.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ pub struct RunObservation {
5757

5858
impl CausalTreeMetrics {
5959
/// Record a single CTE run observation.
60-
pub fn record(&mut self, obs: &RunObservation) {
60+
pub const fn record(&mut self, obs: &RunObservation) {
6161
self.total_runs += 1;
6262
if obs.hit_at_1 {
6363
self.hits_at_1 += 1;
@@ -78,7 +78,7 @@ impl CausalTreeMetrics {
7878
}
7979

8080
/// Record a circuit breaker trip event.
81-
pub fn record_circuit_breaker_trip(&mut self) {
81+
pub const fn record_circuit_breaker_trip(&mut self) {
8282
self.circuit_breaker_trips += 1;
8383
}
8484

@@ -138,6 +138,7 @@ impl CausalTreeMetrics {
138138
}
139139

140140
#[cfg(test)]
141+
#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used)]
141142
mod tests {
142143
use super::*;
143144

src/causal_tree/policy.rs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -74,16 +74,16 @@ pub struct CausalTreeConfig {
7474
pub write_metrics: bool,
7575
}
7676

77-
fn default_w_confidence() -> f32 {
77+
const fn default_w_confidence() -> f32 {
7878
0.50
7979
}
80-
fn default_w_cost() -> f32 {
80+
const fn default_w_cost() -> f32 {
8181
0.25
8282
}
83-
fn default_w_latency() -> f32 {
83+
const fn default_w_latency() -> f32 {
8484
0.25
8585
}
86-
fn default_true() -> bool {
86+
const fn default_true() -> bool {
8787
true
8888
}
8989

@@ -119,13 +119,13 @@ impl Default for CircuitBreakerState {
119119

120120
impl CircuitBreakerState {
121121
/// Record a successful CTE run — resets the failure counter.
122-
pub fn record_success(&mut self) {
122+
pub const fn record_success(&mut self) {
123123
self.consecutive_failures = 0;
124124
self.open_since = None;
125125
}
126126

127127
/// Record a failed CTE run — increments the failure counter.
128-
pub fn record_failure(&mut self) {
128+
pub const fn record_failure(&mut self) {
129129
self.consecutive_failures += 1;
130130
}
131131

@@ -135,10 +135,8 @@ impl CircuitBreakerState {
135135
return false;
136136
}
137137
// If open, check whether the cooldown has elapsed.
138-
match self.open_since {
139-
Some(opened_at) => opened_at.elapsed().as_secs() < policy.circuit_breaker_cooldown_secs,
140-
None => true,
141-
}
138+
self.open_since
139+
.map_or(true, |opened_at| opened_at.elapsed().as_secs() < policy.circuit_breaker_cooldown_secs)
142140
}
143141

144142
/// Transition to the open state if the threshold has been reached.
@@ -150,6 +148,7 @@ impl CircuitBreakerState {
150148
}
151149

152150
#[cfg(test)]
151+
#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used)]
153152
mod tests {
154153
use super::*;
155154

src/causal_tree/rehearsal.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ pub struct DefaultRehearsalEngine;
140140

141141
impl DefaultRehearsalEngine {
142142
/// Create a new [`DefaultRehearsalEngine`].
143-
pub fn new() -> Self {
143+
pub const fn new() -> Self {
144144
Self
145145
}
146146

@@ -247,6 +247,7 @@ impl RehearsalEngine for DefaultRehearsalEngine {
247247
// ---------------------------------------------------------------------------
248248

249249
#[cfg(test)]
250+
#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used)]
250251
mod tests {
251252
use super::*;
252253
use crate::causal_tree::{

src/causal_tree/scorer.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ pub struct DefaultBranchScorer;
9090

9191
impl DefaultBranchScorer {
9292
/// Create a new `DefaultBranchScorer`.
93-
pub fn new() -> Self {
93+
pub const fn new() -> Self {
9494
Self
9595
}
9696

@@ -263,6 +263,7 @@ impl BranchScorer for DefaultBranchScorer {
263263
// ---------------------------------------------------------------------------
264264

265265
#[cfg(test)]
266+
#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used)]
266267
mod tests {
267268
use super::*;
268269
use crate::causal_tree::{

src/causal_tree/selector.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ pub struct DefaultPathSelector;
6666

6767
impl DefaultPathSelector {
6868
/// Create a new [`DefaultPathSelector`].
69-
pub fn new() -> Self {
69+
pub const fn new() -> Self {
7070
Self
7171
}
7272
}
@@ -149,6 +149,7 @@ impl PathSelector for DefaultPathSelector {
149149
// ---------------------------------------------------------------------------
150150

151151
#[cfg(test)]
152+
#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used)]
152153
mod tests {
153154
use super::*;
154155
use crate::causal_tree::branch::{BranchLabel, CausalBranch, CommitPolicy, CostEstimate, RehearsalLevel};

src/causal_tree/snapshot.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ fn truncate_to_chars(s: &str, max_chars: usize) -> &str {
2727
}
2828

2929
/// Map the classified [`TaskIntent`] to a human-readable intent string.
30-
fn intent_label(intent: TaskIntent) -> &'static str {
30+
const fn intent_label(intent: TaskIntent) -> &'static str {
3131
match intent {
3232
TaskIntent::Simple => "simple",
3333
TaskIntent::Delegate => "delegate",
@@ -86,17 +86,17 @@ fn tool_result_to_artifact(_tool_call_id: &str, content: &str, index: usize) ->
8686
///
8787
/// # Parameters
8888
///
89-
/// - `session_id` — Stable session identifier (passed through).
90-
/// - `user_message` — Raw user message; truncated to [`GOAL_MAX_CHARS`]
91-
/// chars for the `goal` field.
92-
/// - `classify_result` — Output of the task classifier; drives `user_intent`.
93-
/// - `history` — Full conversation history for the current session.
89+
/// - `session_id` — Stable session identifier (passed through).
90+
/// - `user_message` — Raw user message; truncated to [`GOAL_MAX_CHARS`]
91+
/// chars for the `goal` field.
92+
/// - `classify_result` — Output of the task classifier; drives `user_intent`.
93+
/// - `history` — Full conversation history for the current session.
9494
/// - `Chat` messages with `role == "assistant"` become completed
9595
/// [`StepRecord`]s.
9696
/// - `ToolResults` entries become [`ArtifactRef`]s.
97-
/// - `side_effect_mode` — Current permission mode; controls `active_constraints`.
98-
/// - `policy` — Active [`CausalPolicy`]; used to set the
99-
/// [`BudgetState`].
97+
/// - `side_effect_mode` — Current permission mode; controls `active_constraints`.
98+
/// - `policy` — Active [`CausalPolicy`]; used to set the
99+
/// [`BudgetState`].
100100
pub fn build_causal_state(
101101
session_id: &str,
102102
user_message: &str,
@@ -168,6 +168,7 @@ pub fn build_causal_state(
168168
}
169169

170170
#[cfg(test)]
171+
#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used)]
171172
mod tests {
172173
use super::super::policy::CausalPolicy;
173174
use super::*;

0 commit comments

Comments
 (0)