feat(suppress): consume per-app suppressions at trigger + route dispatch (§11 tail S3)

The runtime half — suppressions now actually decline inherited templates.

- Triggers (live, per-event): a correlated NOT EXISTS anti-join
  (TRIGGER_SUPPRESSION_ANTIJOIN) appended to all four dispatch match
  queries (list_matching_kv/docs/files + the pubsub fan-out). It excludes a
  group-owned trigger whose handler script name the firing app suppresses;
  `$1` is the firing app (already bound), and the `t.group_id IS NOT NULL`
  guard keeps an app's OWN trigger unsuppressable.
- Routes (rebuild-time): compile_effective_routes takes a
  `suppressed_paths: &HashSet<(AppId, path)>` and drops an inherited
  (`depth > 0`) route at a suppressed path — the binding 404s.
  rebuild_route_table loads the set via a new
  RouteRepository::list_route_suppressions, so every existing rebuild edge
  (route CRUD, apply, tree mutations) already applies it. No new
  invalidation edges; the marker CASCADEs on app delete.

Pinned by tests/template_suppression.rs (live DB): a suppressing app
matches NEITHER the inherited trigger NOR route; a sibling that did not
suppress still inherits both; the app's OWN trigger on the suppressed
handler still fires (suppression is inheritance-only).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-07-01 07:39:06 +02:00
parent 32cb6c1f1f
commit 4b5bf72a66
6 changed files with 339 additions and 14 deletions

View File

@@ -83,14 +83,17 @@ impl PubsubRepo for PostgresPubsubRepo {
// §11 tail: the chain union picks up the app's own pubsub triggers AND
// ancestor-group pubsub TEMPLATES (live, no materialization). The outbox
// row below stamps the firing `ctx.app_id`, so a template runs under the
// publishing app — the inheriting-app boundary.
// publishing app — the inheriting-app boundary. The suppression
// anti-join drops an inherited template whose handler the app opts out
// of (`$1` = ctx.app_id).
let rows: Vec<PubsubTriggerRow> = sqlx::query_as(&format!(
"{CHAIN_LEVELS_CTE} \
SELECT t.id, t.script_id, d.topic_pattern \
FROM triggers t \
JOIN pubsub_trigger_details d ON d.trigger_id = t.id \
JOIN chain c ON (t.app_id = c.app_owner OR t.group_id = c.group_owner) \
WHERE t.kind = 'pubsub' AND t.enabled = TRUE"
WHERE t.kind = 'pubsub' AND t.enabled = TRUE{ANTIJOIN}",
ANTIJOIN = crate::trigger_repo::TRIGGER_SUPPRESSION_ANTIJOIN,
))
.bind(ctx.app_id.into_inner())
.fetch_all(&mut *tx)

View File

@@ -406,7 +406,14 @@ pub async fn rebuild_route_table(
table: &RouteTable,
) -> Result<(), ScriptRepositoryError> {
let effective = routes.list_effective().await?;
let compiled = compile_effective_routes(&effective);
// §11 tail: `(app_id, path)` route suppressions — an inherited route at a
// suppressed path is dropped from the app's slice (404).
let suppressed: std::collections::HashSet<(AppId, String)> = routes
.list_route_suppressions()
.await?
.into_iter()
.collect();
let compiled = compile_effective_routes(&effective, &suppressed);
table.replace_all(compiled);
Ok(())
}
@@ -429,14 +436,23 @@ pub async fn rebuild_route_table(
/// **Disabled + inherited (§4.3 semantic):** the `enabled` filter runs *before*
/// the shadow check, so a **disabled** own-route does NOT claim its binding — an
/// enabled ancestor-group template at the same binding then falls through and
/// serves (disabled = "indistinguishable from absent"). The corollary: a
/// descendant cannot 404 an inherited route by disabling a same-path own route;
/// a true per-app opt-out is deferred (§4.5).
/// serves (disabled = "indistinguishable from absent"). To actually 404 an
/// inherited route, a descendant SUPPRESSES its path (§11 tail, the
/// `suppressed_paths` set) — the deliberate per-app opt-out.
///
/// `suppressed_paths` holds `(app_id, path)` route suppressions: an INHERITED
/// row (`depth > 0`) whose `(effective_app_id, path)` is present is skipped
/// entirely (the binding is absent → 404). Gated to `depth > 0` so an app can
/// only decline what it inherits, never its own route.
///
/// Requires `rows` ordered by `(effective_app_id, depth ASC)` — which
/// [`RouteRepository::list_effective`] guarantees — so first-seen is nearest.
#[must_use]
pub fn compile_effective_routes(rows: &[EffectiveRoute]) -> Vec<CompiledRoute> {
#[allow(clippy::implicit_hasher)] // every caller uses the default hasher
pub fn compile_effective_routes(
rows: &[EffectiveRoute],
suppressed_paths: &std::collections::HashSet<(AppId, String)>,
) -> Vec<CompiledRoute> {
let mut seen: std::collections::HashSet<(AppId, String)> = std::collections::HashSet::new();
let mut out = Vec::new();
for er in rows {
@@ -445,6 +461,12 @@ pub fn compile_effective_routes(rows: &[EffectiveRoute]) -> Vec<CompiledRoute> {
if !er.route.enabled {
continue;
}
// §11 tail: an inherited route whose path this app suppresses is
// dropped — the binding 404s. Gated to inherited rows (`depth > 0`).
if er.depth > 0 && suppressed_paths.contains(&(er.effective_app_id, er.route.path.clone()))
{
continue;
}
// A nearer owner already claimed this binding for this app → shadow.
if !seen.insert((er.effective_app_id, binding_key(&er.route))) {
continue;
@@ -739,6 +761,11 @@ mod tests {
}
}
/// No route suppressions — the common case for these compile tests.
fn no_suppress() -> std::collections::HashSet<(AppId, String)> {
std::collections::HashSet::new()
}
#[test]
fn compile_effective_skips_uncompilable_rows_instead_of_failing() {
// H1 regression guard: a stored route whose path is now reserved
@@ -750,7 +777,7 @@ mod tests {
let good_b = route_with_path("/items");
let rows = [eff(&good_a), eff(&bad), eff(&good_b)];
let compiled = compile_effective_routes(&rows);
let compiled = compile_effective_routes(&rows, &no_suppress());
let ids: Vec<Uuid> = compiled.iter().map(|c| c.route_id).collect();
assert_eq!(compiled.len(), 2, "the reserved row must be dropped");
@@ -769,7 +796,7 @@ mod tests {
let active = route_with_path("/on");
let mut disabled = route_with_path("/off");
disabled.enabled = false;
let compiled = compile_effective_routes(&[eff(&active), eff(&disabled)]);
let compiled = compile_effective_routes(&[eff(&active), eff(&disabled)], &no_suppress());
let ids: Vec<Uuid> = compiled.iter().map(|c| c.route_id).collect();
assert_eq!(ids, vec![active.id], "only the enabled route compiles");
}
@@ -804,7 +831,7 @@ mod tests {
route: other_template.clone(),
},
];
let ids: Vec<Uuid> = compile_effective_routes(&rows)
let ids: Vec<Uuid> = compile_effective_routes(&rows, &no_suppress())
.iter()
.map(|c| c.route_id)
.collect();

View File

@@ -60,6 +60,12 @@ pub trait RouteRepository: Send + Sync {
) -> Result<Vec<Route>, ScriptRepositoryError> {
Ok(Vec::new())
}
/// §11 tail per-app opt-out: all `(app_id, path)` ROUTE suppressions. The
/// route-table rebuild drops an inherited route at a suppressed path.
/// Defaults empty (non-Postgres impls have no suppressions).
async fn list_route_suppressions(&self) -> Result<Vec<(AppId, String)>, ScriptRepositoryError> {
Ok(Vec::new())
}
/// §11 tail: every route resolved for every app — each app's own routes
/// PLUS its ancestor-group templates, tagged with the effective app and
/// the owner's chain depth. The in-memory RouteTable rebuild consumes this
@@ -156,6 +162,15 @@ impl RouteRepository for PostgresRouteRepository {
Ok(rows.into_iter().map(Into::into).collect())
}
async fn list_route_suppressions(&self) -> Result<Vec<(AppId, String)>, ScriptRepositoryError> {
let rows: Vec<(Uuid, String)> = sqlx::query_as(
"SELECT app_id, reference FROM template_suppressions WHERE target_kind = 'route'",
)
.fetch_all(&self.pool)
.await?;
Ok(rows.into_iter().map(|(a, r)| (a.into(), r)).collect())
}
async fn list_effective(&self) -> Result<Vec<EffectiveRoute>, ScriptRepositoryError> {
// The all-apps generalization of CHAIN_LEVELS_CTE: for EVERY app, walk
// its ancestor-group chain, then join routes owned at each level. A

View File

@@ -17,6 +17,19 @@ use uuid::Uuid;
use crate::config_resolver::CHAIN_LEVELS_CTE;
use crate::trigger_config::BackoffShape;
/// §11 tail per-app opt-out: exclude an INHERITED (group-owned) trigger whose
/// handler script name the firing app suppresses. Appended to each dispatch
/// match query's WHERE clause; `$1` is the firing app_id (already bound by the
/// `CHAIN_LEVELS_CTE`). The `t.group_id IS NOT NULL` guard keeps an app's OWN
/// trigger unsuppressable (an app can only decline what it inherits).
pub(crate) const TRIGGER_SUPPRESSION_ANTIJOIN: &str = " \
AND NOT EXISTS ( \
SELECT 1 FROM template_suppressions ts \
JOIN scripts s ON s.id = t.script_id \
WHERE ts.app_id = $1 AND ts.target_kind = 'trigger' \
AND LOWER(ts.reference) = LOWER(s.name) \
AND t.group_id IS NOT NULL)";
#[derive(Debug, thiserror::Error)]
pub enum TriggerRepoError {
#[error("database error: {0}")]
@@ -1318,7 +1331,7 @@ impl TriggerRepo for PostgresTriggerRepo {
FROM triggers t \
JOIN kv_trigger_details d ON d.trigger_id = t.id \
JOIN chain c ON (t.app_id = c.app_owner OR t.group_id = c.group_owner) \
WHERE t.kind = 'kv' AND t.enabled = TRUE"
WHERE t.kind = 'kv' AND t.enabled = TRUE{TRIGGER_SUPPRESSION_ANTIJOIN}"
))
.bind(app_id.into_inner())
.fetch_all(&self.pool)
@@ -1368,7 +1381,7 @@ impl TriggerRepo for PostgresTriggerRepo {
FROM triggers t \
JOIN docs_trigger_details d ON d.trigger_id = t.id \
JOIN chain c ON (t.app_id = c.app_owner OR t.group_id = c.group_owner) \
WHERE t.kind = 'docs' AND t.enabled = TRUE"
WHERE t.kind = 'docs' AND t.enabled = TRUE{TRIGGER_SUPPRESSION_ANTIJOIN}"
))
.bind(app_id.into_inner())
.fetch_all(&self.pool)
@@ -1415,7 +1428,7 @@ impl TriggerRepo for PostgresTriggerRepo {
FROM triggers t \
JOIN files_trigger_details d ON d.trigger_id = t.id \
JOIN chain c ON (t.app_id = c.app_owner OR t.group_id = c.group_owner) \
WHERE t.kind = 'files' AND t.enabled = TRUE"
WHERE t.kind = 'files' AND t.enabled = TRUE{TRIGGER_SUPPRESSION_ANTIJOIN}"
))
.bind(app_id.into_inner())
.fetch_all(&self.pool)

View File

@@ -63,7 +63,13 @@ async fn app_under(pool: &PgPool, slug: &str, group: Uuid) -> Uuid {
/// ancestor-group templates, after nearest-wins shadowing.
async fn slice_paths(repo: &PostgresRouteRepository, app: Uuid) -> Vec<(String, Uuid)> {
let effective = repo.list_effective().await.expect("list_effective");
compile_effective_routes(&effective)
let suppressed = repo
.list_route_suppressions()
.await
.expect("list_route_suppressions")
.into_iter()
.collect();
compile_effective_routes(&effective, &suppressed)
.into_iter()
.filter(|c| c.app_id == AppId::from(app))
.map(|c| {

View File

@@ -0,0 +1,261 @@
//! §11 tail integration test: per-app opt-out of inherited group templates.
//! An app that declares a suppression must NOT match the inherited TRIGGER
//! (dispatch anti-join) nor serve the inherited ROUTE (rebuild-time skip); a
//! sibling app with no suppression still inherits both. Suppression is
//! inheritance-only — an app's OWN trigger on the suppressed handler still
//! fires.
//!
//! Deterministic: drives `list_matching_kv` + `list_effective` /
//! `compile_effective_routes` directly (no async dispatcher). Skips cleanly
//! when `DATABASE_URL` is unset.
#![allow(
clippy::needless_pass_by_value,
clippy::many_single_char_names,
clippy::too_many_lines
)]
use std::collections::HashSet;
use picloud_manager_core::route_admin::compile_effective_routes;
use picloud_manager_core::route_repo::{PostgresRouteRepository, RouteRepository};
use picloud_manager_core::trigger_repo::{PostgresTriggerRepo, TriggerRepo};
use picloud_shared::{AppId, KvEventOp};
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use uuid::Uuid;
async fn pool_or_skip() -> Option<PgPool> {
let Ok(url) = std::env::var("DATABASE_URL") else {
eprintln!("template_suppression: DATABASE_URL unset — skipping");
return None;
};
let pool = PgPoolOptions::new()
.max_connections(2)
.connect(&url)
.await
.expect("connect to DATABASE_URL");
sqlx::migrate!("./migrations")
.run(&pool)
.await
.expect("apply migrations");
Some(pool)
}
async fn id1(pool: &PgPool, sql: &str, bind: &str) -> Uuid {
let row: (Uuid,) = sqlx::query_as(sql)
.bind(bind)
.fetch_one(pool)
.await
.expect("insert returning id");
row.0
}
async fn app_under(pool: &PgPool, slug: &str, group: Uuid) -> Uuid {
let row: (Uuid,) =
sqlx::query_as("INSERT INTO apps (slug, name, group_id) VALUES ($1, $1, $2) RETURNING id")
.bind(slug)
.bind(group)
.fetch_one(pool)
.await
.expect("app insert");
row.0
}
/// Whether `app`'s compiled route slice serves `/hello`.
async fn serves_hello(repo: &PostgresRouteRepository, app: Uuid) -> bool {
let effective = repo.list_effective().await.expect("list_effective");
let suppressed: HashSet<(AppId, String)> = repo
.list_route_suppressions()
.await
.expect("list_route_suppressions")
.into_iter()
.collect();
compile_effective_routes(&effective, &suppressed)
.into_iter()
.any(|c| c.app_id == AppId::from(app) && format!("{:?}", c.path).contains("/hello"))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn suppression_declines_inherited_trigger_and_route_only_for_declaring_app() {
let Some(pool) = pool_or_skip().await else {
return;
};
let sfx = Uuid::new_v4().simple().to_string();
let admin = id1(
&pool,
"INSERT INTO admin_users (username, password_hash) VALUES ($1, 'x') RETURNING id",
&format!("ts-{sfx}"),
)
.await;
// Group G owns a handler `audit` + a kv trigger template + a /hello route
// template, both bound to it.
let g = id1(
&pool,
"INSERT INTO groups (slug, name) VALUES ($1, $1) RETURNING id",
&format!("ts-g-{sfx}"),
)
.await;
let handler: (Uuid,) = sqlx::query_as(
"INSERT INTO scripts (name, source, group_id) VALUES ($1, 'x', $2) RETURNING id",
)
.bind(format!("audit-{sfx}"))
.bind(g)
.fetch_one(&pool)
.await
.expect("group handler");
let handler_name = format!("audit-{sfx}");
let tmpl: (Uuid,) = sqlx::query_as(
"INSERT INTO triggers \
(group_id, script_id, kind, enabled, dispatch_mode, \
retry_max_attempts, retry_backoff, retry_base_ms, \
registered_by_principal, name) \
VALUES ($1, $2, 'kv', TRUE, 'async', 3, 'exponential', 1000, $3, $4) RETURNING id",
)
.bind(g)
.bind(handler.0)
.bind(admin)
.bind(format!("tmpl-{sfx}"))
.fetch_one(&pool)
.await
.expect("kv template");
sqlx::query(
"INSERT INTO kv_trigger_details (trigger_id, collection_glob, ops) \
VALUES ($1, '*', ARRAY['insert'])",
)
.bind(tmpl.0)
.execute(&pool)
.await
.expect("kv details");
sqlx::query(
"INSERT INTO routes (group_id, script_id, host_kind, host, path_kind, path, method) \
VALUES ($1, $2, 'any', '', 'exact', '/hello', NULL)",
)
.bind(g)
.bind(handler.0)
.execute(&pool)
.await
.expect("route template");
// App A (suppresses both) + app B (no suppression), both under G.
let a = app_under(&pool, &format!("ts-a-{sfx}"), g).await;
let b = app_under(&pool, &format!("ts-b-{sfx}"), g).await;
sqlx::query(
"INSERT INTO template_suppressions (app_id, target_kind, reference) \
VALUES ($1, 'trigger', $2), ($1, 'route', '/hello')",
)
.bind(a)
.bind(&handler_name)
.execute(&pool)
.await
.expect("suppressions for A");
let trig = PostgresTriggerRepo::new(pool.clone());
let routes = PostgresRouteRepository::new(pool.clone());
// A suppressed → neither the inherited trigger matches nor the route serves.
let a_trig = trig
.list_matching_kv(AppId::from(a), "users", KvEventOp::Insert)
.await
.expect("match A");
assert!(
!a_trig.iter().any(|m| m.trigger_id == tmpl.0.into()),
"the suppressing app must NOT match the inherited trigger"
);
assert!(
!serves_hello(&routes, a).await,
"the suppressing app must NOT serve the inherited route"
);
// B did not suppress → still inherits both.
let b_trig = trig
.list_matching_kv(AppId::from(b), "users", KvEventOp::Insert)
.await
.expect("match B");
assert!(
b_trig.iter().any(|m| m.trigger_id == tmpl.0.into()),
"a sibling app that did not suppress still inherits the trigger"
);
assert!(
serves_hello(&routes, b).await,
"a sibling app that did not suppress still serves the route"
);
// Suppression is inheritance-only: A's OWN kv trigger on the same handler
// name (a distinct app-owned script) still fires despite the suppression.
let a_own_script: (Uuid,) = sqlx::query_as(
"INSERT INTO scripts (name, source, app_id) VALUES ($1, 'x', $2) RETURNING id",
)
.bind(&handler_name)
.bind(a)
.fetch_one(&pool)
.await
.expect("A own script");
let a_own_trig: (Uuid,) = sqlx::query_as(
"INSERT INTO triggers \
(app_id, script_id, kind, enabled, dispatch_mode, \
retry_max_attempts, retry_backoff, retry_base_ms, \
registered_by_principal, name) \
VALUES ($1, $2, 'kv', TRUE, 'async', 3, 'exponential', 1000, $3, $4) RETURNING id",
)
.bind(a)
.bind(a_own_script.0)
.bind(admin)
.bind(format!("own-{sfx}"))
.fetch_one(&pool)
.await
.expect("A own trigger");
sqlx::query(
"INSERT INTO kv_trigger_details (trigger_id, collection_glob, ops) \
VALUES ($1, '*', ARRAY['insert'])",
)
.bind(a_own_trig.0)
.execute(&pool)
.await
.expect("A own kv details");
let a_after = trig
.list_matching_kv(AppId::from(a), "users", KvEventOp::Insert)
.await
.expect("match A after own trigger");
assert!(
a_after.iter().any(|m| m.trigger_id == a_own_trig.0.into()),
"the app's OWN trigger fires — suppression only declines inherited ones"
);
assert!(
!a_after.iter().any(|m| m.trigger_id == tmpl.0.into()),
"the inherited trigger stays suppressed"
);
// Cleanup (FK order).
let _ = sqlx::query("DELETE FROM triggers WHERE id = ANY($1)")
.bind(vec![tmpl.0, a_own_trig.0])
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM routes WHERE group_id = $1")
.bind(g)
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM template_suppressions WHERE app_id = $1")
.bind(a)
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM scripts WHERE id = ANY($1)")
.bind(vec![handler.0, a_own_script.0])
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM apps WHERE id = ANY($1)")
.bind(vec![a, b])
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM groups WHERE id = $1")
.bind(g)
.execute(&pool)
.await;
let _ = sqlx::query("DELETE FROM admin_users WHERE id = $1")
.bind(admin)
.execute(&pool)
.await;
}