use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt;
use std::str::FromStr;
use std::sync::{Arc, Mutex, OnceLock};
use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
use adk_core::{
AdkError, AgentPrincipal, Clock, ErrorCategory, ErrorComponent, IdentitySource, Memory,
MemoryEntry, SystemClock,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::audit;
use crate::error::{KernelError, MEMORY_CROSSING_CODE, MEMORY_DELETE_CODE, NOT_FOUND_CODE, Result};
use crate::sched::{QuietHours, Quotas};
mod crossing;
pub use crossing::{
CROSSING_PARTITION_ARG, Crossing, CrossingAccess, CrossingFilter, CrossingOutcome,
CrossingRecord, CrossingResource, CrossingRoute, CrossingRun, CrossingTool, PartitionPolicy,
RecurringCrossing,
};
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PartitionId(String);
impl PartitionId {
pub const DEFAULT: &'static str = "default";
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Default for PartitionId {
fn default() -> Self {
Self::new(Self::DEFAULT)
}
}
impl fmt::Display for PartitionId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for PartitionId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl From<&str> for PartitionId {
fn from(id: &str) -> Self {
Self::new(id)
}
}
impl From<String> for PartitionId {
fn from(id: String) -> Self {
Self(id)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PartitionMode {
ReadOnly,
Plan,
Ask,
Auto,
}
impl PartitionMode {
pub fn as_str(self) -> &'static str {
match self {
Self::ReadOnly => "read_only",
Self::Plan => "plan",
Self::Ask => "ask",
Self::Auto => "auto",
}
}
}
impl fmt::Display for PartitionMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.as_str())
}
}
impl FromStr for PartitionMode {
type Err = KernelError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
match text.trim().to_ascii_lowercase().replace('-', "_").as_str() {
"read_only" | "readonly" => Ok(Self::ReadOnly),
"plan" => Ok(Self::Plan),
"ask" => Ok(Self::Ask),
"auto" => Ok(Self::Auto),
other => Err(KernelError::Config {
reason: format!(
"unknown partition mode `{other}`; use read_only, plan, ask or auto"
),
}),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CrossPartition {
#[default]
Deny,
CoordinatorWithApproval,
}
impl CrossPartition {
pub fn as_str(self) -> &'static str {
match self {
Self::Deny => "deny",
Self::CoordinatorWithApproval => "coordinator_with_approval",
}
}
}
impl fmt::Display for CrossPartition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.as_str())
}
}
impl FromStr for CrossPartition {
type Err = KernelError;
fn from_str(text: &str) -> Result<Self> {
match text.trim().to_ascii_lowercase().replace('-', "_").as_str() {
"deny" => Ok(Self::Deny),
"coordinator_with_approval" | "coordinator" => Ok(Self::CoordinatorWithApproval),
other => Err(KernelError::Config {
reason: format!(
"unknown crossing setting `{other}`; use deny or coordinator_with_approval"
),
}),
}
}
}
fn ask() -> PartitionMode {
PartitionMode::Ask
}
fn unlimited(quotas: &Quotas) -> bool {
*quotas == Quotas::default()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Partition {
pub id: PartitionId,
pub class: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tenant: Option<String>,
#[serde(default = "ask")]
pub default_mode: PartitionMode,
pub memory_scope: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub drivers: Vec<String>,
#[serde(default, skip_serializing_if = "unlimited")]
pub quotas: Quotas,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quiet_hours: Option<QuietHours>,
#[serde(default)]
pub cross_partition: CrossPartition,
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub blocked_crossings: BTreeSet<PartitionId>,
}
impl Partition {
pub const PRINCIPAL_ATTRIBUTE: &'static str = "adk.partition";
pub fn new(id: impl Into<PartitionId>, class: impl Into<String>) -> Self {
let id = id.into();
Self {
memory_scope: id.as_str().to_string(),
id,
class: class.into(),
tenant: None,
default_mode: PartitionMode::Ask,
drivers: Vec::new(),
quotas: Quotas::default(),
quiet_hours: None,
cross_partition: CrossPartition::Deny,
blocked_crossings: BTreeSet::new(),
}
}
#[must_use]
pub fn with_tenant(mut self, tenant: impl Into<String>) -> Self {
self.tenant = Some(tenant.into());
self
}
#[must_use]
pub fn with_mode(mut self, mode: PartitionMode) -> Self {
self.default_mode = mode;
self
}
#[must_use]
pub fn with_memory_scope(mut self, scope: impl Into<String>) -> Self {
self.memory_scope = scope.into();
self
}
#[must_use]
pub fn with_driver(mut self, driver: impl Into<String>) -> Self {
self.drivers.push(driver.into());
self
}
#[must_use]
pub fn with_quotas(mut self, quotas: Quotas) -> Self {
self.quotas = quotas;
self
}
#[must_use]
pub fn with_quiet_hours(mut self, quiet_hours: QuietHours) -> Self {
self.quiet_hours = Some(quiet_hours);
self
}
#[must_use]
pub fn with_cross_partition(mut self, cross_partition: CrossPartition) -> Self {
self.cross_partition = cross_partition;
self
}
#[must_use]
pub fn with_blocked_crossing(mut self, to: impl Into<PartitionId>) -> Self {
self.blocked_crossings.insert(to.into());
self
}
pub fn validate(&self) -> Result<()> {
let fields = [
("id", self.id.as_str()),
("class", self.class.as_str()),
("memoryScope", self.memory_scope.as_str()),
];
for (field, value) in fields {
if value.trim().is_empty() || value.chars().any(char::is_control) {
return Err(KernelError::Config {
reason: format!(
"partition `{}`: `{field}` must be non-empty text without control \
characters",
self.id
),
});
}
}
Ok(())
}
pub fn principal(&self, app_name: &str, agent_name: &str) -> AgentPrincipal {
let mut principal = AgentPrincipal::derived(app_name, agent_name)
.with_class(self.class.clone())
.with_attribute(Self::PRINCIPAL_ATTRIBUTE, self.id.as_str());
if let Some(tenant) = &self.tenant {
principal = principal.with_tenant(tenant.clone());
}
principal
}
pub fn identity_source(&self, app_name: &str, root_agent: &str) -> Arc<dyn IdentitySource> {
Arc::new(PartitionIdentity {
partition: self.clone(),
app_name: app_name.to_string(),
root_agent: root_agent.to_string(),
})
}
pub fn scope_memory(&self, memory: Arc<dyn Memory>) -> Result<Arc<dyn Memory>> {
if !memory.supports_project_scoping() {
return Err(KernelError::Config {
reason: format!(
"partition `{}` needs a memory that keeps projects apart: this memory \
does not implement project scoping, so it would show every partition's \
entries to every other; use a MemoryService with project support",
self.id
),
});
}
Ok(Arc::new(PartitionMemory {
inner: memory,
partition: self.id.clone(),
project: self.memory_scope.clone(),
}))
}
}
#[derive(Debug)]
struct PartitionIdentity {
partition: Partition,
app_name: String,
root_agent: String,
}
#[async_trait]
impl IdentitySource for PartitionIdentity {
async fn current(&self) -> adk_core::Result<AgentPrincipal> {
Ok(self.partition.principal(&self.app_name, &self.root_agent))
}
async fn principal_for(&self, agent_name: &str) -> adk_core::Result<Option<AgentPrincipal>> {
Ok(Some(self.partition.principal(&self.app_name, agent_name)))
}
}
struct PartitionMemory {
inner: Arc<dyn Memory>,
partition: PartitionId,
project: String,
}
impl PartitionMemory {
fn refuse(&self, project: &str) -> AdkError {
AdkError::new(
ErrorComponent::Memory,
ErrorCategory::Forbidden,
MEMORY_CROSSING_CODE,
format!(
"partition `{}` reads and writes only its own memory scope `{}`, not `{project}`; \
the coordinator reaches another partition through a crossing (spec 3.2 K-I15)",
self.partition, self.project
),
)
}
}
#[async_trait]
impl Memory for PartitionMemory {
async fn search(&self, query: &str) -> adk_core::Result<Vec<MemoryEntry>> {
self.inner.search_in_project(query, &self.project).await
}
async fn health_check(&self) -> adk_core::Result<()> {
self.inner.health_check().await
}
async fn add(&self, entry: MemoryEntry) -> adk_core::Result<()> {
self.inner.add_to_project(entry, &self.project).await
}
async fn delete(&self, _query: &str) -> adk_core::Result<u64> {
Err(AdkError::new(
ErrorComponent::Memory,
ErrorCategory::Unsupported,
MEMORY_DELETE_CODE,
format!(
"partition `{}` cannot delete by query: the memory's delete reaches every \
project; delete the partition's project through its MemoryService",
self.partition
),
))
}
fn supports_project_scoping(&self) -> bool {
true
}
async fn search_in_project(
&self,
query: &str,
project_id: &str,
) -> adk_core::Result<Vec<MemoryEntry>> {
if project_id != self.project {
return Err(self.refuse(project_id));
}
self.inner.search_in_project(query, project_id).await
}
async fn add_to_project(&self, entry: MemoryEntry, project_id: &str) -> adk_core::Result<()> {
if project_id != self.project {
return Err(self.refuse(project_id));
}
self.inner.add_to_project(entry, project_id).await
}
}
#[async_trait]
pub trait PartitionStore: Send + Sync {
async fn put(&self, partition: Partition) -> Result<()>;
async fn get(&self, id: &PartitionId) -> Result<Option<Partition>>;
async fn list(&self) -> Result<Vec<Partition>>;
async fn delete(&self, id: &PartitionId) -> Result<bool>;
async fn record_crossing(&self, record: CrossingRecord) -> Result<()>;
async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>>;
async fn grant(&self, run: &str, fingerprint: &str) -> Result<()>;
async fn grants(&self, run: &str) -> Result<Vec<String>>;
async fn release_run(&self, run: &str) -> Result<u64>;
}
pub(crate) fn unknown_partition(id: &PartitionId) -> KernelError {
KernelError::Core(AdkError::new(
ErrorComponent::Server,
ErrorCategory::NotFound,
NOT_FOUND_CODE,
format!("no partition named `{id}`; list them with `adk-rust partitions`"),
))
}
const RECORDED_CAP: usize = 4096;
const INVOCATION_GRANTS_CAP: usize = 4096;
pub(crate) struct CrossingCall<'a> {
pub(crate) crossing: &'a Crossing,
pub(crate) fingerprint: &'a str,
pub(crate) run: &'a str,
pub(crate) agent: &'a str,
pub(crate) tool: &'a str,
}
#[derive(Clone)]
pub struct Partitions {
inner: Arc<PartitionsInner>,
}
struct PartitionsInner {
store: Arc<dyn PartitionStore>,
audit: OnceLock<AuditTrail>,
clock: Arc<dyn Clock>,
recorded: Mutex<HashSet<(String, String, CrossingOutcome)>>,
invocation_grants: Mutex<HashMap<String, HashSet<String>>>,
}
impl fmt::Debug for Partitions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Partitions")
.field("audit", &self.inner.audit.get().is_some())
.finish_non_exhaustive()
}
}
impl Partitions {
pub fn new(store: Arc<dyn PartitionStore>) -> Self {
Self::with_parts(store, Arc::new(SystemClock))
}
pub fn in_memory() -> Self {
Self::new(Arc::new(crate::stores::InMemoryPartitionStore::new()))
}
fn with_parts(store: Arc<dyn PartitionStore>, clock: Arc<dyn Clock>) -> Self {
Self {
inner: Arc::new(PartitionsInner {
store,
audit: OnceLock::new(),
clock,
recorded: Mutex::new(HashSet::new()),
invocation_grants: Mutex::new(HashMap::new()),
}),
}
}
#[must_use]
pub fn with_audit(self, trail: AuditTrail) -> Self {
let _ = self.inner.audit.set(trail);
self
}
#[must_use]
pub fn with_clock(self, clock: Arc<dyn Clock>) -> Self {
let partitions = Self::with_parts(Arc::clone(&self.inner.store), clock);
if let Some(trail) = self.inner.audit.get() {
let _ = partitions.inner.audit.set(trail.clone());
}
partitions
}
pub fn attach_audit(&self, trail: AuditTrail) {
let _ = self.inner.audit.set(trail);
}
pub fn store(&self) -> &Arc<dyn PartitionStore> {
&self.inner.store
}
pub async fn get(&self, id: &PartitionId) -> Result<Option<Partition>> {
self.inner.store.get(id).await
}
pub async fn list(&self) -> Result<Vec<Partition>> {
self.inner.store.list().await
}
pub async fn put(&self, partition: Partition, by: AuditActor) -> Result<()> {
partition.validate()?;
let before = self.inner.store.get(&partition.id).await?;
let to = serde_json::to_value(&partition)?;
let (action, fields, from) = match &before {
None => (audit::PARTITION_CREATED, Vec::new(), Value::Null),
Some(before) => {
let from = serde_json::to_value(before)?;
let changed: Vec<String> = match (&from, &to) {
(Value::Object(old), Value::Object(new)) => old
.keys()
.chain(new.keys())
.filter(|key| old.get(*key) != new.get(*key))
.cloned()
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
_ => Vec::new(),
};
if changed.is_empty() {
return Ok(());
}
(audit::PARTITION_CHANGED, changed, from)
}
};
self.inner.store.put(partition.clone()).await?;
let fields = json!({
"partition": partition.id,
"fields": fields,
"from": from,
"to": to,
});
self.record_audit(action, by, fields).await;
Ok(())
}
pub async fn set_mode(
&self,
id: impl Into<PartitionId>,
mode: PartitionMode,
by: AuditActor,
) -> Result<Partition> {
let id = id.into();
let partition = self.inner.store.get(&id).await?.ok_or_else(|| unknown_partition(&id))?;
let partition = partition.with_mode(mode);
self.put(partition.clone(), by).await?;
Ok(partition)
}
pub async fn block(
&self,
from: impl Into<PartitionId>,
to: impl Into<PartitionId>,
by: AuditActor,
) -> Result<Partition> {
let from = from.into();
let partition =
self.inner.store.get(&from).await?.ok_or_else(|| unknown_partition(&from))?;
let partition = partition.with_blocked_crossing(to);
self.put(partition.clone(), by).await?;
Ok(partition)
}
pub async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>> {
self.inner.store.crossings(filter).await
}
pub fn policy(&self, home: impl Into<PartitionId>) -> PartitionPolicy {
PartitionPolicy::new(self.clone(), home.into())
}
pub async fn admit(
&self,
crossing: &Crossing,
coordinator: bool,
) -> std::result::Result<(), String> {
let read = |id: &PartitionId| {
let id = id.clone();
async move {
match self.inner.store.get(&id).await {
Ok(Some(partition)) => Ok(partition),
Ok(None) => Err(format!("there is no partition named `{id}`")),
Err(error) => Err(format!(
"the partition table could not be read ({error}), so the crossing is \
refused"
)),
}
}
};
let from = read(&crossing.from).await?;
let to = read(&crossing.to).await?;
if !coordinator {
return Err(format!(
"{} belongs to partition `{}`; only the coordinator may cross into another \
partition, and only under approval",
crossing.label(),
crossing.to
));
}
for partition in [&from, &to] {
if partition.cross_partition == CrossPartition::Deny {
return Err(format!(
"partition `{}` takes part in no crossings (cross_partition: deny)",
partition.id
));
}
}
if from.blocked_crossings.contains(&crossing.to) {
return Err(format!(
"crossings to `{}` from partition `{}` are blocked",
crossing.to, crossing.from
));
}
Ok(())
}
pub async fn granted(&self, run: &CrossingRun, fingerprint: &str) -> bool {
let digest = crossing::digest(fingerprint);
match run {
CrossingRun::Invocation(id) => self
.inner
.invocation_grants
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(id)
.is_some_and(|grants| grants.contains(&digest)),
CrossingRun::Durable(id) => match self.inner.store.grants(id).await {
Ok(grants) => grants.contains(&digest),
Err(error) => {
tracing::warn!(error = %error, "could not read the run's crossing grants; the crossing asks again");
false
}
},
}
}
pub async fn grants(&self, run: &CrossingRun) -> Result<Vec<String>> {
match run {
CrossingRun::Invocation(id) => {
let grants = self.inner.invocation_grants.lock().unwrap_or_else(|e| e.into_inner());
let mut digests: Vec<String> =
grants.get(id).map(|set| set.iter().cloned().collect()).unwrap_or_default();
digests.sort();
Ok(digests)
}
CrossingRun::Durable(id) => self.inner.store.grants(id).await,
}
}
pub async fn release_run(&self, run: &CrossingRun) -> Result<u64> {
match run {
CrossingRun::Invocation(id) => Ok(self
.inner
.invocation_grants
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(id)
.map_or(0, |grants| grants.len() as u64)),
CrossingRun::Durable(id) => self.inner.store.release_run(id).await,
}
}
pub async fn executed(
&self,
crossing: &Crossing,
fingerprint: &str,
run: &CrossingRun,
agent: &str,
tool: &str,
) -> Result<()> {
let read = crossing.access == CrossingAccess::Read;
if read && self.granted(run, fingerprint).await {
return Ok(());
}
let call = CrossingCall { crossing, fingerprint, run: run.as_str(), agent, tool };
let record = self.crossing_record(&call, CrossingOutcome::Approved, None);
self.inner.store.record_crossing(record.clone()).await?;
self.audit_crossing(&record).await;
if read {
match run {
CrossingRun::Invocation(id) => {
let mut grants =
self.inner.invocation_grants.lock().unwrap_or_else(|e| e.into_inner());
if grants.len() > INVOCATION_GRANTS_CAP {
grants.clear();
}
grants.entry(id.clone()).or_default().insert(record.fingerprint);
}
CrossingRun::Durable(id) => self.inner.store.grant(id, &record.fingerprint).await?,
}
}
Ok(())
}
pub async fn recurring_crossings(
&self,
since: chrono::DateTime<chrono::Utc>,
at_least: usize,
) -> Result<Vec<RecurringCrossing>> {
let filter = CrossingFilter::default().since(since).outcomes([
CrossingOutcome::Held,
CrossingOutcome::Denied,
CrossingOutcome::RunGrant,
]);
let mut counts: std::collections::BTreeMap<
(PartitionId, PartitionId, CrossingResource, String),
usize,
> = std::collections::BTreeMap::new();
for record in self.inner.store.crossings(&filter).await? {
*counts.entry((record.from, record.to, record.resource, record.name)).or_default() += 1;
}
let mut recurring: Vec<RecurringCrossing> = counts
.into_iter()
.filter(|(_, count)| *count >= at_least)
.map(|((from, to, resource, name), count)| {
RecurringCrossing::new(from, to, resource, name, count)
})
.collect();
recurring.sort_by_key(|crossing| std::cmp::Reverse(crossing.count));
Ok(recurring)
}
pub(crate) async fn decided(
&self,
call: &CrossingCall<'_>,
call_id: Option<&str>,
outcome: CrossingOutcome,
reason: Option<String>,
) {
if let Some(call_id) = call_id {
let mut recorded = self.inner.recorded.lock().unwrap_or_else(|e| e.into_inner());
if recorded.len() > RECORDED_CAP {
recorded.clear();
}
if !recorded.insert((crossing::digest(call.fingerprint), call_id.to_string(), outcome))
{
return;
}
}
let record = self.crossing_record(call, outcome, reason);
if let Err(error) = self.inner.store.record_crossing(record.clone()).await {
tracing::warn!(error = %error, "could not write a crossing record");
}
self.audit_crossing(&record).await;
}
fn crossing_record(
&self,
call: &CrossingCall<'_>,
outcome: CrossingOutcome,
reason: Option<String>,
) -> CrossingRecord {
let crossing = call.crossing;
CrossingRecord {
id: uuid::Uuid::new_v4().to_string(),
at: self.inner.clock.now(),
run: call.run.to_string(),
agent: call.agent.to_string(),
from: crossing.from.clone(),
to: crossing.to.clone(),
resource: crossing.resource,
name: crossing.name.clone(),
access: crossing.access,
tool: call.tool.to_string(),
fingerprint: crossing::digest(call.fingerprint),
outcome,
reason,
}
}
async fn audit_crossing(&self, record: &CrossingRecord) {
let actor = match adk_core::AgentId::new(record.agent.clone()) {
Ok(agent) => AuditActor { agent: Some(agent), ..AuditActor::default() },
Err(_) => AuditActor::default(),
};
let fields = json!({
"partition": record.from,
"to": record.to,
"resource": record.resource,
"name": record.name,
"access": record.access,
"outcome": record.outcome,
"run": record.run,
"tool": record.tool,
"fingerprintDigest": record.fingerprint,
"reason": record.reason,
"by": record.agent,
});
self.record_audit(audit::PARTITION_CROSSING, actor, fields).await;
}
async fn record_audit(&self, action: &str, actor: AuditActor, fields: Value) {
let Some(trail) = self.inner.audit.get() else { return };
let mut draft =
AuditRecordDraft::new(AuditRecordKind::Other(audit::KERNEL_AUDIT_KIND.into()), action)
.actor(actor);
if let Value::Object(fields) = fields {
for (key, value) in fields {
draft = draft.ext(key, value);
}
}
if let Err(error) = trail.record(draft).await {
tracing::warn!(audit.action = action, error = %error, "could not write a partition audit record");
}
}
}