Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

docs(security): document egress module and its emit pipeline

Steven Enamakel2f3cb81c83b8
diff --git a/crates/openhuman-core/src/security/egress/README.md b/crates/openhuman-core/src/security/egress/README.md
index 8bffc79720..18475aa097 100644
--- a/crates/openhuman-core/src/security/egress/README.md
+++ b/crates/openhuman-core/src/security/egress/README.md
@@ -29,7 +29,7 @@ plus the `LocalOnly` enforcement chokepoint built on top of it.
`security::approval::APPROVAL_CHAT_CONTEXT`, and fire-and-forget publishes
`DomainEvent::ExternalTransferPending` on `crate::core::bus::BUS`. This
never blocks or fails the caller.
-- `dedup_turn_scope(f)`: runs `f` with a per-turn dedup ledger so a single
+- `EgressLedger::per_turn()` / `emit_external_transfer_in(&ledger, d)`: an explicit per-turn dedup ledger, passed down the provider factory chain, so a single
managed chat turn's multi-model fan-out (primary + workload-tier + summarizer
builds) collapses repeated disclosures of the same destination into one
event; every other call path emits unconditionally.
diff --git a/crates/openhuman-core/src/security/egress/emit.rs b/crates/openhuman-core/src/security/egress/emit.rs
index 99f7e1d9b1..3d70ce4677 100644
--- a/crates/openhuman-core/src/security/egress/emit.rs
+++ b/crates/openhuman-core/src/security/egress/emit.rs
@@ -14,38 +14,57 @@
//! - **S4** adds an approval arm (park the transfer until the user decides).
//! - **S7** adds enforcement (block the transfer under a restrictive policy).
-use std::cell::RefCell;
use std::collections::HashSet;
+use std::sync::{Arc, Mutex};
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
use super::types::EgressDescriptor;
-tokio::task_local! {
- /// Per-turn dedup ledger for external-transfer disclosures. Present only
- /// inside [`dedup_turn_scope`] (the managed-turn model-build fan-out); absent
- /// on every other egress path, where each `emit_external_transfer` publishes
- /// unconditionally.
- static EGRESS_TURN_DEDUP: RefCell<HashSet<String>>;
-}
-
-/// Run `f` with a fresh per-turn egress-dedup ledger in scope. Repeated
-/// disclosures of the *same* destination within `f` collapse to one event.
+/// Per-turn dedup ledger for external-transfer disclosures, passed explicitly
+/// down the provider factory chain by the managed-turn model build
+/// (`build_turn_models_crate`). [`EgressLedger::per_turn`] collapses repeated
+/// disclosures of the *same* destination to one event; [`EgressLedger::none`]
+/// (every other egress path) publishes unconditionally.
///
-/// Wraps the turn-model build fan-out (`build_turn_models_crate`): a single
-/// managed chat turn constructs the primary model, one model per workload route
-/// tier, and a summarizer, and each managed construction resolves through the
-/// same `resolve_managed_backend` chokepoint. Without this scope, one user
-/// prompt publishes an `ExternalTransferPending` per construction — many
-/// identical `openhuman` disclosures for a single logical destination (codex
-/// P2, PR #4812). Distinct tier *models* still disclose once each: they are real
-/// candidate destinations. The residual gap — a candidate tier disclosed at
-/// construction but never actually dispatched to — is inherent to emitting at
-/// build time rather than at request dispatch (the crate owns dispatch); dedup
-/// bounds the noise to one event per distinct destination per turn.
-pub fn dedup_turn_scope<T>(f: impl FnOnce() -> T) -> T {
- EGRESS_TURN_DEDUP.sync_scope(RefCell::new(HashSet::new()), f)
+/// A single managed chat turn constructs the primary model, one model per
+/// workload route tier, and a summarizer, and each managed construction resolves
+/// through the same `resolve_managed_backend` chokepoint. Without a shared
+/// ledger, one user prompt publishes an `ExternalTransferPending` per
+/// construction, many identical `openhuman` disclosures for a single logical
+/// destination (codex P2, PR #4812). Distinct tier *models* still disclose once
+/// each: they are real candidate destinations. The residual gap, a candidate
+/// tier disclosed at construction but never actually dispatched to, is
+/// inherent to emitting at build time rather than at request dispatch (the
+/// crate owns dispatch); dedup bounds the noise to one event per distinct
+/// destination per turn.
+#[derive(Clone, Debug, Default)]
+pub struct EgressLedger(Option<Arc<Mutex<HashSet<String>>>>);
+
+impl EgressLedger {
+ /// No ledger: every disclosure publishes.
+ pub fn none() -> Self {
+ Self(None)
+ }
+
+ /// A fresh ledger that collapses repeat disclosures of one destination.
+ pub fn per_turn() -> Self {
+ Self(Some(Arc::new(Mutex::new(HashSet::new()))))
+ }
+
+ /// Returns `true` when `descriptor` was already disclosed through this
+ /// ledger. Records it as seen on first sight. Always `false` for
+ /// [`EgressLedger::none`] (no ledger, nothing suppressed).
+ fn already_disclosed(&self, descriptor: &EgressDescriptor) -> bool {
+ match &self.0 {
+ Some(seen) => !seen
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .insert(dedup_key(descriptor)),
+ None => false,
+ }
+ }
}
/// Stable dedup key for a descriptor: destination + reason. Two disclosures with
@@ -57,15 +76,6 @@ fn dedup_key(descriptor: &EgressDescriptor) -> String {
)
}
-/// Returns `true` when `descriptor` was already disclosed earlier in the current
-/// [`dedup_turn_scope`]. Records it as seen on first sight. Always `false`
-/// outside a dedup scope (no ledger → nothing suppressed).
-fn already_disclosed_this_turn(descriptor: &EgressDescriptor) -> bool {
- EGRESS_TURN_DEDUP
- .try_with(|seen| !seen.borrow_mut().insert(dedup_key(descriptor)))
- .unwrap_or(false)
-}
-
/// Best-effort ambient chat routing for the current turn, mirroring
/// `artifacts::store::current_chat_context`. Returns
/// `(thread_id, client_id, request_id)`, each `None` outside a chat-scoped
@@ -89,6 +99,12 @@ fn current_chat_context() -> (Option<String>, Option<String>, Option<String>) {
/// Fire-and-forget: [`publish_global`] never blocks and never fails the caller,
/// so an egress site can call this unconditionally on its hot path.
pub fn emit_external_transfer(descriptor: EgressDescriptor) {
+ emit_external_transfer_in(&EgressLedger::none(), descriptor);
+}
+
+/// [`emit_external_transfer`] through an explicit per-turn [`EgressLedger`]:
+/// repeated disclosures of one destination collapse to a single event.
+pub fn emit_external_transfer_in(ledger: &EgressLedger, descriptor: EgressDescriptor) {
if !descriptor.is_external {
log::trace!(
"[privacy][egress] local transfer provider={} service={} reason={:?} — not external, not emitting",
@@ -99,7 +115,7 @@ pub fn emit_external_transfer(descriptor: EgressDescriptor) {
return;
}
- if already_disclosed_this_turn(&descriptor) {
+ if ledger.already_disclosed(&descriptor) {
log::trace!(
"[privacy][egress] duplicate transfer provider={} service={} reason={:?} — already disclosed this turn, not re-emitting",
descriptor.provider_slug,
diff --git a/crates/openhuman-core/src/security/egress/emit_tests.rs b/crates/openhuman-core/src/security/egress/emit_tests.rs
index b7c68b525f..849b7a249e 100644
--- a/crates/openhuman-core/src/security/egress/emit_tests.rs
+++ b/crates/openhuman-core/src/security/egress/emit_tests.rs
@@ -103,26 +103,28 @@ async fn attaches_ambient_chat_context() {
assert_eq!(client_id.as_deref(), Some("client-abc"));
}
-/// Inside a [`dedup_turn_scope`], repeated disclosures of the *same* destination
+/// Inside a [`EgressLedger::per_turn`], repeated disclosures of the *same* destination
/// (provider/service/reason) collapse to a single event, while a distinct
/// destination still publishes — the managed-turn fan-out fix (codex P2, #4812).
#[tokio::test]
-async fn dedup_turn_scope_collapses_repeat_destination() {
+async fn per_turn_ledger_collapses_repeat_destination() {
crate::core::bus::init().await.expect("bus init");
let mut rx = crate::core::bus::BUS.get().unwrap().receiver();
let dup = "svc-dedup-dup-test";
let distinct = "svc-dedup-distinct-test";
let sentinel = "svc-dedup-sentinel-test";
- dedup_turn_scope(|| {
- emit_external_transfer(EgressDescriptor::inference("openhuman", dup, true));
- // Same destination again — must be suppressed within the turn.
- emit_external_transfer(EgressDescriptor::inference("openhuman", dup, true));
- // A distinct destination (different service) still discloses.
- emit_external_transfer(EgressDescriptor::inference("openhuman", distinct, true));
- // Sentinel closes the drain window.
- emit_external_transfer(EgressDescriptor::network_fetch(sentinel));
- });
+ let ledger = EgressLedger::per_turn();
+ emit_external_transfer_in(&ledger, EgressDescriptor::inference("openhuman", dup, true));
+ // Same destination again — must be suppressed within the turn.
+ emit_external_transfer_in(&ledger, EgressDescriptor::inference("openhuman", dup, true));
+ // A distinct destination (different service) still discloses.
+ emit_external_transfer_in(
+ &ledger,
+ EgressDescriptor::inference("openhuman", distinct, true),
+ );
+ // Sentinel closes the drain window.
+ emit_external_transfer_in(&ledger, EgressDescriptor::network_fetch(sentinel));
let mut dup_count = 0;
let mut distinct_seen = false;
@@ -153,7 +155,7 @@ async fn dedup_turn_scope_collapses_repeat_destination() {
);
}
-/// Outside any [`dedup_turn_scope`] (CLI / cron / a single egress site) there is
+/// Outside any [`EgressLedger::per_turn`] (CLI / cron / a single egress site) there is
/// no ledger, so every `emit_external_transfer` publishes — dedup never leaks
/// across unrelated calls.
#[tokio::test]
diff --git a/crates/openhuman-core/src/security/egress/mod.rs b/crates/openhuman-core/src/security/egress/mod.rs
index 20ea6f52ec..0c3ac2e364 100644
--- a/crates/openhuman-core/src/security/egress/mod.rs
+++ b/crates/openhuman-core/src/security/egress/mod.rs
@@ -11,6 +11,6 @@ pub mod emit;
pub mod enforce;
pub mod types;
-pub use emit::{dedup_turn_scope, emit_external_transfer};
+pub use emit::{emit_external_transfer, emit_external_transfer_in, EgressLedger};
pub use enforce::{enforce_egress, local_only_blocks, local_only_tool_block};
pub use types::{DataKind, EgressDescriptor, EgressReason, IdentificationRisk};