From 56aa98f00536b81d05d722b898b8cfb1e0eb309d Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 13 May 2026 20:43:39 -0500 Subject: [PATCH] perf(persona): single-allocation hex encoding in content_hash_sha256 (#1145) Replaces `format!()` per byte with `write!()` into the pre-allocated buffer. Previous code allocated 32 small Strings per hash (one per byte's `format!()` call); now allocates exactly one String for the whole output. Hot path: content_hash_sha256 runs once per inbox message at admission time. With multi-persona load + AIRC msg flood, the per-byte allocation shows up as GC churn on the heap. Same correctness; same canonical "sha256:" output. 16/16 tests green (persona::inbox_admission unchanged in scope). Spotted by claude-tab-2 in their post-merge review of continuum#1143. Card: continuum#1145. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../continuum-core/src/persona/inbox_admission.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/workers/continuum-core/src/persona/inbox_admission.rs b/src/workers/continuum-core/src/persona/inbox_admission.rs index 5429184f2..ce10f7244 100644 --- a/src/workers/continuum-core/src/persona/inbox_admission.rs +++ b/src/workers/continuum-core/src/persona/inbox_admission.rs @@ -59,6 +59,8 @@ //! needs envelope material this module's input doesn't carry; that //! conversion is a separate function in a separate slice (PR-5+). +use std::fmt::Write as _; + use sha2::{Digest, Sha256}; use super::admission::{ @@ -133,6 +135,12 @@ impl TrustMapping { /// Canonical content hash format used by all admission paths. Returns /// `"sha256:"` so dedup keys are stable across origin /// kinds (chat / AIRC / tool) and machine boundaries. +/// +/// Hot path: called once per inbox message at admission time. Hex +/// encoding writes directly into the preallocated string buffer +/// (single allocation total) rather than `format!()` per byte (which +/// allocated 32 small `String`s per hash). See claude-tab-2's review +/// nit on continuum#1143. pub fn content_hash_sha256(content: &str) -> String { let mut hasher = Sha256::new(); hasher.update(content.as_bytes()); @@ -140,7 +148,10 @@ pub fn content_hash_sha256(content: &str) -> String { let mut hex = String::with_capacity(7 + digest.len() * 2); hex.push_str("sha256:"); for byte in digest { - hex.push_str(&format!("{:02x}", byte)); + // `write!` into a `String` cannot fail — the `Write` impl for + // `String` returns `Ok` unconditionally — so the unwrap is the + // standard idiom for this pattern. + write!(&mut hex, "{:02x}", byte).expect("write to String never fails"); } hex }