runledger-postgres 0.12.0

PostgreSQL persistence layer for the Runledger durable job and workflow system
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
mod support;

use std::time::Duration;

use runledger_core::jobs::JobFailureKind;
use runledger_postgres::jobs::{
    JobContinuationUpdate, JobFailureUpdate, claim_prestart_jobs, complete_job_continuation,
    complete_job_failure, complete_job_success, release_unstarted_job_claim,
};
use runledger_postgres::{Error, QueryErrorCategory, QueryErrorKind};
use runledger_test_support::{setup_ephemeral_pool, teardown_ephemeral_pool};
use serde_json::json;
use sqlx::{PgPool, postgres::PgPoolOptions};
use tokio::time::{Instant, timeout};

use support::{claim_one_job, enqueue_test_job, register_test_job_definition};

const JOB_TYPE: &str = "jobs.test.lifecycle_completion_timeout";

fn assert_lock_timeout_error(error: Error) {
    match error {
        Error::QueryError(query_error) => {
            assert_eq!(query_error.category(), QueryErrorCategory::Internal);
            assert_eq!(
                query_error.kind(),
                Some(QueryErrorKind::PostgresLockNotAvailable)
            );
            assert_eq!(query_error.sqlstate(), Some("55P03"));
        }
        other => panic!("expected lock-timeout query error, got {other:?}"),
    }
}

async fn enqueue_and_claim(
    pool: &PgPool,
    worker_id: &str,
) -> runledger_postgres::jobs::JobQueueRecord {
    enqueue_test_job(pool, JOB_TYPE, None, &json!({"worker_id": worker_id})).await;
    claim_one_job(pool, worker_id).await
}

async fn lock_job_row<'a>(
    pool: &'a PgPool,
    job_id: sqlx::types::Uuid,
) -> sqlx::Transaction<'a, sqlx::Postgres> {
    let mut blocker = pool.begin().await.expect("begin job-row blocker");
    sqlx::query("SELECT id FROM job_queue WHERE id = $1 FOR UPDATE")
        .bind(job_id)
        .fetch_one(&mut *blocker)
        .await
        .expect("hold job row lock");
    blocker
}

#[tokio::test]
async fn unstarted_claim_release_row_lock_wait_preserves_stricter_database_timeout() {
    let (pool, database) = setup_ephemeral_pool("postgres_unstarted_release_timeout", 4).await;
    let server_version = sqlx::query_scalar::<_, String>("SHOW server_version")
        .fetch_one(&pool)
        .await
        .expect("read PostgreSQL server_version");
    let server_version_num =
        sqlx::query_scalar::<_, i32>("SELECT current_setting('server_version_num')::int")
            .fetch_one(&pool)
            .await
            .expect("read PostgreSQL server_version_num");
    eprintln!(
        "unstarted release timeout regression PostgreSQL server_version={server_version}, \
         server_version_num={server_version_num}"
    );
    register_test_job_definition(&pool, JOB_TYPE).await;

    enqueue_test_job(
        &pool,
        JOB_TYPE,
        None,
        &json!({"worker_id": "worker-unstarted-release-timeout"}),
    )
    .await;
    let claimed = claim_prestart_jobs(&pool, "worker-unstarted-release-timeout", 30, 1)
        .await
        .expect("claim unstarted job")
        .pop()
        .expect("one unstarted job should be claimable");
    let release_pool = PgPoolOptions::new()
        .max_connections(1)
        .connect(database.url())
        .await
        .expect("connect unstarted release pool");
    sqlx::query("SET SESSION lock_timeout = '100ms'")
        .execute(&release_pool)
        .await
        .expect("set strict unstarted release lock timeout");

    let blocker = lock_job_row(&pool, claimed.id).await;
    let error = timeout(
        Duration::from_secs(2),
        release_unstarted_job_claim(
            &release_pool,
            runledger_postgres::jobs::JobLeaseIdentity::new(
                claimed.id,
                claimed.run_number,
                claimed.attempt,
                claimed.worker_id.as_deref().expect("claimed worker id"),
            ),
            "TEST_RELEASE_LOCK_TIMEOUT",
            0,
        ),
    )
    .await
    .expect("unstarted claim release lock wait should be bounded")
    .expect_err("unstarted claim release should report lock timeout");
    assert_lock_timeout_error(error);

    blocker
        .rollback()
        .await
        .expect("release unstarted claim blocker");
    release_pool.close().await;
    teardown_ephemeral_pool(pool, database).await;
}

#[tokio::test]
async fn completion_row_lock_wait_uses_default_five_second_cap() {
    let (pool, database) = setup_ephemeral_pool("postgres_default_completion_timeout", 4).await;
    let server_version = sqlx::query_scalar::<_, String>("SHOW server_version")
        .fetch_one(&pool)
        .await
        .expect("read PostgreSQL server_version");
    let server_version_num =
        sqlx::query_scalar::<_, i32>("SELECT current_setting('server_version_num')::int")
            .fetch_one(&pool)
            .await
            .expect("read PostgreSQL server_version_num");
    eprintln!(
        "default completion timeout regression PostgreSQL server_version={server_version}, \
         server_version_num={server_version_num}"
    );
    register_test_job_definition(&pool, JOB_TYPE).await;

    let claimed = enqueue_and_claim(&pool, "worker-default-completion-timeout").await;
    let completion_pool = PgPoolOptions::new()
        .max_connections(1)
        .connect(database.url())
        .await
        .expect("connect default completion pool");
    assert_eq!(
        sqlx::query_scalar::<_, String>("SHOW lock_timeout")
            .fetch_one(&completion_pool)
            .await
            .expect("read default completion lock timeout"),
        "0"
    );

    let blocker = lock_job_row(&pool, claimed.id).await;
    let started = Instant::now();
    let error = timeout(
        Duration::from_secs(7),
        complete_job_success(
            &completion_pool,
            claimed.id,
            claimed.run_number,
            claimed.attempt,
            claimed.worker_id.as_deref().expect("claimed worker id"),
            None,
        ),
    )
    .await
    .expect("default completion lock cap must beat the test guard")
    .expect_err("blocked completion should report the default lock timeout");
    let elapsed = started.elapsed();
    assert_lock_timeout_error(error);
    assert!(
        elapsed >= Duration::from_millis(4_500),
        "default completion lock timeout fired too early: {elapsed:?}"
    );
    assert!(
        elapsed < Duration::from_secs(7),
        "default completion lock timeout did not cap the wait: {elapsed:?}"
    );

    blocker
        .rollback()
        .await
        .expect("release default completion blocker");
    completion_pool.close().await;
    teardown_ephemeral_pool(pool, database).await;
}

#[tokio::test]
async fn completion_row_lock_waits_preserve_stricter_database_timeout() {
    let (pool, database) = setup_ephemeral_pool("postgres_completion_timeouts", 4).await;
    let server_version = sqlx::query_scalar::<_, String>("SHOW server_version")
        .fetch_one(&pool)
        .await
        .expect("read PostgreSQL server_version");
    let server_version_num =
        sqlx::query_scalar::<_, i32>("SELECT current_setting('server_version_num')::int")
            .fetch_one(&pool)
            .await
            .expect("read PostgreSQL server_version_num");
    eprintln!(
        "completion timeout regression PostgreSQL server_version={server_version}, \
         server_version_num={server_version_num}"
    );
    register_test_job_definition(&pool, JOB_TYPE).await;

    let success = enqueue_and_claim(&pool, "worker-completion-timeout-success").await;
    let failure = enqueue_and_claim(&pool, "worker-completion-timeout-failure").await;
    let continuation = enqueue_and_claim(&pool, "worker-completion-timeout-continuation").await;

    let completion_pool = PgPoolOptions::new()
        .max_connections(1)
        .connect(database.url())
        .await
        .expect("connect completion pool");
    sqlx::query("SET SESSION lock_timeout = '100ms'")
        .execute(&completion_pool)
        .await
        .expect("set strict completion lock timeout");

    let success_worker_id = success.worker_id.as_deref().expect("success worker id");
    let success_blocker = lock_job_row(&pool, success.id).await;
    let success_error = timeout(
        Duration::from_secs(2),
        complete_job_success(
            &completion_pool,
            success.id,
            success.run_number,
            success.attempt,
            success_worker_id,
            None,
        ),
    )
    .await
    .expect("success completion lock wait should be bounded")
    .expect_err("success completion should report lock timeout");
    assert_lock_timeout_error(success_error);
    success_blocker
        .rollback()
        .await
        .expect("release success blocker");

    let failure_worker_id = failure.worker_id.as_deref().expect("failure worker id");
    let failure_blocker = lock_job_row(&pool, failure.id).await;
    let failure_update = JobFailureUpdate::new(
        JobFailureKind::Retryable,
        "job.test.completion_timeout",
        "completion timeout regression",
        Some(1_000),
    );
    let failure_error = timeout(
        Duration::from_secs(2),
        complete_job_failure(
            &completion_pool,
            failure.id,
            failure.run_number,
            failure.attempt,
            failure_worker_id,
            &failure_update,
        ),
    )
    .await
    .expect("failure completion lock wait should be bounded")
    .expect_err("failure completion should report lock timeout");
    assert_lock_timeout_error(failure_error);
    failure_blocker
        .rollback()
        .await
        .expect("release failure blocker");

    let continuation_worker_id = continuation
        .worker_id
        .as_deref()
        .expect("continuation worker id");
    let continuation_blocker = lock_job_row(&pool, continuation.id).await;
    let continuation_error = timeout(
        Duration::from_secs(2),
        complete_job_continuation(
            &completion_pool,
            continuation.id,
            continuation.run_number,
            continuation.attempt,
            continuation_worker_id,
            &JobContinuationUpdate {
                delay: Duration::ZERO,
                progress_done: None,
                progress_total: None,
                checkpoint: None,
            },
        ),
    )
    .await
    .expect("continuation completion lock wait should be bounded")
    .expect_err("continuation completion should report lock timeout");
    assert_lock_timeout_error(continuation_error);
    continuation_blocker
        .rollback()
        .await
        .expect("release continuation blocker");

    completion_pool.close().await;
    teardown_ephemeral_pool(pool, database).await;
}

#[tokio::test]
async fn completion_restores_caller_timeouts_after_job_row_acquisition() {
    let (pool, database) = setup_ephemeral_pool("postgres_completion_timeout_scope", 4).await;
    let server_version = sqlx::query_scalar::<_, String>("SHOW server_version")
        .fetch_one(&pool)
        .await
        .expect("read PostgreSQL server_version");
    let server_version_num =
        sqlx::query_scalar::<_, i32>("SELECT current_setting('server_version_num')::int")
            .fetch_one(&pool)
            .await
            .expect("read PostgreSQL server_version_num");
    eprintln!(
        "completion timeout scope regression PostgreSQL server_version={server_version}, \
         server_version_num={server_version_num}"
    );
    register_test_job_definition(&pool, JOB_TYPE).await;

    for statement in [
        "CREATE TABLE runledger_test_completion_timeout_observations (
            lock_timeout text NOT NULL,
            transaction_timeout text NOT NULL
         )",
        "CREATE FUNCTION runledger_test_observe_completion_timeouts()
         RETURNS trigger
         LANGUAGE plpgsql
         AS $$
         BEGIN
             INSERT INTO runledger_test_completion_timeout_observations (
                 lock_timeout,
                 transaction_timeout
             )
             VALUES (
                 current_setting('lock_timeout'),
                 current_setting('transaction_timeout')
             );
             RETURN NEW;
         END;
         $$",
        "CREATE TRIGGER runledger_test_observe_completion_timeouts
         AFTER UPDATE OF finished_at ON job_attempts
         FOR EACH ROW
         WHEN (NEW.finished_at IS NOT NULL)
         EXECUTE FUNCTION runledger_test_observe_completion_timeouts()",
    ] {
        sqlx::query(statement)
            .execute(&pool)
            .await
            .expect("install completion timeout observation trigger");
    }

    let success = enqueue_and_claim(&pool, "worker-completion-timeout-scope-success").await;
    let failure = enqueue_and_claim(&pool, "worker-completion-timeout-scope-failure").await;
    let continuation =
        enqueue_and_claim(&pool, "worker-completion-timeout-scope-continuation").await;
    let completion_pool = PgPoolOptions::new()
        .max_connections(1)
        .connect(database.url())
        .await
        .expect("connect timeout-scope completion pool");
    sqlx::query(
        "SELECT
            set_config('lock_timeout', '1min', false),
            set_config('transaction_timeout', '2min', false)",
    )
    .execute(&completion_pool)
    .await
    .expect("set caller completion timeouts");

    complete_job_success(
        &completion_pool,
        success.id,
        success.run_number,
        success.attempt,
        success.worker_id.as_deref().expect("success worker id"),
        None,
    )
    .await
    .expect("complete job after scoped row-lock timeout");

    let failure_update = JobFailureUpdate::new(
        JobFailureKind::Retryable,
        "job.test.completion_timeout_scope",
        "completion timeout scope regression",
        Some(1_000),
    );
    complete_job_failure(
        &completion_pool,
        failure.id,
        failure.run_number,
        failure.attempt,
        failure.worker_id.as_deref().expect("failure worker id"),
        &failure_update,
    )
    .await
    .expect("fail job after scoped row-lock timeout");

    complete_job_continuation(
        &completion_pool,
        continuation.id,
        continuation.run_number,
        continuation.attempt,
        continuation
            .worker_id
            .as_deref()
            .expect("continuation worker id"),
        &JobContinuationUpdate {
            delay: Duration::ZERO,
            progress_done: None,
            progress_total: None,
            checkpoint: None,
        },
    )
    .await
    .expect("continue job after scoped row-lock timeout");

    let (observed, unexpected) = sqlx::query_as::<_, (i64, i64)>(
        "SELECT
            count(*) FILTER (
                WHERE lock_timeout = '1min'
                  AND transaction_timeout = '2min'
            ),
            count(*) FILTER (
                WHERE lock_timeout <> '1min'
                   OR transaction_timeout <> '2min'
            )
         FROM runledger_test_completion_timeout_observations",
    )
    .fetch_one(&pool)
    .await
    .expect("read downstream completion timeout settings");
    assert_eq!(observed, 3);
    assert_eq!(unexpected, 0);

    completion_pool.close().await;
    teardown_ephemeral_pool(pool, database).await;
}