agentics-persistence 0.3.0

Database persistence layer for the Agentics challenge platform.
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//! Challenge review record, GitHub identity, private asset, and review lifecycle queries.

use sqlx::{PgPool, Postgres, Row, Transaction};

use agentics_domain::models::auth::GithubUserId;
use agentics_domain::models::challenge_creation::{
    ChallengeCreationManifest, ChallengePrivateAssetKind, ChallengeReviewRecordStatus,
};
use agentics_domain::models::github::GithubPullRequestNumber;
use agentics_domain::models::hashes::GitCommitSha;
use agentics_domain::models::hashes::Sha256Digest;
use agentics_domain::models::ids::{ChallengePrivateAssetId, ChallengeReviewRecordId, HumanId};
use agentics_domain::models::names::AssetName;
use agentics_domain::models::paths::RepoRelativePath;
use agentics_domain::models::urls::{GithubPullRequestUrl, GithubRepoRemote};
use agentics_domain::storage::StorageKey;
use agentics_error::{Result, ServiceError};

mod assets;
mod audit;
mod publishing;
mod rows;
mod validation;

pub use assets::{
    activate_challenge_private_asset, activate_challenge_private_asset_with_audit,
    fail_challenge_private_asset, private_asset_storage_key_has_active_reference,
    reserve_challenge_private_asset,
};
pub use audit::CreateChallengeReviewRecordAuditEventInput;
use audit::create_challenge_review_audit_event_tx;
pub use publishing::{
    ClaimedChallengeReviewRecordForPublish, PublishArchiveChallengeReviewRecordInput,
    PublishNewChallengeReviewRecordInput, claim_challenge_review_record_for_publish,
    fail_challenge_review_record_publish, mark_challenge_review_record_published,
    publish_archive_challenge_review_record, publish_new_challenge_review_record,
};
pub use rows::{
    AdminChallengePrivateAssetRecord, ChallengePrivateAssetRecord, ChallengeReviewRecordRecord,
    ChallengeReviewValidationRecord, list_challenge_private_asset_states,
};
use rows::{
    list_private_assets_for_review_record, list_validation_records_for_review_record,
    optional_storage_key_from_row, row_to_review_record, storage_key_from_row,
};
pub use validation::{
    BeginChallengeReviewRecordValidationInput, FinishChallengeReviewRecordValidationInput,
    begin_challenge_review_record_validation, finish_challenge_review_record_validation,
};

use super::ids::{challenge_private_asset_id_from_row, challenge_review_record_id_from_row};

/// Input for inserting one GitHub PR-backed challenge review record.
#[derive(Debug, Clone)]
pub struct CreateChallengeReviewRecordInput {
    pub review_record_id: ChallengeReviewRecordId,
    pub creator_human_id: HumanId,
    pub max_active_review_records: i64,
    pub creator_github_user_id: GithubUserId,
    pub creator_github_login: String,
    pub repo_url: GithubRepoRemote,
    pub pr_number: GithubPullRequestNumber,
    pub pr_url: GithubPullRequestUrl,
    pub commit_sha: GitCommitSha,
    pub challenge_path: RepoRelativePath,
    pub manifest_sha256: Sha256Digest,
    pub manifest: ChallengeCreationManifest,
}

/// Input for persisting one private benchmark asset.
#[derive(Debug, Clone)]
pub struct CreateChallengePrivateAssetInput {
    pub asset_row_id: ChallengePrivateAssetId,
    pub review_record_id: ChallengeReviewRecordId,
    pub asset_name: AssetName,
    pub kind: ChallengePrivateAssetKind,
    pub required: bool,
    pub size_bytes: i64,
    pub sha256: Sha256Digest,
    pub storage_key: StorageKey,
    pub temporary_storage_key: StorageKey,
    pub uploader_human_id: HumanId,
}

/// Internal private asset cleanup candidate.
#[derive(Debug, Clone)]
pub struct ChallengePrivateAssetPurgeRecord {
    pub id: ChallengePrivateAssetId,
    pub storage_key: StorageKey,
    pub temporary_storage_key: Option<StorageKey>,
}

/// Insert a new challenge review record bound to a GitHub PR.
pub async fn create_challenge_review_record(
    pool: &PgPool,
    input: &CreateChallengeReviewRecordInput,
    audit_event: &CreateChallengeReviewRecordAuditEventInput,
) -> Result<ChallengeReviewRecordRecord> {
    if audit_event.review_record_id != input.review_record_id {
        return Err(ServiceError::Internal(
            "review record creation audit event targets a different review record".to_string(),
        ));
    }
    let manifest_json =
        serde_json::to_value(&input.manifest).map_err(|e| ServiceError::Internal(e.to_string()))?;
    let mut tx = pool.begin().await?;
    let scope = format!("challenge-review-records:human:{}", input.creator_human_id);
    lock_quota_scope(&mut tx, &scope).await?;
    let active_review_records =
        count_active_challenge_review_records_for_human_tx(&mut tx, &input.creator_human_id)
            .await?;
    if active_review_records >= input.max_active_review_records {
        return Err(ServiceError::TooManyRequests(format!(
            "challenge review record quota exceeded: {active_review_records} of {} active review records are already open",
            input.max_active_review_records
        )));
    }
    let row = sqlx::query(
        r#"
        INSERT INTO challenge_review_records (
            id,
            challenge_name,
            request_kind,
            status,
            creator_human_id,
            creator_github_user_id,
            creator_github_login,
            repo_url,
            repo_key,
            pr_number,
            pr_url,
            commit_sha,
            challenge_path,
            manifest_sha256,
            manifest_json
        )
        VALUES ($1::uuid, $2, $3, 'pending_review', $4::uuid, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
        RETURNING *
        "#,
    )
    .bind(input.review_record_id.as_str())
    .bind(input.manifest.challenge_name.as_str())
    .bind(input.manifest.request.as_str())
    .bind(input.creator_human_id.as_str())
    .bind(input.creator_github_user_id.as_i64())
    .bind(&input.creator_github_login)
    .bind(input.repo_url.as_str())
    .bind(input.repo_url.repository_key().as_str())
    .bind(input.pr_number.as_i32().map_err(|e| {
        ServiceError::Internal(format!(
            "invalid typed pull request number reached database: {e}"
        ))
    })?)
    .bind(input.pr_url.as_str())
    .bind(input.commit_sha.to_string())
    .bind(input.challenge_path.as_str())
    .bind(input.manifest_sha256.to_string())
    .bind(&manifest_json)
    .fetch_one(&mut *tx)
    .await?;

    create_challenge_review_audit_event_tx(&mut tx, audit_event).await?;
    tx.commit().await?;

    row_to_review_record(row, Vec::new(), Vec::new())
}

/// Get one review_record with its private assets and validation records.
pub async fn get_challenge_review_record(
    pool: &PgPool,
    review_record_id: &ChallengeReviewRecordId,
) -> Result<Option<ChallengeReviewRecordRecord>> {
    let row = sqlx::query("SELECT * FROM challenge_review_records WHERE id = $1::uuid")
        .bind(review_record_id.as_str())
        .fetch_optional(pool)
        .await?;

    let Some(row) = row else {
        return Ok(None);
    };

    let assets = list_private_assets_for_review_record(pool, review_record_id).await?;
    let validation_records =
        list_validation_records_for_review_record(pool, review_record_id).await?;
    row_to_review_record(row, assets, validation_records).map(Some)
}

/// List recent review_records for admin review.
pub async fn list_challenge_review_records(
    pool: &PgPool,
    limit: i64,
) -> Result<Vec<ChallengeReviewRecordRecord>> {
    let rows = sqlx::query(
        r#"
        SELECT *
        FROM challenge_review_records
        ORDER BY updated_at DESC, created_at DESC
        LIMIT $1
        "#,
    )
    .bind(limit)
    .fetch_all(pool)
    .await?;

    let mut review_records = Vec::with_capacity(rows.len());
    for row in rows {
        let review_record_id = challenge_review_record_id_from_row(&row, "id")?;
        let assets = list_private_assets_for_review_record(pool, &review_record_id).await?;
        let validation_records =
            list_validation_records_for_review_record(pool, &review_record_id).await?;
        review_records.push(row_to_review_record(row, assets, validation_records)?);
    }
    Ok(review_records)
}

/// Count non-terminal review_records owned by a human for creator quota enforcement.
async fn count_active_challenge_review_records_for_human_tx(
    tx: &mut Transaction<'_, Postgres>,
    human_id: &HumanId,
) -> Result<i64> {
    let count = sqlx::query_scalar::<_, i64>(
        r#"
        SELECT COUNT(*)::BIGINT
        FROM challenge_review_records
        WHERE creator_human_id = $1::uuid
          AND status IN ('pending_review', 'validated', 'approved', 'publishing')
        "#,
    )
    .bind(human_id.as_str())
    .fetch_one(&mut **tx)
    .await?;

    Ok(count)
}

/// Fail and clear active validation leases that exceeded the configured timeout.
pub(super) async fn clear_stale_active_validation_tx(
    tx: &mut Transaction<'_, Postgres>,
    review_record_id: &str,
    timeout_minutes: i32,
) -> Result<()> {
    let stale_validation_id: Option<String> = sqlx::query_scalar(
        r#"
        SELECT v.id::text
        FROM challenge_review_records d
        JOIN challenge_review_validation_records v ON v.id = d.active_validation_record_id
        WHERE d.id = $1::uuid
          AND (
            v.status <> 'running'
            OR v.created_at < NOW() - INTERVAL '1 minute' * $2
          )
        "#,
    )
    .bind(review_record_id)
    .bind(timeout_minutes.max(1))
    .fetch_optional(&mut **tx)
    .await?;
    let Some(stale_validation_id) = stale_validation_id else {
        return Ok(());
    };

    sqlx::query(
        r#"
        UPDATE challenge_review_validation_records
        SET status = 'failed',
            message = 'challenge review record validation lease expired'
        WHERE id = $1::uuid
          AND status = 'running'
        "#,
    )
    .bind(&stale_validation_id)
    .execute(&mut **tx)
    .await?;

    sqlx::query(
        r#"
        UPDATE challenge_review_records
        SET active_validation_record_id = NULL,
            validation_message = 'challenge review record validation lease expired',
            updated_at = NOW()
        WHERE id = $1::uuid
          AND active_validation_record_id = $2::uuid
        "#,
    )
    .bind(review_record_id)
    .bind(&stale_validation_id)
    .execute(&mut **tx)
    .await?;

    Ok(())
}

/// Handles lock quota scope for this module.
pub(super) async fn lock_quota_scope(
    tx: &mut Transaction<'_, Postgres>,
    scope: &str,
) -> Result<()> {
    sqlx::query(
        r#"
        INSERT INTO quota_admission_locks (scope)
        VALUES ($1)
        ON CONFLICT (scope) DO NOTHING
        "#,
    )
    .bind(scope)
    .execute(&mut **tx)
    .await?;

    sqlx::query(
        r#"
        SELECT scope
        FROM quota_admission_locks
        WHERE scope = $1
        FOR UPDATE
        "#,
    )
    .bind(scope)
    .fetch_one(&mut **tx)
    .await?;

    Ok(())
}

/// Approve the latest validated review_record content and freeze its review digest.
pub async fn approve_validated_challenge_review_record(
    pool: &PgPool,
    review_record_id: &str,
    message: Option<&str>,
) -> Result<()> {
    let result = sqlx::query(
        r#"
        UPDATE challenge_review_records
        SET status = 'approved',
            validation_message = COALESCE($2, validation_message),
            approved_bundle_sha256 = validation_bundle_sha256,
            updated_at = NOW()
        WHERE id = $1::uuid
          AND status = 'validated'
          AND validation_bundle_sha256 IS NOT NULL
          AND active_validation_record_id IS NULL
        "#,
    )
    .bind(review_record_id)
    .bind(message)
    .execute(pool)
    .await?;

    if result.rows_affected() == 0 {
        return Err(ServiceError::Conflict);
    }
    Ok(())
}

/// Approve a validated review_record and audit the exact digest approved in one transaction.
pub async fn approve_validated_challenge_review_record_with_audit(
    pool: &PgPool,
    review_record_id: &ChallengeReviewRecordId,
    expected_validation_bundle_sha256: &Sha256Digest,
    message: Option<&str>,
    audit_event: &CreateChallengeReviewRecordAuditEventInput,
) -> Result<()> {
    if audit_event.review_record_id != *review_record_id {
        return Err(ServiceError::Internal(
            "review record approval audit event targets a different review record".to_string(),
        ));
    }
    let mut tx = pool.begin().await?;
    let row = sqlx::query(
        r#"
        UPDATE challenge_review_records
        SET status = 'approved',
            validation_message = COALESCE($2, validation_message),
            approved_bundle_sha256 = validation_bundle_sha256,
            updated_at = NOW()
        WHERE id = $1::uuid
          AND status = 'validated'
          AND validation_bundle_sha256 IS NOT NULL
          AND validation_bundle_sha256 = $3
          AND active_validation_record_id IS NULL
        RETURNING approved_bundle_sha256
        "#,
    )
    .bind(review_record_id.as_str())
    .bind(message)
    .bind(expected_validation_bundle_sha256.to_string())
    .fetch_optional(&mut *tx)
    .await?;

    let Some(row) = row else {
        return Err(ServiceError::Conflict);
    };
    let approved_bundle_sha256: Option<String> = row.try_get("approved_bundle_sha256")?;
    create_challenge_review_audit_event_tx(
        &mut tx,
        &CreateChallengeReviewRecordAuditEventInput {
            event_id: audit_event.event_id.clone(),
            review_record_id: review_record_id.clone(),
            actor_human_id: audit_event.actor_human_id.clone(),
            actor_admin_service_token_id: audit_event.actor_admin_service_token_id.clone(),
            actor_display: audit_event.actor_display.clone(),
            action: "review_record_approved".to_string(),
            message: message.unwrap_or_default().to_string(),
            metadata: serde_json::json!({ "approved_bundle_sha256": approved_bundle_sha256 }),
        },
    )
    .await?;

    tx.commit().await?;
    Ok(())
}

/// Move a review_record to a review status.
pub async fn update_challenge_review_record_status(
    pool: &PgPool,
    review_record_id: &str,
    status: ChallengeReviewRecordStatus,
    message: Option<&str>,
) -> Result<()> {
    let result = sqlx::query(
        r#"
        UPDATE challenge_review_records
        SET status = $2,
            validation_message = COALESCE($3, validation_message),
            updated_at = NOW()
        WHERE id = $1::uuid
          AND status IN ('pending_review', 'validated', 'approved')
          AND active_validation_record_id IS NULL
        "#,
    )
    .bind(review_record_id)
    .bind(status.as_str())
    .bind(message)
    .execute(pool)
    .await?;

    if result.rows_affected() == 0 {
        return Err(ServiceError::Conflict);
    }
    Ok(())
}

/// Move a review_record to a review status and append its audit event atomically.
pub async fn update_challenge_review_record_status_with_audit(
    pool: &PgPool,
    review_record_id: &ChallengeReviewRecordId,
    status: ChallengeReviewRecordStatus,
    message: Option<&str>,
    audit_event: &CreateChallengeReviewRecordAuditEventInput,
) -> Result<()> {
    let mut tx = pool.begin().await?;
    let result = sqlx::query(
        r#"
        UPDATE challenge_review_records
        SET status = $2,
            validation_message = COALESCE($3, validation_message),
            updated_at = NOW()
        WHERE id = $1::uuid
          AND status IN ('pending_review', 'validated', 'approved')
          AND active_validation_record_id IS NULL
        "#,
    )
    .bind(review_record_id.as_str())
    .bind(status.as_str())
    .bind(message)
    .execute(&mut *tx)
    .await?;

    if result.rows_affected() == 0 {
        return Err(ServiceError::Conflict);
    }
    create_challenge_review_audit_event_tx(&mut tx, audit_event).await?;
    tx.commit().await?;
    Ok(())
}

/// Mark one review_record abandoned unless it has already been published.
pub async fn abandon_challenge_review_record(
    pool: &PgPool,
    review_record_id: &str,
    message: Option<&str>,
) -> Result<()> {
    let result = sqlx::query(
        r#"
        UPDATE challenge_review_records
        SET status = 'abandoned',
            validation_message = COALESCE($2, validation_message),
            updated_at = NOW()
        WHERE id = $1::uuid
          AND status IN ('pending_review', 'validated', 'approved', 'rejected')
          AND active_validation_record_id IS NULL
        "#,
    )
    .bind(review_record_id)
    .bind(message)
    .execute(pool)
    .await?;

    if result.rows_affected() == 0 {
        return Err(ServiceError::Conflict);
    }
    Ok(())
}

/// Mark one review_record abandoned and append its audit event atomically.
pub async fn abandon_challenge_review_record_with_audit(
    pool: &PgPool,
    review_record_id: &ChallengeReviewRecordId,
    message: Option<&str>,
    audit_event: &CreateChallengeReviewRecordAuditEventInput,
) -> Result<()> {
    let mut tx = pool.begin().await?;
    let result = sqlx::query(
        r#"
        UPDATE challenge_review_records
        SET status = 'abandoned',
            validation_message = COALESCE($2, validation_message),
            updated_at = NOW()
        WHERE id = $1::uuid
          AND status IN ('pending_review', 'validated', 'approved', 'rejected')
          AND active_validation_record_id IS NULL
        "#,
    )
    .bind(review_record_id.as_str())
    .bind(message)
    .execute(&mut *tx)
    .await?;

    if result.rows_affected() == 0 {
        return Err(ServiceError::Conflict);
    }
    create_challenge_review_audit_event_tx(&mut tx, audit_event).await?;
    tx.commit().await?;
    Ok(())
}

/// Mark inactive unpublished review_records abandoned after the configured TTL.
pub async fn abandon_stale_challenge_review_records(pool: &PgPool, ttl_days: i64) -> Result<i64> {
    let result = sqlx::query(
        r#"
        UPDATE challenge_review_records
        SET status = 'abandoned',
            validation_message = COALESCE(validation_message, 'review record abandoned due to inactivity'),
            updated_at = NOW()
        WHERE status IN ('pending_review', 'validated', 'approved')
          AND updated_at < NOW() - ($1::TEXT || ' days')::INTERVAL
        "#,
    )
    .bind(ttl_days)
    .execute(pool)
    .await?;

    i64::try_from(result.rows_affected()).map_err(|_| {
        ServiceError::Internal("abandoned review record count exceeds supported range".to_string())
    })
}

/// List private assets eligible for cleanup because their review_record did not publish.
pub async fn list_unpublished_private_assets_for_purge(
    pool: &PgPool,
    grace_days: i64,
) -> Result<Vec<ChallengePrivateAssetPurgeRecord>> {
    let rows = sqlx::query(
        r#"
        SELECT a.id, a.storage_key, a.temporary_storage_key
        FROM challenge_private_assets a
        JOIN challenge_review_records d ON d.id = a.review_record_id
        WHERE d.status IN ('abandoned', 'rejected')
          AND d.updated_at < NOW() - ($1::TEXT || ' days')::INTERVAL
          AND a.status IN ('pending', 'active', 'failed', 'purging')
        ORDER BY a.created_at ASC
        "#,
    )
    .bind(grace_days)
    .fetch_all(pool)
    .await?;

    rows.into_iter()
        .map(|row| {
            Ok(ChallengePrivateAssetPurgeRecord {
                id: challenge_private_asset_id_from_row(&row, "id")?,
                storage_key: storage_key_from_row(&row, "storage_key")?,
                temporary_storage_key: optional_storage_key_from_row(
                    &row,
                    "temporary_storage_key",
                )?,
            })
        })
        .collect()
}

/// Mark a purge-eligible private asset as purging before deleting storage.
pub async fn mark_challenge_private_asset_purging(
    pool: &PgPool,
    asset_row_id: &ChallengePrivateAssetId,
) -> Result<Option<ChallengePrivateAssetPurgeRecord>> {
    let row = sqlx::query(
        r#"
        UPDATE challenge_private_assets
        SET status = 'purging'
        WHERE id = $1::uuid
          AND status IN ('pending', 'active', 'failed', 'purging')
        RETURNING id, storage_key, temporary_storage_key
        "#,
    )
    .bind(asset_row_id.as_str())
    .fetch_optional(pool)
    .await?;

    row.map(|row| {
        Ok(ChallengePrivateAssetPurgeRecord {
            id: challenge_private_asset_id_from_row(&row, "id")?,
            storage_key: storage_key_from_row(&row, "storage_key")?,
            temporary_storage_key: optional_storage_key_from_row(&row, "temporary_storage_key")?,
        })
    })
    .transpose()
}

/// Delete a private asset record after its object has been removed.
pub async fn delete_challenge_private_asset(
    pool: &PgPool,
    asset_row_id: &ChallengePrivateAssetId,
) -> Result<()> {
    sqlx::query(
        r#"
        WITH deleted AS (
            DELETE FROM challenge_private_assets
            WHERE id = $1::uuid
            RETURNING review_record_id
        )
        UPDATE challenge_review_records d
        SET updated_at = NOW()
        WHERE d.id IN (SELECT review_record_id FROM deleted)
        "#,
    )
    .bind(asset_row_id.as_str())
    .execute(pool)
    .await?;

    Ok(())
}