Skip to content

Commit 659b792

Browse files
wesbillmanCarl
andcommitted
fix(workflows): dispatch and audit repaired deletion retries
Only state-changing retries reach normal dispatch; completed duplicates stay silent. Cover live delivery, audit fencing, and intentional backdating. Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz> Signed-off-by: Wes <[email protected]>
1 parent c4db359 commit 659b792

6 files changed

Lines changed: 289 additions & 61 deletions

File tree

‎crates/buzz-db/src/store/workflow.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
//! - All list queries have a bounded LIMIT to prevent unbounded scans.
99
1010
mod deletion;
11+
pub use deletion::WorkflowDeletionOutcome;
1112

1213
use std::fmt;
1314
use std::str::FromStr;

‎crates/buzz-db/src/store/workflow/deletion.rs‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,31 @@ use uuid::Uuid;
88

99
use crate::{Db, DbError, Result};
1010

11+
/// Committed changes made by a workflow-coordinate deletion.
12+
#[derive(Debug, Default)]
13+
pub struct WorkflowDeletionOutcome {
14+
/// Whether either the executable workflow or a visible definition was removed.
15+
pub changed: bool,
16+
/// Removed executable workflow's channel, for trigger-cache invalidation.
17+
pub channel_id: Option<Uuid>,
18+
}
19+
1120
impl Db {
1221
/// Delete an authorized workflow coordinate and its definition atomically.
1322
///
1423
/// Shares the replacement lock with definition saves. A deletion older than
1524
/// the live definition is a no-op. Missing projections are tolerated so a
1625
/// retry can remove definitions left behind by older relay versions.
17-
/// Returns the removed projection's channel for trigger-cache invalidation.
26+
/// Reports committed changes independently of the optional workflow channel.
27+
/// No tombstone is retained: clients may intentionally publish backdated definitions.
1828
#[datastore_span(name = "delete_workflow_by_coordinate", system = "postgresql")]
1929
pub async fn delete_workflow_by_coordinate(
2030
&self,
2131
community_id: CommunityId,
2232
owner_pubkey: &[u8],
2333
d_tag: &str,
2434
deletion_created_at_secs: i64,
25-
) -> Result<Option<Uuid>> {
35+
) -> Result<WorkflowDeletionOutcome> {
2636
let cutoff = DateTime::from_timestamp(deletion_created_at_secs, 0)
2737
.ok_or(DbError::InvalidTimestamp(deletion_created_at_secs))?;
2838
let mut tx = self.begin_event_write_transaction().await?;
@@ -52,7 +62,7 @@ impl Db {
5262
.fetch_optional(&mut *tx)
5363
.await?;
5464
if head.is_some_and(|created_at| created_at > cutoff) {
55-
return Ok(None);
65+
return Ok(WorkflowDeletionOutcome::default());
5666
}
5767

5868
// UUID coordinates are canonical; retain the legacy name-based path.
@@ -70,7 +80,7 @@ impl Db {
7080
.bind(d_tag)
7181
.fetch_optional(&mut *tx)
7282
.await?;
73-
sqlx::query(
83+
let definitions = sqlx::query(
7484
"UPDATE events SET deleted_at = NOW() WHERE community_id = $1 AND kind = $2 \
7585
AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL AND created_at <= $5",
7686
)
@@ -81,12 +91,16 @@ impl Db {
8191
.bind(cutoff)
8292
.execute(&mut *tx)
8393
.await?;
94+
let changed = row.is_some() || definitions.rows_affected() > 0;
8495
let channel_id = row
8596
.map(|row| row.try_get("channel_id"))
8697
.transpose()?
8798
.flatten();
8899
tx.commit().await?;
89-
Ok(channel_id)
100+
Ok(WorkflowDeletionOutcome {
101+
changed,
102+
channel_id,
103+
})
90104
}
91105
}
92106

‎crates/buzz-db/src/store/workflow/deletion_tests.rs‎

Lines changed: 47 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -100,14 +100,16 @@ async fn workflow_deletion_removes_both_projections_and_is_scoped_and_retryable(
100100
let other_query = seed(&db, other, &keys, id, &d_tag, now).await;
101101
assert_present(&db, &query, id).await;
102102

103-
db.delete_workflow_by_coordinate(
104-
community,
105-
&Keys::generate().public_key().to_bytes(),
106-
&d_tag,
107-
now as i64,
108-
)
109-
.await
110-
.expect("wrong owner is a no-op");
103+
let unchanged = db
104+
.delete_workflow_by_coordinate(
105+
community,
106+
&Keys::generate().public_key().to_bytes(),
107+
&d_tag,
108+
now as i64,
109+
)
110+
.await
111+
.expect("wrong owner is a no-op");
112+
assert!(!unchanged.changed);
111113
assert_present(&db, &query, id).await;
112114

113115
let run_id = create_workflow_run(&db.pool, community, id, None, None)
@@ -125,18 +127,32 @@ async fn workflow_deletion_removes_both_projections_and_is_scoped_and_retryable(
125127
.execute(&db.pool)
126128
.await
127129
.expect("scheduled claim linked to run");
128-
db.delete_workflow_by_coordinate(community, &owner, &d_tag, now as i64)
129-
.await
130-
.expect("delete workflow");
130+
let (first, second) = tokio::join!(
131+
db.delete_workflow_by_coordinate(community, &owner, &d_tag, now as i64),
132+
db.delete_workflow_by_coordinate(community, &owner, &d_tag, now as i64),
133+
);
134+
let first = first.expect("first deletion");
135+
let second = second.expect("concurrent deletion");
136+
assert_ne!(
137+
first.changed, second.changed,
138+
"only one deletion changes state"
139+
);
140+
assert_eq!(
141+
first.channel_id, None,
142+
"channel-less mutation still reports change"
143+
);
144+
assert_eq!(second.channel_id, None);
131145
assert_absent(&db, &query, id).await;
132146
assert_present(&db, &other_query, id).await;
133147
assert!(matches!(
134148
db.get_workflow_run(community, run_id).await,
135149
Err(DbError::NotFound(_))
136150
));
137-
db.delete_workflow_by_coordinate(community, &owner, &d_tag, now as i64)
151+
let unchanged = db
152+
.delete_workflow_by_coordinate(community, &owner, &d_tag, now as i64)
138153
.await
139154
.expect("repeat deletion");
155+
assert!(!unchanged.changed);
140156
assert_absent(&db, &query, id).await;
141157
}
142158

@@ -150,9 +166,11 @@ async fn workflow_deletion_preserves_newer_definition_and_cleans_legacy_orphan()
150166
let d_tag = id.to_string();
151167
let now = Timestamp::now().as_secs();
152168
let query = seed(&db, community, &keys, id, &d_tag, now).await;
153-
db.delete_workflow_by_coordinate(community, &owner, &d_tag, now as i64 - 1)
169+
let unchanged = db
170+
.delete_workflow_by_coordinate(community, &owner, &d_tag, now as i64 - 1)
154171
.await
155172
.expect("stale deletion");
173+
assert!(!unchanged.changed);
156174
assert_present(&db, &query, id).await;
157175

158176
// Old relay releases deleted the executable row, but not the definition.
@@ -166,16 +184,30 @@ async fn workflow_deletion_preserves_newer_definition_and_cleans_legacy_orphan()
166184
.len(),
167185
1
168186
);
169-
db.delete_workflow_by_coordinate(community, &owner, &d_tag, now as i64)
187+
let repaired = db
188+
.delete_workflow_by_coordinate(community, &owner, &d_tag, now as i64)
170189
.await
171190
.expect("repair deletion");
191+
assert!(repaired.changed, "orphan-only cleanup must dispatch");
192+
assert_eq!(repaired.channel_id, None);
172193
assert_absent(&db, &query, id).await;
173194

174195
let legacy_id = Uuid::new_v4();
175196
let legacy = seed(&db, community, &keys, legacy_id, "legacy-name", now).await;
176-
db.delete_workflow_by_coordinate(community, &owner, "legacy-name", now as i64)
197+
db.soft_delete_by_coordinate(
198+
community,
199+
KIND_WORKFLOW_DEF as i32,
200+
&owner,
201+
"legacy-name",
202+
now as i64,
203+
)
204+
.await
205+
.expect("remove definition to leave only executable projection");
206+
let repaired = db
207+
.delete_workflow_by_coordinate(community, &owner, "legacy-name", now as i64)
177208
.await
178209
.expect("name coordinate deletion");
210+
assert!(repaired.changed, "projection-only cleanup must dispatch");
179211
assert_absent(&db, &legacy, legacy_id).await;
180212
}
181213

‎crates/buzz-relay/src/handlers/ingest.rs‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3207,13 +3207,17 @@ async fn ingest_event_inner(
32073207
// idempotent transaction also runs for duplicate requests: the event may
32083208
// have been stored before a failure, including by an older relay version.
32093209
let workflow_deletion = crate::handlers::side_effects::is_workflow_deletion(&event);
3210-
if workflow_deletion {
3211-
crate::handlers::side_effects::handle_side_effects(tenant, kind_u32, &event, state)
3210+
let workflow_deletion_changed = if workflow_deletion {
3211+
crate::handlers::side_effects::handle_a_tag_deletion(tenant, &event, state)
32123212
.await
3213-
.map_err(|e| IngestError::Internal(format!("error: workflow deletion failed: {e}")))?;
3214-
}
3213+
.map_err(|e| IngestError::Internal(format!("error: workflow deletion failed: {e}")))?
3214+
} else {
3215+
false
3216+
};
32153217

3216-
if !was_inserted {
3218+
// A repaired deletion still needs the normal audit and live dispatch below.
3219+
// Completed duplicates remain no-ops, including channel-less/orphan repairs.
3220+
if !was_inserted && !workflow_deletion_changed {
32173221
return Ok(IngestResult {
32183222
event_id: event_id_hex,
32193223
accepted: true,

‎crates/buzz-relay/src/handlers/side_effects.rs‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2111,11 +2111,12 @@ pub(crate) fn is_workflow_deletion(event: &Event) -> bool {
21112111

21122112
/// Handle NIP-09 deletion via `a` tag (addressable/parameterized-replaceable events).
21132113
/// Parses "kind:pubkey:d-tag" and deletes the corresponding DB record.
2114-
async fn handle_a_tag_deletion(
2114+
/// Returns whether a workflow deletion changed state, for duplicate repair dispatch.
2115+
pub(crate) async fn handle_a_tag_deletion(
21152116
tenant: &TenantContext,
21162117
event: &Event,
21172118
state: &Arc<AppState>,
2118-
) -> anyhow::Result<()> {
2119+
) -> anyhow::Result<bool> {
21192120
let a_value = event
21202121
.tags
21212122
.iter()
@@ -2143,7 +2144,7 @@ async fn handle_a_tag_deletion(
21432144
// not necessarily the signer of the deletion request.
21442145
let owner_bytes = hex::decode(pubkey_hex)
21452146
.map_err(|_| anyhow::anyhow!("invalid pubkey hex in workflow coordinate"))?;
2146-
let channel_id = state
2147+
let outcome = state
21472148
.db
21482149
.delete_workflow_by_coordinate(
21492150
tenant.community(),
@@ -2152,11 +2153,12 @@ async fn handle_a_tag_deletion(
21522153
event.created_at.as_secs() as i64,
21532154
)
21542155
.await?;
2155-
if let Some(channel_id) = channel_id {
2156+
if let Some(channel_id) = outcome.channel_id {
21562157
state
21572158
.workflow_engine
21582159
.invalidate_channel_workflows(tenant.community(), channel_id);
21592160
}
2161+
return Ok(outcome.changed);
21602162
}
21612163
// Other NIP-33 events have no executable workflow projection.
21622164
k if is_parameterized_replaceable(k) => {
@@ -2211,7 +2213,7 @@ async fn handle_a_tag_deletion(
22112213
}
22122214
}
22132215

2214-
Ok(())
2216+
Ok(false)
22152217
}
22162218

22172219
async fn handle_standard_deletion_event(
@@ -2224,7 +2226,9 @@ async fn handle_standard_deletion_event(
22242226
// NIP-09 a-tag deletion path for addressable events. Keyed on the
22252227
// absence of *any* e tag (not just valid e-ids): a malformed e + a must
22262228
// not route here and silently soft-delete the coordinate.
2227-
return handle_a_tag_deletion(tenant, event, state).await;
2229+
return handle_a_tag_deletion(tenant, event, state)
2230+
.await
2231+
.map(|_| ());
22282232
}
22292233

22302234
for target_id in target_ids {

0 commit comments

Comments
 (0)