ff-backend-postgres 0.11.0

FlowFabric EngineBackend impl — Postgres backend (RFC-v0.7, Wave 0 scaffold)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! RFC-019 Stage B — `subscribe_lease_history` on Postgres.
//!
//! Mirror of [`crate::completion::subscribe`] but against the
//! `ff_lease_event` outbox + `pg_notify('ff_lease_event', ...)`
//! trigger. See `migrations/0006_lease_event_outbox.sql`.
//!
//! Cursor encoding: `POSTGRES_CURSOR_PREFIX (0x02)` + `event_id`
//! (i64, big-endian). Resume-from-cursor is fully plumbed — the
//! subscribe call decodes the caller's cursor, catch-up replays
//! rows strictly after it, and steady-state NOTIFY wakes re-run
//! the catch-up query.
//!
//! Partition scope: one subscription tails the backend's configured
//! partition. Cross-partition consumers instantiate one backend
//! per partition and merge streams consumer-side (RFC-019
//! §Backend Semantics).

use std::time::Duration;

use ff_core::backend::ScannerFilter;
use ff_core::engine_error::EngineError;
use ff_core::stream_events::{LeaseHistoryEvent, LeaseHistorySubscription};
use ff_core::stream_subscribe::{
    decode_postgres_event_cursor, encode_postgres_event_cursor, StreamCursor,
};
use ff_core::types::{ExecutionId, LeaseId, TimestampMs};
use futures_core::Stream;
use sqlx::postgres::{PgListener, PgPool};
use sqlx::Row;
use tokio::sync::mpsc;
use uuid::Uuid;

/// Channel fired by `ff_notify_lease_event()` on every
/// `ff_lease_event` INSERT.
pub const LEASE_EVENT_CHANNEL: &str = "ff_lease_event";

/// Bounded fan-out capacity (matches `completion::STREAM_CAPACITY`).
const STREAM_CAPACITY: usize = 1024;

/// Max rows pulled per wake.
const REPLAY_BATCH: i64 = 256;

/// Reconnect backoff when the LISTEN connection drops.
const RECONNECT_BACKOFF: Duration = Duration::from_millis(200);

/// #282 — in-memory `ScannerFilter` check over an outbox row's
/// denormalised `namespace` + `instance_tag` columns. Namespace
/// compares exact; `instance_tag` compares the caller-supplied VALUE
/// (the key half of the tuple is denormalisation-choice at write time,
/// not a query-time input — matches the Valkey/dependency-reconciler
/// convention). NULL columns never match a non-None filter dimension.
pub(crate) fn passes_filter(
    filter: &ScannerFilter,
    row_namespace: Option<&str>,
    row_instance_tag: Option<&str>,
) -> bool {
    if let Some(ref want_ns) = filter.namespace {
        match row_namespace {
            Some(have) if have == want_ns.as_str() => {}
            _ => return false,
        }
    }
    if let Some((_, ref want_value)) = filter.instance_tag {
        match row_instance_tag {
            Some(have) if have == want_value.as_str() => {}
            _ => return false,
        }
    }
    true
}

struct LeaseEventRow {
    event_id: i64,
    execution_id: String,
    lease_id: Option<String>,
    event_type: String,
    occurred_at_ms: i64,
    partition_key: i32,
}

/// Subscribe to `ff_lease_event` rows strictly after `cursor` for the
/// given partition. Empty cursor tails from `max(event_id)` at
/// subscribe time.
pub(crate) async fn subscribe(
    pool: &PgPool,
    partition_key: i16,
    cursor: StreamCursor,
    filter: ScannerFilter,
) -> Result<LeaseHistorySubscription, EngineError> {
    // Decode + validate the caller's cursor before spawning so
    // malformed cursors fail loudly at subscribe time.
    let start = decode_postgres_event_cursor(&cursor).map_err(|msg| {
        EngineError::Validation {
            kind: ff_core::engine_error::ValidationKind::InvalidInput,
            detail: msg.to_string(),
        }
    })?;

    // Empty cursor → tail-from-now (resolve max at subscribe time so
    // early committers do not slip between subscribe + LISTEN).
    let last_seen: i64 = match start {
        Some(v) => v,
        None => sqlx::query_scalar(
            "SELECT COALESCE(MAX(event_id), 0) FROM ff_lease_event WHERE partition_key = $1",
        )
        .bind(i32::from(partition_key))
        .fetch_one(pool)
        .await
        .map_err(|_| EngineError::Unavailable {
            op: "pg.subscribe_lease_history",
        })?,
    };

    let (tx, rx) = mpsc::channel::<Result<LeaseHistoryEvent, EngineError>>(STREAM_CAPACITY);
    let pool_clone = pool.clone();
    tokio::spawn(subscriber_loop(
        pool_clone,
        partition_key,
        tx,
        last_seen,
        filter,
    ));

    Ok(Box::pin(Adapter { rx }))
}

/// `mpsc::Receiver` → `Stream` adapter.
struct Adapter {
    rx: mpsc::Receiver<Result<LeaseHistoryEvent, EngineError>>,
}

impl Stream for Adapter {
    type Item = Result<LeaseHistoryEvent, EngineError>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        self.rx.poll_recv(cx)
    }
}

async fn subscriber_loop(
    pool: PgPool,
    partition_key: i16,
    tx: mpsc::Sender<Result<LeaseHistoryEvent, EngineError>>,
    mut last_seen: i64,
    filter: ScannerFilter,
) {
    loop {
        let mut listener = match PgListener::connect_with(&pool).await {
            Ok(l) => l,
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "pg.lease_history.subscribe: PgListener::connect_with failed; retrying"
                );
                if wait_or_exit(&tx, RECONNECT_BACKOFF).await {
                    return;
                }
                continue;
            }
        };
        if let Err(e) = listener.listen(LEASE_EVENT_CHANNEL).await {
            tracing::warn!(
                error = %e,
                "pg.lease_history.subscribe: LISTEN ff_lease_event failed; retrying"
            );
            if wait_or_exit(&tx, RECONNECT_BACKOFF).await {
                return;
            }
            continue;
        }

        // Catch-up replay.
        if !replay(&pool, partition_key, &tx, &mut last_seen, &filter).await {
            return;
        }

        loop {
            tokio::select! {
                _ = tx.closed() => return,
                res = listener.recv() => {
                    match res {
                        Ok(_notif) => {
                            if !replay(&pool, partition_key, &tx, &mut last_seen, &filter).await {
                                return;
                            }
                        }
                        Err(e) => {
                            tracing::warn!(
                                error = %e,
                                "pg.lease_history.subscribe: listener.recv() error; reconnecting"
                            );
                            // Surface a non-terminal disconnect notice
                            // carrying the current cursor so the
                            // consumer can choose to re-subscribe.
                            let _ = tx
                                .send(Err(EngineError::StreamDisconnected {
                                    cursor: encode_postgres_event_cursor(last_seen),
                                }))
                                .await;
                            break; // outer loop rebuilds the listener
                        }
                    }
                }
            }
        }

        if wait_or_exit(&tx, RECONNECT_BACKOFF).await {
            return;
        }
    }
}

async fn wait_or_exit(
    tx: &mpsc::Sender<Result<LeaseHistoryEvent, EngineError>>,
    d: Duration,
) -> bool {
    tokio::select! {
        _ = tx.closed() => true,
        _ = tokio::time::sleep(d) => false,
    }
}

/// Drain rows above `last_seen`; forward each as a typed
/// `LeaseHistoryEvent`. Returns `false` iff the consumer dropped
/// the subscription.
async fn replay(
    pool: &PgPool,
    partition_key: i16,
    tx: &mpsc::Sender<Result<LeaseHistoryEvent, EngineError>>,
    last_seen: &mut i64,
    filter: &ScannerFilter,
) -> bool {
    // #282 — read the denormalised filter columns on every row so the
    // in-memory `ScannerFilter::matches`-shaped check can admit / drop
    // without a per-event RTT. SELECT is unfiltered (matches the
    // `completion::replay` pattern + keeps `last_seen` advancing past
    // dropped rows) — the bandwidth cost of two extra TEXT columns is
    // dwarfed by the round-trip savings of not re-querying skipped
    // rows on every LISTEN wake.
    loop {
        let rows = match sqlx::query(
            "SELECT event_id, execution_id, lease_id, event_type, occurred_at_ms, \
                    partition_key, namespace, instance_tag \
             FROM ff_lease_event \
             WHERE partition_key = $1 AND event_id > $2 \
             ORDER BY event_id ASC \
             LIMIT $3",
        )
        .bind(i32::from(partition_key))
        .bind(*last_seen)
        .bind(REPLAY_BATCH)
        .fetch_all(pool)
        .await
        {
            Ok(rows) => rows,
            Err(e) => {
                tracing::warn!(error = %e, "pg.lease_history.replay: query failed");
                return !tx.is_closed();
            }
        };

        if rows.is_empty() {
            return !tx.is_closed();
        }

        for row in rows {
            let Ok(event_id) = row.try_get::<i64, _>("event_id") else {
                continue;
            };
            let Ok(execution_id) = row.try_get::<String, _>("execution_id") else {
                continue;
            };
            let lease_id: Option<String> =
                row.try_get::<Option<String>, _>("lease_id").unwrap_or(None);
            let Ok(event_type) = row.try_get::<String, _>("event_type") else {
                continue;
            };
            let Ok(occurred_at_ms) = row.try_get::<i64, _>("occurred_at_ms") else {
                continue;
            };
            let Ok(partition_key) = row.try_get::<i32, _>("partition_key") else {
                continue;
            };
            // #282 — denormalised filter columns (added in migration
            // 0008). NULL-safe via `Option<String>`; unfiltered
            // subscribers bypass the compare entirely.
            let namespace: Option<String> =
                row.try_get::<Option<String>, _>("namespace").unwrap_or(None);
            let instance_tag: Option<String> = row
                .try_get::<Option<String>, _>("instance_tag")
                .unwrap_or(None);

            let decoded = LeaseEventRow {
                event_id,
                execution_id,
                lease_id,
                event_type,
                occurred_at_ms,
                partition_key,
            };
            *last_seen = decoded.event_id;

            // #282 — apply `ScannerFilter` inline. Match semantics
            // mirror the Valkey `FilterGate`: namespace equality +
            // instance-tag-value equality. A NULL-column row on a
            // non-noop filter is silently dropped (matches the
            // "filtered subscribers silently drop NULL-column rows"
            // invariant documented in migration 0008).
            if !passes_filter(filter, namespace.as_deref(), instance_tag.as_deref()) {
                continue;
            }

            let cursor = encode_postgres_event_cursor(decoded.event_id);

            // Re-attach the `{fp:N}:<uuid>` hash-tag so the inline
            // `execution_id` matches what Valkey would emit. Rows
            // without a parseable UUID are defensively skipped —
            // producers always write a UUID, so a bad row is a
            // schema corruption surface, not a skip.
            let execution_id = match Uuid::parse_str(&decoded.execution_id)
                .ok()
                .and_then(|uuid| {
                    ExecutionId::parse(&format!(
                        "{{fp:{}}}:{}",
                        decoded.partition_key, uuid
                    ))
                    .ok()
                }) {
                Some(eid) => eid,
                None => {
                    tracing::warn!(
                        execution_id = %decoded.execution_id,
                        event_id = decoded.event_id,
                        "pg.lease_history.replay: skipping row with unparseable execution_id"
                    );
                    continue;
                }
            };

            let lease_id = decoded
                .lease_id
                .as_deref()
                .and_then(|s| LeaseId::parse(s).ok());
            let at = TimestampMs::from_millis(decoded.occurred_at_ms);

            // PG outbox does not persist the owning worker instance —
            // the fence triple is rebuilt from attempt rows at lookup
            // time. Surface `None` for now; consumers who need it go
            // through `read_execution_state`. `lease_id` is also
            // typically `None` on PG since `ff_attempt` identity is
            // `(lease_epoch, attempt_index, execution_id)` rather than
            // a stable uuid (see `lease_event::emit`).
            let event = match decoded.event_type.as_str() {
                "acquired" => LeaseHistoryEvent::Acquired {
                    cursor,
                    execution_id,
                    lease_id,
                    worker_instance_id: None,
                    at,
                },
                "renewed" => LeaseHistoryEvent::Renewed {
                    cursor,
                    execution_id,
                    lease_id,
                    worker_instance_id: None,
                    at,
                },
                "expired" => LeaseHistoryEvent::Expired {
                    cursor,
                    execution_id,
                    lease_id,
                    prev_owner: None,
                    at,
                },
                "reclaimed" => LeaseHistoryEvent::Reclaimed {
                    cursor,
                    execution_id,
                    new_lease_id: lease_id,
                    new_owner: None,
                    at,
                },
                "revoked" => LeaseHistoryEvent::Revoked {
                    cursor,
                    execution_id,
                    lease_id,
                    // PG outbox does not yet persist the revoke source;
                    // match the Valkey default. Taxonomy typed-up when
                    // the outbox schema gains a `revoked_by` column.
                    revoked_by: "operator".to_string(),
                    at,
                },
                other => {
                    tracing::warn!(
                        event_id = decoded.event_id,
                        event_type = %other,
                        "pg.lease_history.replay: unknown event_type, skipping"
                    );
                    continue;
                }
            };

            if tx.send(Ok(event)).await.is_err() {
                return false; // consumer dropped
            }
        }
    }
}