allsource-core 0.29.0

High-performance event store core built in Rust
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
// `cap` counts live bytes for the heap gauges; no limit is set.
#[cfg(not(all(feature = "heap-profile", target_os = "linux")))]
#[global_allocator]
static GLOBAL: cap::Cap<mimalloc::MiMalloc> = cap::Cap::new(mimalloc::MiMalloc, usize::MAX);

#[cfg(all(feature = "heap-profile", target_os = "linux"))]
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

#[cfg(all(feature = "heap-profile", target_os = "linux"))]
#[allow(non_upper_case_globals)]
#[expect(
    unsafe_code,
    reason = "jemalloc reads malloc_conf from the binary's symbol table"
)]
#[unsafe(export_name = "malloc_conf")]
pub static malloc_conf: &[u8] = b"prof:true,prof_active:true,lg_prof_sample:19\0";

#[cfg(not(all(feature = "heap-profile", target_os = "linux")))]
fn heap_live_bytes() -> u64 {
    GLOBAL.allocated() as u64
}

#[cfg(all(feature = "heap-profile", target_os = "linux"))]
fn heap_live_bytes() -> u64 {
    allsource_core::infrastructure::observability::heap::jemalloc_live_bytes()
}

#[cfg(feature = "replication")]
use allsource_core::replication::{ReplicationMode, WalReceiver, WalShipper};
use allsource_core::{
    api_v1,
    api_v1::NodeRole,
    auth::AuthManager,
    config::ServerConfig,
    domain::repositories::TenantRepository,
    infrastructure::{
        cluster::{
            ClusterManager, ClusterMember, GeoReplicationConfig, GeoReplicationManager, MemberRole,
        },
        di::ContainerBuilder,
        observability::memory,
        persistence::{
            SystemBootstrap, SystemCheckpointSettings, SystemCheckpointer, SystemMetadataStore,
            VerifyOutcome,
        },
        repositories::InMemoryTenantRepository,
        web::boot_gate::BootGate,
    },
    rate_limit::{RateLimitConfig, RateLimiter},
    resp::RespServer,
    store::EventStore,
};
use anyhow::Result;
use std::sync::Arc;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

#[cfg_attr(feature = "hotpath", hotpath::main)]
#[tokio::main]
async fn main() -> Result<()> {
    // Initialize tracing
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "allsource_core=info,tower_http=info".into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();

    // Detect node role from environment
    let role = NodeRole::from_env();

    tracing::info!(
        "🌟 AllSource Core v{} starting...",
        env!("CARGO_PKG_VERSION")
    );
    match role {
        NodeRole::Leader => tracing::info!("   Starting as LEADER"),
        NodeRole::Follower => tracing::info!("   Starting as FOLLOWER (read-only)"),
    }
    tracing::info!("   Production-ready event store with authentication & multi-tenancy");

    // Bind before the bootstrap: while it replays, the gate answers 503
    // not_ready, which the gateways hold through, instead of a refused dial.
    // Use Config::from_env() to pick up ALLSOURCE_HOST / ALLSOURCE_PORT / PORT env vars
    // (Critical on Fly.io where ALLSOURCE_HOST="::" enables IPv6 6PN internal networking)
    let server_config = ServerConfig::from_env();
    let addr = if server_config.host.contains(':') {
        format!("[{}]:{}", server_config.host, server_config.port)
    } else {
        format!("{}:{}", server_config.host, server_config.port)
    };
    let gate = BootGate::new();
    let listener = tokio::net::TcpListener::bind(&addr).await?;
    let server = {
        let gate = Arc::clone(&gate);
        tokio::spawn(async move {
            let shutdown_gate = Arc::clone(&gate);
            axum::serve(listener, gate.router())
                .with_graceful_shutdown(async move {
                    api_v1::shutdown_signal().await;
                    // Before the gate opens no handler has run, and the
                    // bootstrap blocks main until it finishes, so exiting is
                    // the only way to stop promptly.
                    if !shutdown_gate.is_open() {
                        tracing::info!("🛑 Stopping before the bootstrap finished");
                        std::process::exit(0);
                    }
                })
                .await
        })
    };
    tracing::info!("🚦 Listening on {addr}; answering not_ready until the bootstrap finishes");

    // Initialize components — read persistence config from environment
    let (config, mode) = allsource_core::store::EventStoreConfig::from_env();
    if mode == "in-memory" {
        tracing::warn!(
            "   Persistence: NONE (in-memory only) — set ALLSOURCE_DATA_DIR for durability"
        );
    } else {
        tracing::info!(
            "   Persistence: {} (storage_dir={:?}, wal_dir={:?})",
            mode,
            config.storage_dir,
            config.wal_dir
        );
    }
    let mut store = match EventStore::try_with_config(config) {
        Ok(store) => store,
        Err(error) => {
            tracing::error!("Core cannot open its local storage: {error}");
            std::process::exit(1);
        }
    };

    // Initialize WAL replication if this is a leader with replication enabled
    #[cfg(feature = "replication")]
    let replication_enabled =
        std::env::var("ALLSOURCE_REPLICATION_ENABLED").is_ok_and(|v| v == "true");
    #[cfg(feature = "replication")]
    let replication_port: u16 = std::env::var("ALLSOURCE_REPLICATION_PORT")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(3910);
    #[cfg(not(feature = "replication"))]
    let replication_port: u16 = 3910;

    // Read replication mode and ACK timeout
    #[cfg(feature = "replication")]
    let replication_mode = std::env::var("ALLSOURCE_REPLICATION_MODE")
        .map_or(ReplicationMode::Async, |v| {
            ReplicationMode::from_str_value(&v)
        });
    #[cfg(feature = "replication")]
    let ack_timeout_ms: u64 = std::env::var("ALLSOURCE_REPLICATION_ACK_TIMEOUT_MS")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(5000);

    // Create WAL shipper (but don't spawn yet — needs store Arc first for catch-up)
    #[cfg(feature = "replication")]
    let wal_shipper_raw = if replication_enabled && role == NodeRole::Leader {
        let (mut shipper, tx) = WalShipper::new();
        shipper.set_replication_mode(
            replication_mode,
            std::time::Duration::from_millis(ack_timeout_ms),
        );
        store.enable_wal_replication(tx);
        Some(shipper)
    } else {
        if replication_enabled && role == NodeRole::Follower {
            tracing::info!("   Replication enabled but this is a follower — shipper not started");
        }
        None
    };

    // Initialize system metadata (event-sourced repositories) BEFORE Arc-wrapping the store,
    // so we can set the durable consumer registry via &mut self.
    let system_data_dir = std::env::var("ALLSOURCE_SYSTEM_DATA_DIR")
        .ok()
        .filter(|s| !s.is_empty())
        .map(std::path::PathBuf::from)
        .or_else(|| {
            std::env::var("ALLSOURCE_DATA_DIR")
                .ok()
                .filter(|s| !s.is_empty())
                .map(|d| std::path::PathBuf::from(d).join("__system"))
        });
    let bootstrap_tenant = std::env::var("ALLSOURCE_BOOTSTRAP_TENANT")
        .ok()
        .filter(|s| !s.is_empty());
    let system_repos = SystemBootstrap::try_initialize_with(
        system_data_dir,
        bootstrap_tenant,
        SystemCheckpointSettings::from_env(),
    )
    .await;
    let checkpointer = system_repos.as_ref().map(|r| Arc::clone(&r.checkpointer));
    if let Some(checkpointer) = &checkpointer {
        spawn_system_checkpoints(checkpointer);
    }

    // Wire durable consumer registry into EventStore before Arc wrapping
    if let Some(ref repos) = system_repos {
        store.set_consumer_registry(repos.consumer_registry.clone());
    }

    let store = Arc::new(store);

    // Populate the on-disk storage-size gauges once at boot so the dashboard's
    // "storage" card reflects reality immediately, rather than reading 0 until the
    // first checkpoint tick (or staying 0 forever if checkpointing is disabled).
    {
        let store_for_metrics = Arc::clone(&store);
        tokio::task::spawn_blocking(move || store_for_metrics.refresh_storage_metrics_now());
    }

    spawn_memory_upkeep(
        Arc::clone(&store),
        system_repos.as_ref().map(|r| Arc::clone(&r.system_store)),
    );

    // Step 6: spawn the background checkpoint loop if a cadence is
    // configured. Each tick flushes pending Parquet batches and, on
    // success, truncates the WAL — bounding dirty-restart replay to
    // one interval of writes regardless of total dataset size.
    if let Some(interval) = store.checkpoint_interval() {
        let store_for_checkpoint = Arc::clone(&store);
        tokio::spawn(async move {
            let mut ticker = tokio::time::interval(interval);
            ticker.tick().await; // first tick fires immediately — skip it
            loop {
                ticker.tick().await;
                let store = Arc::clone(&store_for_checkpoint);
                let result = tokio::task::spawn_blocking(move || store.checkpoint()).await;
                match result {
                    Ok(Ok(())) => tracing::debug!("✅ Background checkpoint complete"),
                    Ok(Err(e)) => tracing::warn!("Background checkpoint failed: {e}"),
                    Err(e) => tracing::warn!("Background checkpoint task panicked: {e}"),
                }
            }
        });
        tracing::info!(
            "✅ Background WAL checkpoint loop started (interval: {:?})",
            interval
        );
    }

    // Step 4: the only thing that drives the per-tenant compaction sweep,
    // and so the only thing that applies retention — a tenant's TTL is
    // enforced inside the sweep, not on its own cadence (gh#321).
    if let Some(manager) = store.compaction_manager() {
        let interval = std::time::Duration::from_secs(
            manager
                .config()
                .compaction_interval_seconds
                .clamp(60, 86_400),
        );
        // Derived from the last sweep's recorded time, not from boot. Re-arming
        // the full interval on every start meant a process restarting more
        // often than the interval never reached its first tick (gh#321).
        let first_delay = manager.delay_until_next_sweep(std::time::Duration::from_secs(120));
        // `allsource_compaction_*` were registered but never incremented outside
        // their own unit test, so an alarm on them read zero however many sweeps
        // had run (gh#321).
        let sweep_metrics = store.metrics();
        tracing::info!(
            last_compaction = ?manager.last_compaction(),
            first_sweep_in_secs = first_delay.as_secs(),
            "Compaction sweep scheduled"
        );
        tokio::spawn(async move {
            tokio::time::sleep(first_delay).await;
            let mut ticker = tokio::time::interval(interval);
            loop {
                ticker.tick().await;
                let manager = Arc::clone(&manager);
                // One sweep at a time. `spawn_blocking` is awaited before the
                // next tick is read, and `tokio::time::interval` drops missed
                // ticks rather than queueing them, so a sweep that outlives
                // its interval cannot overlap the next.
                let result = tokio::task::spawn_blocking(move || {
                    if !manager.should_compact() {
                        return None;
                    }
                    Some(manager.compact())
                })
                .await;
                match result {
                    Ok(None) => {}
                    Ok(Some(Ok(r))) => {
                        sweep_metrics.record_compaction_sweep(
                            r.files_compacted as u64,
                            r.bytes_before,
                            r.bytes_after,
                        );
                        if r.files_compacted > 0 {
                            tracing::info!(
                                files_compacted = r.files_compacted,
                                events_compacted = r.events_compacted,
                                bytes_before = r.bytes_before,
                                bytes_after = r.bytes_after,
                                duration_ms = r.duration_ms,
                                "✅ Background compaction sweep complete"
                            );
                        } else {
                            tracing::debug!("Background compaction sweep found nothing to compact");
                        }
                    }
                    Ok(Some(Err(e))) => tracing::warn!("Background compaction failed: {e}"),
                    Err(e) => tracing::warn!("Background compaction task panicked: {e}"),
                }
            }
        });
        tracing::info!(
            "✅ Background compaction loop started (interval: {:?})",
            interval
        );
    }

    // Now that store is in Arc, attach it to the shipper and spawn
    #[cfg(feature = "replication")]
    let wal_shipper = if let Some(mut shipper) = wal_shipper_raw {
        shipper.set_store(Arc::clone(&store));
        shipper.set_metrics(store.metrics());
        let shipper = Arc::new(shipper);
        let shipper_clone = Arc::clone(&shipper);
        tokio::spawn(async move {
            if let Err(e) = shipper_clone.serve(replication_port).await {
                tracing::error!("Replication server error: {}", e);
            }
        });
        tracing::info!(
            "✅ WAL replication enabled on port {} (mode: {}, ack_timeout: {}ms)",
            replication_port,
            replication_mode,
            ack_timeout_ms,
        );
        Some(shipper)
    } else {
        None
    };
    #[cfg(not(feature = "replication"))]
    let wal_shipper: Option<Arc<allsource_core::replication::WalShipper>> = None;

    // Initialize WAL receiver if this is a follower with a leader URL configured
    #[cfg(feature = "replication")]
    let wal_receiver = if role == NodeRole::Follower {
        if let Ok(leader_url) = std::env::var("ALLSOURCE_LEADER_URL")
            && !leader_url.is_empty()
        {
            let follower_wal_dir = std::env::var("ALLSOURCE_DATA_DIR")
                .unwrap_or_else(|_| "/tmp/allsource".to_string());
            let wal_dir = std::path::PathBuf::from(&follower_wal_dir).join("follower-wal");

            match WalReceiver::new(leader_url.clone(), &wal_dir, Arc::clone(&store)) {
                Ok(mut receiver) => {
                    receiver.set_metrics(store.metrics());
                    let receiver = Arc::new(receiver);
                    let receiver_clone = Arc::clone(&receiver);
                    tokio::spawn(async move {
                        receiver_clone.run().await;
                    });
                    tracing::info!(
                        "✅ WAL receiver started, connecting to leader at {}",
                        leader_url,
                    );
                    Some(receiver)
                }
                Err(e) => {
                    tracing::error!("Failed to initialize WAL receiver: {}", e);
                    None
                }
            }
        } else {
            tracing::warn!("Follower mode but ALLSOURCE_LEADER_URL not set — replication disabled");
            None
        }
    } else {
        None
    };
    #[cfg(not(feature = "replication"))]
    let wal_receiver: Option<Arc<allsource_core::replication::WalReceiver>> = None;

    let auth_manager = Arc::new({
        let mut mgr = match std::env::var("ALLSOURCE_JWT_SECRET") {
            Ok(secret) if !secret.is_empty() => {
                tracing::info!("Using ALLSOURCE_JWT_SECRET for JWT validation");
                AuthManager::new(&secret)
            }
            _ => {
                tracing::warn!(
                    "ALLSOURCE_JWT_SECRET not set — using random secret (tokens from other services will fail)"
                );
                AuthManager::default()
            }
        };

        // Attach event-sourced auth repository for durable API key storage
        if let Some(ref repos) = system_repos {
            mgr = mgr.with_auth_repository(repos.auth_repository.clone());
        }

        mgr
    });
    let rate_limiter = Arc::new(RateLimiter::new(RateLimitConfig::professional()));

    // Use event-sourced tenant repository when system repositories are available,
    // otherwise fall back to in-memory only (dev/test mode).
    let tenant_repo: Arc<dyn TenantRepository> = if let Some(ref repos) = system_repos {
        repos.tenant_repository.clone()
    } else {
        Arc::new(InMemoryTenantRepository::new())
    };

    // Initialize DI container for paywall domain + system repositories
    let mut builder = ContainerBuilder::new().with_in_memory_repositories();
    if let Some(repos) = system_repos {
        builder = builder.with_system_repositories(repos);
    }
    let service_container = builder.build();

    // Start webhook delivery worker (v0.11 feature)
    {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        store.set_webhook_tx(tx);
        let webhook_registry = store.webhook_registry();
        tokio::spawn(allsource_core::webhook_worker::run_webhook_delivery_worker(
            rx,
            webhook_registry,
        ));
    }

    tracing::info!("✅ Event store initialized");
    tracing::info!("✅ Authentication manager initialized");
    tracing::info!("✅ Tenant repository initialized");
    tracing::info!("✅ Rate limiter initialized (professional tier defaults)");
    if service_container.has_system_repositories() {
        tracing::info!("✅ Service container initialized (event-sourced system repositories)");
    } else {
        tracing::info!("✅ Service container initialized (in-memory repositories)");
    }

    // Register bootstrap API key if configured
    if let Ok(bootstrap_key) = std::env::var("ALLSOURCE_BOOTSTRAP_API_KEY")
        && !bootstrap_key.is_empty()
    {
        let bootstrap_tenant = std::env::var("ALLSOURCE_BOOTSTRAP_TENANT_ID")
            .ok()
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| "default".to_string());
        auth_manager.register_bootstrap_api_key(&bootstrap_key, &bootstrap_tenant);
        tracing::info!(
            "✅ Bootstrap API key configured (tenant: {})",
            bootstrap_tenant
        );
    }

    // Start RESP3 (Redis wire protocol) server if configured
    if let Ok(resp_port_str) = std::env::var("ALLSOURCE_RESP_PORT")
        && let Ok(resp_port) = resp_port_str.parse::<u16>()
    {
        let resp_server = Arc::new(RespServer::new(Arc::clone(&store)));
        tokio::spawn(async move {
            if let Err(e) = resp_server.serve(resp_port).await {
                tracing::error!("RESP3 server error: {}", e);
            }
        });
        tracing::info!("✅ RESP3 server enabled on port {}", resp_port);
    }

    // Initialize cluster manager if cluster mode is enabled
    let cluster_manager = if std::env::var("ALLSOURCE_CLUSTER_ENABLED").is_ok_and(|v| v == "true") {
        let self_node_id: u32 = std::env::var("ALLSOURCE_NODE_ID")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(0);
        let partition_count: u32 = std::env::var("ALLSOURCE_PARTITION_COUNT")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(32);

        let cm = ClusterManager::new(self_node_id, partition_count);

        // Self-register this node
        let api_port: u16 = std::env::var("ALLSOURCE_PORT")
            .or_else(|_| std::env::var("PORT"))
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(3900);
        let host = std::env::var("ALLSOURCE_HOST").unwrap_or_else(|_| "0.0.0.0".to_string());

        let member_role = match role {
            NodeRole::Leader => MemberRole::Leader,
            NodeRole::Follower => MemberRole::Follower,
        };

        let self_member = ClusterMember {
            node_id: self_node_id,
            api_address: format!("{host}:{api_port}"),
            replication_address: format!("{host}:{replication_port}"),
            role: member_role,
            last_wal_offset: 0,
            last_heartbeat_ms: 0,
            healthy: true,
        };

        // Use block_on to run the async add_member from sync context
        tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current().block_on(cm.add_member(self_member));
        });

        tracing::info!(
            "✅ Cluster mode enabled (node_id={}, partitions={})",
            self_node_id,
            partition_count,
        );
        Some(Arc::new(cm))
    } else {
        None
    };

    // Initialize geo-replication if configured
    let geo_replication = GeoReplicationConfig::from_env().map(|config| {
        let peer_count = config.peers.len();
        let region_id = config.region_id.clone();
        let mgr = Arc::new(GeoReplicationManager::new(config));
        tracing::info!(
            "✅ Geo-replication enabled (region='{}', peers={})",
            region_id,
            peer_count,
        );
        mgr
    });

    api_v1::serve_v1(
        store,
        auth_manager,
        tenant_repo,
        rate_limiter,
        service_container,
        &gate,
        role,
        wal_shipper,
        wal_receiver,
        replication_port,
        cluster_manager,
        geo_replication,
    )
    .await?;
    tracing::info!("🚀 AllSource Core ready on {}", addr);
    tracing::info!("📝 API: /health, /api/v1/events, /api/v1/events/query");
    tracing::info!(
        "🔌 WebSocket: ws://{}:{}/api/v1/events/stream",
        server_config.host,
        server_config.port
    );
    tracing::info!("🔒 Features: Auth, Multi-tenancy, Rate Limiting");

    server.await??;
    if let Some(checkpointer) = checkpointer {
        // Handlers have drained, so the next boot's WAL tail is close to empty.
        match tokio::task::spawn_blocking(move || checkpointer.checkpoint()).await {
            Ok(Ok(Some(o))) => tracing::info!("Shutdown system checkpoint at {}", o.covered_seq),
            Ok(Ok(None)) => tracing::info!("Shutdown system checkpoint already current"),
            Ok(Err(e)) => tracing::error!("Shutdown system checkpoint failed: {e}"),
            Err(e) => tracing::error!("Shutdown system checkpoint panicked: {e}"),
        }
    }
    tracing::info!("🛑 AllSource Core shutdown complete");
    Ok(())
}

/// Every 60 s: apply the cache budget, which otherwise runs only when a tenant
/// hydrates, and set the memory gauges. RSS is read once so live and retained
/// bytes come from the same moment.
fn spawn_memory_upkeep(store: Arc<EventStore>, system_store: Option<Arc<SystemMetadataStore>>) {
    store.metrics().ledger_metrics();
    tokio::spawn(async move {
        let mut ticker = tokio::time::interval(std::time::Duration::from_secs(60));
        ticker.tick().await;
        loop {
            ticker.tick().await;
            let store = Arc::clone(&store);
            let system_store = system_store.clone();
            let sampled = tokio::task::spawn_blocking(move || {
                store.enforce_cache_budget_now();
                let (events, bytes) =
                    system_store.map_or((0, 0), |s| (s.resident_events(), s.resident_bytes()));
                let rss = memory::resident_set_bytes();
                let metrics = store.metrics();
                metrics.record_memory(events, bytes, rss);
                let heap_live = heap_live_bytes();
                metrics.record_heap(heap_live, rss, &store.resident_structures());
                metrics.record_ledger(
                    heap_live,
                    allsource_core::infrastructure::memory::ledger::resident(),
                );
            })
            .await;
            if let Err(e) = sampled {
                tracing::warn!("Memory upkeep task panicked: {e}");
            }
        }
    });
}

/// Periodic system checkpoints bound how much of the tenant stream a crash
/// leaves to replay; the verify pass checks the checkpoint this boot used.
fn spawn_system_checkpoints(checkpointer: &Arc<SystemCheckpointer>) {
    let settings = checkpointer.settings();
    if !settings.enabled {
        tracing::warn!("System checkpoints off: every boot replays the whole system WAL");
        return;
    }
    let interval = std::env::var("ALLSOURCE_SYSTEM_CHECKPOINT_INTERVAL_SECONDS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(300);
    if interval > 0 {
        let checkpointer = Arc::clone(checkpointer);
        tokio::spawn(async move {
            let mut ticker = tokio::time::interval(std::time::Duration::from_secs(interval));
            ticker.tick().await;
            loop {
                ticker.tick().await;
                let checkpointer = Arc::clone(&checkpointer);
                match tokio::task::spawn_blocking(move || checkpointer.checkpoint()).await {
                    Ok(Ok(Some(o))) => tracing::info!(
                        "System checkpoint at {} ({} tenant events folded)",
                        o.covered_seq,
                        o.tail_events
                    ),
                    Ok(Ok(None)) => {}
                    Ok(Err(e)) => tracing::error!("System checkpoint failed: {e}"),
                    Err(e) => tracing::error!("System checkpoint panicked: {e}"),
                }
            }
        });
    }
    if settings.verify {
        let checkpointer = Arc::clone(checkpointer);
        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_secs(30)).await;
            match tokio::task::spawn_blocking(move || checkpointer.verify_loaded()).await {
                Ok(Ok(VerifyOutcome::Matches {
                    covered_seq,
                    tenant_events,
                })) => tracing::info!(
                    "System checkpoint {covered_seq} matches a full replay of {tenant_events} \
                     tenant events"
                ),
                Ok(Ok(VerifyOutcome::NoCheckpointLoaded)) => {
                    tracing::info!("System checkpoint verify skipped: this boot replayed the WAL");
                }
                Ok(Ok(VerifyOutcome::Rejected { covered_seq, .. })) => {
                    // The live state was built from the rejected checkpoint;
                    // the restart replays the whole WAL.
                    tracing::error!(
                        "Exiting so the restart rebuilds system state without checkpoint \
                         {covered_seq}"
                    );
                    std::process::exit(70);
                }
                Ok(Err(e)) => tracing::error!("System checkpoint verify failed to run: {e}"),
                Err(e) => tracing::error!("System checkpoint verify panicked: {e}"),
            }
        });
    }
}