tuitbot-core 0.1.47

Core library for Tuitbot autonomous X growth assistant
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Append-only action log for auditing and status reporting.
//!
//! Records every action taken by the agent with timestamps,
//! status, and optional metadata in JSON format.

use super::accounts::DEFAULT_ACCOUNT_ID;
use super::DbPool;
use crate::error::StorageError;
use std::collections::HashMap;

/// An entry in the action audit log.
#[derive(Debug, Clone, sqlx::FromRow, serde::Serialize)]
pub struct ActionLogEntry {
    /// Internal auto-generated ID.
    pub id: i64,
    /// Action type: search, reply, tweet, thread, mention_check, cleanup, auth_refresh.
    pub action_type: String,
    /// Status: success, failure, or skipped.
    pub status: String,
    /// Human-readable description.
    pub message: Option<String>,
    /// JSON blob for flexible extra data.
    pub metadata: Option<String>,
    /// ISO-8601 UTC timestamp.
    pub created_at: String,
}

/// Insert a new action log entry for a specific account.
///
/// The `metadata` parameter is a pre-serialized JSON string; the caller
/// is responsible for serialization. The `created_at` field uses the SQL default.
pub async fn log_action_for(
    pool: &DbPool,
    account_id: &str,
    action_type: &str,
    status: &str,
    message: Option<&str>,
    metadata: Option<&str>,
) -> Result<(), StorageError> {
    sqlx::query(
        "INSERT INTO action_log (account_id, action_type, status, message, metadata) \
         VALUES (?, ?, ?, ?, ?)",
    )
    .bind(account_id)
    .bind(action_type)
    .bind(status)
    .bind(message)
    .bind(metadata)
    .execute(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(())
}

/// Insert a new action log entry.
///
/// The `metadata` parameter is a pre-serialized JSON string; the caller
/// is responsible for serialization. The `created_at` field uses the SQL default.
pub async fn log_action(
    pool: &DbPool,
    action_type: &str,
    status: &str,
    message: Option<&str>,
    metadata: Option<&str>,
) -> Result<(), StorageError> {
    log_action_for(
        pool,
        DEFAULT_ACCOUNT_ID,
        action_type,
        status,
        message,
        metadata,
    )
    .await
}

/// Fetch action log entries since a given timestamp for a specific account,
/// optionally filtered by type.
///
/// Results are ordered by `created_at` ascending.
pub async fn get_actions_since_for(
    pool: &DbPool,
    account_id: &str,
    since: &str,
    action_type: Option<&str>,
) -> Result<Vec<ActionLogEntry>, StorageError> {
    match action_type {
        Some(at) => sqlx::query_as::<_, ActionLogEntry>(
            "SELECT * FROM action_log WHERE created_at >= ? AND action_type = ? \
                 AND account_id = ? ORDER BY created_at ASC",
        )
        .bind(since)
        .bind(at)
        .bind(account_id)
        .fetch_all(pool)
        .await
        .map_err(|e| StorageError::Query { source: e }),
        None => sqlx::query_as::<_, ActionLogEntry>(
            "SELECT * FROM action_log WHERE created_at >= ? \
                 AND account_id = ? ORDER BY created_at ASC",
        )
        .bind(since)
        .bind(account_id)
        .fetch_all(pool)
        .await
        .map_err(|e| StorageError::Query { source: e }),
    }
}

/// Fetch action log entries since a given timestamp, optionally filtered by type.
///
/// Results are ordered by `created_at` ascending.
pub async fn get_actions_since(
    pool: &DbPool,
    since: &str,
    action_type: Option<&str>,
) -> Result<Vec<ActionLogEntry>, StorageError> {
    get_actions_since_for(pool, DEFAULT_ACCOUNT_ID, since, action_type).await
}

/// Get counts of each action type since a given timestamp for a specific account.
///
/// Returns a HashMap mapping action types to their counts.
pub async fn get_action_counts_since_for(
    pool: &DbPool,
    account_id: &str,
    since: &str,
) -> Result<HashMap<String, i64>, StorageError> {
    let rows: Vec<(String, i64)> = sqlx::query_as(
        "SELECT action_type, COUNT(*) as count FROM action_log \
         WHERE created_at >= ? AND account_id = ? GROUP BY action_type",
    )
    .bind(since)
    .bind(account_id)
    .fetch_all(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(rows.into_iter().collect())
}

/// Get counts of each action type since a given timestamp.
///
/// Returns a HashMap mapping action types to their counts.
pub async fn get_action_counts_since(
    pool: &DbPool,
    since: &str,
) -> Result<HashMap<String, i64>, StorageError> {
    get_action_counts_since_for(pool, DEFAULT_ACCOUNT_ID, since).await
}

/// Get the most recent action log entries for a specific account, newest first.
pub async fn get_recent_actions_for(
    pool: &DbPool,
    account_id: &str,
    limit: u32,
) -> Result<Vec<ActionLogEntry>, StorageError> {
    sqlx::query_as::<_, ActionLogEntry>(
        "SELECT * FROM action_log WHERE account_id = ? ORDER BY created_at DESC LIMIT ?",
    )
    .bind(account_id)
    .bind(limit)
    .fetch_all(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })
}

/// Get the most recent action log entries, newest first.
pub async fn get_recent_actions(
    pool: &DbPool,
    limit: u32,
) -> Result<Vec<ActionLogEntry>, StorageError> {
    get_recent_actions_for(pool, DEFAULT_ACCOUNT_ID, limit).await
}

/// Fetch paginated action log entries for a specific account with optional
/// type and status filters.
///
/// Results are ordered by `created_at` descending (newest first).
pub async fn get_actions_paginated_for(
    pool: &DbPool,
    account_id: &str,
    limit: u32,
    offset: u32,
    action_type: Option<&str>,
    status: Option<&str>,
) -> Result<Vec<ActionLogEntry>, StorageError> {
    let mut sql = String::from("SELECT * FROM action_log WHERE 1=1 AND account_id = ?");
    if action_type.is_some() {
        sql.push_str(" AND action_type = ?");
    }
    if status.is_some() {
        sql.push_str(" AND status = ?");
    }
    sql.push_str(" ORDER BY created_at DESC LIMIT ? OFFSET ?");

    let mut query = sqlx::query_as::<_, ActionLogEntry>(&sql);
    query = query.bind(account_id);
    if let Some(at) = action_type {
        query = query.bind(at);
    }
    if let Some(st) = status {
        query = query.bind(st);
    }
    query = query.bind(limit).bind(offset);

    query
        .fetch_all(pool)
        .await
        .map_err(|e| StorageError::Query { source: e })
}

/// Fetch paginated action log entries with optional type and status filters.
///
/// Results are ordered by `created_at` descending (newest first).
pub async fn get_actions_paginated(
    pool: &DbPool,
    limit: u32,
    offset: u32,
    action_type: Option<&str>,
    status: Option<&str>,
) -> Result<Vec<ActionLogEntry>, StorageError> {
    get_actions_paginated_for(pool, DEFAULT_ACCOUNT_ID, limit, offset, action_type, status).await
}

/// Get total count of action log entries for a specific account with optional
/// type and status filters.
pub async fn get_actions_count_for(
    pool: &DbPool,
    account_id: &str,
    action_type: Option<&str>,
    status: Option<&str>,
) -> Result<i64, StorageError> {
    let mut sql = String::from("SELECT COUNT(*) FROM action_log WHERE 1=1 AND account_id = ?");
    if action_type.is_some() {
        sql.push_str(" AND action_type = ?");
    }
    if status.is_some() {
        sql.push_str(" AND status = ?");
    }

    let mut query = sqlx::query_as::<_, (i64,)>(&sql);
    query = query.bind(account_id);
    if let Some(at) = action_type {
        query = query.bind(at);
    }
    if let Some(st) = status {
        query = query.bind(st);
    }

    let (count,) = query
        .fetch_one(pool)
        .await
        .map_err(|e| StorageError::Query { source: e })?;
    Ok(count)
}

/// Get total count of action log entries with optional type and status filters.
pub async fn get_actions_count(
    pool: &DbPool,
    action_type: Option<&str>,
    status: Option<&str>,
) -> Result<i64, StorageError> {
    get_actions_count_for(pool, DEFAULT_ACCOUNT_ID, action_type, status).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::init_test_db;

    #[tokio::test]
    async fn log_and_retrieve_action() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "search", "success", Some("Found 10 tweets"), None)
            .await
            .expect("log");

        let actions = get_actions_since(&pool, "2000-01-01T00:00:00Z", None)
            .await
            .expect("get");

        assert_eq!(actions.len(), 1);
        assert_eq!(actions[0].action_type, "search");
        assert_eq!(actions[0].status, "success");
        assert_eq!(actions[0].message.as_deref(), Some("Found 10 tweets"));
    }

    #[tokio::test]
    async fn filter_by_action_type() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "search", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "reply", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "search", "failure", None, None)
            .await
            .expect("log");

        let searches = get_actions_since(&pool, "2000-01-01T00:00:00Z", Some("search"))
            .await
            .expect("get");
        assert_eq!(searches.len(), 2);

        let replies = get_actions_since(&pool, "2000-01-01T00:00:00Z", Some("reply"))
            .await
            .expect("get");
        assert_eq!(replies.len(), 1);
    }

    #[tokio::test]
    async fn action_counts_aggregation() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "search", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "search", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "reply", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "tweet", "failure", None, None)
            .await
            .expect("log");

        let counts = get_action_counts_since(&pool, "2000-01-01T00:00:00Z")
            .await
            .expect("get counts");

        assert_eq!(counts.get("search"), Some(&2));
        assert_eq!(counts.get("reply"), Some(&1));
        assert_eq!(counts.get("tweet"), Some(&1));
    }

    #[tokio::test]
    async fn log_with_metadata() {
        let pool = init_test_db().await.expect("init db");

        let metadata = r#"{"tweet_id": "123", "score": 85}"#;
        log_action(
            &pool,
            "reply",
            "success",
            Some("Replied to tweet"),
            Some(metadata),
        )
        .await
        .expect("log");

        let actions = get_actions_since(&pool, "2000-01-01T00:00:00Z", Some("reply"))
            .await
            .expect("get");

        assert_eq!(actions[0].metadata.as_deref(), Some(metadata));
    }

    #[tokio::test]
    async fn empty_counts_returns_empty_map() {
        let pool = init_test_db().await.expect("init db");

        let counts = get_action_counts_since(&pool, "2000-01-01T00:00:00Z")
            .await
            .expect("get counts");

        assert!(counts.is_empty());
    }

    #[tokio::test]
    async fn paginated_actions_with_offset() {
        let pool = init_test_db().await.expect("init db");

        for i in 0..10 {
            log_action(
                &pool,
                "search",
                "success",
                Some(&format!("Action {i}")),
                None,
            )
            .await
            .expect("log");
        }

        let page1 = get_actions_paginated(&pool, 3, 0, None, None)
            .await
            .expect("page 1");
        assert_eq!(page1.len(), 3);

        let page2 = get_actions_paginated(&pool, 3, 3, None, None)
            .await
            .expect("page 2");
        assert_eq!(page2.len(), 3);

        // Pages should not overlap
        let ids1: Vec<i64> = page1.iter().map(|a| a.id).collect();
        let ids2: Vec<i64> = page2.iter().map(|a| a.id).collect();
        assert!(ids1.iter().all(|id| !ids2.contains(id)));
    }

    #[tokio::test]
    async fn paginated_actions_with_type_filter() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "search", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "reply", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "search", "success", None, None)
            .await
            .expect("log");

        let searches = get_actions_paginated(&pool, 10, 0, Some("search"), None)
            .await
            .expect("get");
        assert_eq!(searches.len(), 2);

        let count = get_actions_count(&pool, Some("search"), None)
            .await
            .expect("count");
        assert_eq!(count, 2);
    }

    #[tokio::test]
    async fn paginated_actions_with_status_filter() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "search", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "reply", "failure", Some("Rate limited"), None)
            .await
            .expect("log");
        log_action(&pool, "tweet", "failure", Some("API error"), None)
            .await
            .expect("log");

        let failures = get_actions_paginated(&pool, 10, 0, None, Some("failure"))
            .await
            .expect("get");
        assert_eq!(failures.len(), 2);

        let count = get_actions_count(&pool, None, Some("failure"))
            .await
            .expect("count");
        assert_eq!(count, 2);
    }

    #[tokio::test]
    async fn paginated_actions_combined_filters() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "reply", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "reply", "failure", None, None)
            .await
            .expect("log");
        log_action(&pool, "tweet", "failure", None, None)
            .await
            .expect("log");

        let reply_failures = get_actions_paginated(&pool, 10, 0, Some("reply"), Some("failure"))
            .await
            .expect("get");
        assert_eq!(reply_failures.len(), 1);

        let count = get_actions_count(&pool, Some("reply"), Some("failure"))
            .await
            .expect("count");
        assert_eq!(count, 1);
    }

    #[tokio::test]
    async fn actions_count_no_filter() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "search", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "reply", "success", None, None)
            .await
            .expect("log");

        let count = get_actions_count(&pool, None, None).await.expect("count");
        assert_eq!(count, 2);
    }

    #[tokio::test]
    async fn actions_count_empty_db() {
        let pool = init_test_db().await.expect("init db");
        let count = get_actions_count(&pool, None, None).await.expect("count");
        assert_eq!(count, 0);
    }

    #[tokio::test]
    async fn paginated_offset_beyond_data_returns_empty() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "search", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "reply", "success", None, None)
            .await
            .expect("log");

        let page = get_actions_paginated(&pool, 10, 100, None, None)
            .await
            .expect("page");
        assert!(page.is_empty(), "offset past data should return empty");
    }

    #[tokio::test]
    async fn get_recent_actions_returns_limited_set() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "search", "success", Some("first"), None)
            .await
            .expect("log");
        log_action(&pool, "reply", "success", Some("second"), None)
            .await
            .expect("log");
        log_action(&pool, "tweet", "success", Some("third"), None)
            .await
            .expect("log");

        let recent = get_recent_actions(&pool, 2).await.expect("get");
        assert_eq!(recent.len(), 2, "should respect limit");

        let all = get_recent_actions(&pool, 10).await.expect("get all");
        assert_eq!(all.len(), 3);
    }

    #[tokio::test]
    async fn log_action_with_null_message_and_metadata() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "cleanup", "success", None, None)
            .await
            .expect("log");

        let actions = get_actions_since(&pool, "2000-01-01T00:00:00Z", None)
            .await
            .expect("get");
        assert_eq!(actions.len(), 1);
        assert!(actions[0].message.is_none());
        assert!(actions[0].metadata.is_none());
    }

    #[tokio::test]
    async fn action_counts_since_future_returns_empty() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "search", "success", None, None)
            .await
            .expect("log");

        let counts = get_action_counts_since(&pool, "2099-01-01T00:00:00Z")
            .await
            .expect("counts");
        assert!(counts.is_empty());
    }

    #[tokio::test]
    async fn paginated_type_and_status_combined_count() {
        let pool = init_test_db().await.expect("init db");

        log_action(&pool, "reply", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "reply", "failure", None, None)
            .await
            .expect("log");
        log_action(&pool, "reply", "success", None, None)
            .await
            .expect("log");
        log_action(&pool, "tweet", "success", None, None)
            .await
            .expect("log");

        let count = get_actions_count(&pool, Some("reply"), Some("success"))
            .await
            .expect("count");
        assert_eq!(count, 2);

        let page = get_actions_paginated(&pool, 10, 0, Some("reply"), Some("success"))
            .await
            .expect("page");
        assert_eq!(page.len(), 2);
    }

    #[tokio::test]
    async fn log_action_for_different_accounts() {
        let pool = init_test_db().await.expect("init db");

        log_action_for(&pool, "acct_a", "search", "success", Some("a"), None)
            .await
            .expect("log a");
        log_action_for(&pool, "acct_b", "search", "success", Some("b"), None)
            .await
            .expect("log b");
        log_action_for(&pool, "acct_a", "reply", "success", Some("a2"), None)
            .await
            .expect("log a2");

        let actions_a = get_actions_since_for(&pool, "acct_a", "2000-01-01T00:00:00Z", None)
            .await
            .expect("get a");
        assert_eq!(actions_a.len(), 2);

        let actions_b = get_actions_since_for(&pool, "acct_b", "2000-01-01T00:00:00Z", None)
            .await
            .expect("get b");
        assert_eq!(actions_b.len(), 1);

        let count_a = get_actions_count_for(&pool, "acct_a", None, None)
            .await
            .expect("count a");
        assert_eq!(count_a, 2);

        let count_b = get_actions_count_for(&pool, "acct_b", None, None)
            .await
            .expect("count b");
        assert_eq!(count_b, 1);
    }

    #[tokio::test]
    async fn get_recent_actions_respects_limit() {
        let pool = init_test_db().await.expect("init db");

        for i in 0..5 {
            log_action(
                &pool,
                "search",
                "success",
                Some(&format!("Action {i}")),
                None,
            )
            .await
            .expect("log");
        }

        let recent = get_recent_actions(&pool, 0).await.expect("get");
        assert!(recent.is_empty(), "limit 0 should return empty");

        let recent = get_recent_actions(&pool, 1).await.expect("get");
        assert_eq!(recent.len(), 1);
    }

    // ================================================================
    // Account-scoped `_for` variant isolation tests
    // ================================================================

    #[tokio::test]
    async fn get_action_counts_since_for_account_isolation() {
        let pool = init_test_db().await.expect("init db");

        log_action_for(&pool, "acct_x", "search", "success", None, None)
            .await
            .expect("log x");
        log_action_for(&pool, "acct_x", "search", "success", None, None)
            .await
            .expect("log x2");
        log_action_for(&pool, "acct_x", "reply", "success", None, None)
            .await
            .expect("log x3");
        log_action_for(&pool, "acct_y", "search", "success", None, None)
            .await
            .expect("log y");

        let counts_x = get_action_counts_since_for(&pool, "acct_x", "2000-01-01T00:00:00Z")
            .await
            .expect("counts x");
        assert_eq!(counts_x.get("search"), Some(&2));
        assert_eq!(counts_x.get("reply"), Some(&1));

        let counts_y = get_action_counts_since_for(&pool, "acct_y", "2000-01-01T00:00:00Z")
            .await
            .expect("counts y");
        assert_eq!(counts_y.get("search"), Some(&1));
        assert!(counts_y.get("reply").is_none());
    }

    #[tokio::test]
    async fn get_actions_paginated_for_account_isolation() {
        let pool = init_test_db().await.expect("init db");

        for i in 0..5 {
            log_action_for(
                &pool,
                "acct_p",
                "search",
                "success",
                Some(&format!("P{i}")),
                None,
            )
            .await
            .expect("log p");
        }
        for i in 0..3 {
            log_action_for(
                &pool,
                "acct_q",
                "reply",
                "failure",
                Some(&format!("Q{i}")),
                None,
            )
            .await
            .expect("log q");
        }

        // Paginate acct_p
        let page1 = get_actions_paginated_for(&pool, "acct_p", 3, 0, None, None)
            .await
            .expect("page1");
        assert_eq!(page1.len(), 3);

        let page2 = get_actions_paginated_for(&pool, "acct_p", 3, 3, None, None)
            .await
            .expect("page2");
        assert_eq!(page2.len(), 2);

        // acct_q should have its own data
        let q_all = get_actions_paginated_for(&pool, "acct_q", 10, 0, None, None)
            .await
            .expect("q all");
        assert_eq!(q_all.len(), 3);
        assert!(q_all.iter().all(|a| a.action_type == "reply"));

        // Filter by type within account
        let q_filtered =
            get_actions_paginated_for(&pool, "acct_q", 10, 0, Some("reply"), Some("failure"))
                .await
                .expect("q filtered");
        assert_eq!(q_filtered.len(), 3);

        // Cross-check: acct_p should have no reply actions
        let p_replies = get_actions_paginated_for(&pool, "acct_p", 10, 0, Some("reply"), None)
            .await
            .expect("p replies");
        assert!(p_replies.is_empty());
    }

    #[tokio::test]
    async fn get_recent_actions_for_account_isolation() {
        let pool = init_test_db().await.expect("init db");

        log_action_for(&pool, "acct_r", "search", "success", Some("R1"), None)
            .await
            .expect("log r1");
        log_action_for(&pool, "acct_r", "reply", "success", Some("R2"), None)
            .await
            .expect("log r2");
        log_action_for(&pool, "acct_s", "tweet", "success", Some("S1"), None)
            .await
            .expect("log s1");

        let recent_r = get_recent_actions_for(&pool, "acct_r", 10)
            .await
            .expect("recent r");
        assert_eq!(recent_r.len(), 2);

        let recent_s = get_recent_actions_for(&pool, "acct_s", 10)
            .await
            .expect("recent s");
        assert_eq!(recent_s.len(), 1);
        assert_eq!(recent_s[0].message.as_deref(), Some("S1"));

        // Limit works per account
        let recent_r1 = get_recent_actions_for(&pool, "acct_r", 1)
            .await
            .expect("recent r limited");
        assert_eq!(recent_r1.len(), 1);
    }
}