use super::*;
use std::time::Duration;
use tempfile::TempDir;
const TENANT: &str = "synthetic-archive-consistency";
#[test]
fn cold_archive_window_reports_version_before_filtering_and_paging() {
let directory = TempDir::new().unwrap();
{
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
for _ in 0..3 {
store.ingest(&event()).unwrap();
}
store.flush_storage().unwrap();
}
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
assert_eq!(store.get_entity_version("synthetic-entity"), 0);
let request = QueryEventsRequest {
as_of_valid: None,
since_valid: None,
until_valid: None,
tenant_id: Some(TENANT.into()),
entity_id: Some("synthetic-entity".into()),
limit: Some(1),
..Default::default()
};
let (events, total) = store
.query_window_from_archive(
&request,
0,
false,
&ReadScope::unrestricted(),
WindowOrder::RecordTime,
)
.unwrap();
assert_eq!(events.len(), 1);
assert_eq!(events[0].version, 1);
assert_eq!(total, 3);
assert_eq!(store.get_entity_version("synthetic-entity"), 3);
assert_eq!(store.total_events(), 0);
assert!(!store.is_tenant_loaded(TENANT));
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
assert_eq!(store.get_entity_version("synthetic-entity"), 0);
let (events, total) = store
.query_window_from_archive(
&QueryEventsRequest {
as_of_valid: None,
since_valid: None,
until_valid: None,
event_type: Some("synthetic.absent".into()),
..request
},
0,
false,
&ReadScope::unrestricted(),
WindowOrder::RecordTime,
)
.unwrap();
assert!(events.is_empty());
assert_eq!(total, 0);
assert_eq!(store.get_entity_version("synthetic-entity"), 3);
}
fn event() -> Event {
Event::from_strings(
"synthetic.updated".into(),
"synthetic-entity".into(),
TENANT.into(),
serde_json::json!({"synthetic": true}),
None,
)
.unwrap()
}
#[test]
fn eviction_cannot_erase_an_unflushed_conditional_predecessor() {
let directory = TempDir::new().unwrap();
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
store
.ingest_with_expected_version(&event(), Some(0))
.unwrap();
store.evict_tenant(TENANT);
assert_eq!(
store.total_events(),
1,
"pending history must remain resident"
);
assert!(
store
.ingest_with_expected_version(&event(), Some(0))
.is_err()
);
assert_eq!(
store
.query(&QueryEventsRequest {
as_of_valid: None,
since_valid: None,
until_valid: None,
tenant_id: Some(TENANT.into()),
..Default::default()
})
.unwrap()
.len(),
1
);
assert_eq!(
store
.ingest_with_expected_version(&event(), Some(1))
.unwrap(),
2
);
store.flush_storage().unwrap();
store.evict_tenant(TENANT);
assert!(!store.is_tenant_loaded(TENANT));
assert_eq!(
store
.ingest_with_expected_version(&event(), Some(2))
.unwrap(),
3
);
}
#[test]
fn in_memory_store_cannot_evict_its_only_history() {
let store = EventStore::new();
store
.ingest_with_expected_version(&event(), Some(0))
.unwrap();
store.evict_tenant(TENANT);
assert_eq!(store.total_events(), 1);
assert_eq!(
store
.ingest_with_expected_version(&event(), Some(1))
.unwrap(),
2
);
}
#[test]
fn replicated_history_reaches_parquet_before_it_can_be_evicted() {
let directory = TempDir::new().unwrap();
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
let mut replicated = event();
replicated.version = 1;
store.ingest_replicated(&replicated).unwrap();
store.evict_tenant(TENANT);
assert_eq!(store.total_events(), 1);
store.flush_storage().unwrap();
store.evict_tenant(TENANT);
assert_eq!(store.total_events(), 0);
let restored = store
.query(&QueryEventsRequest {
as_of_valid: None,
since_valid: None,
until_valid: None,
tenant_id: Some(TENANT.into()),
..Default::default()
})
.unwrap();
assert_eq!(restored.len(), 1);
assert_eq!(restored[0].id, replicated.id);
assert_eq!(restored[0].version, 1);
}
#[test]
fn read_only_replication_never_buffers_archive_writes_or_discards_memory() {
let directory = TempDir::new().unwrap();
let store = EventStore::with_config(EventStoreConfig {
read_only: true,
..EventStoreConfig::with_persistence(directory.path())
});
store.ingest_replicated(&event()).unwrap();
assert!(
!store
.storage
.as_ref()
.unwrap()
.read()
.has_pending_tenant_events(TENANT)
);
store.evict_tenant(TENANT);
assert_eq!(store.total_events(), 1);
}
#[test]
fn eviction_does_not_wait_for_in_flight_storage_work() {
let directory = TempDir::new().unwrap();
let store = Arc::new(EventStore::with_config(EventStoreConfig::with_persistence(
directory.path(),
)));
store
.ingest_with_expected_version(&event(), Some(0))
.unwrap();
store.flush_storage().unwrap();
let storage = store.storage.as_ref().unwrap().read();
let eviction_store = Arc::clone(&store);
let (finished_tx, finished_rx) = std::sync::mpsc::channel();
let eviction = std::thread::spawn(move || {
eviction_store.evict_tenant(TENANT);
finished_tx.send(()).unwrap();
});
let finished_before_release = finished_rx.recv_timeout(Duration::from_secs(1));
drop(storage);
eviction.join().unwrap();
assert!(finished_before_release.is_ok());
assert_eq!(store.total_events(), 1);
store.evict_tenant(TENANT);
assert_eq!(store.total_events(), 0);
assert!(!store.is_tenant_loaded(TENANT));
}
#[test]
fn eviction_does_not_lower_an_entity_version() {
let directory = TempDir::new().unwrap();
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
store
.ingest_with_expected_version(&event(), Some(0))
.unwrap();
store
.ingest_with_expected_version(&event(), Some(1))
.unwrap();
store.flush_storage().unwrap();
assert_eq!(store.get_entity_version("synthetic-entity"), 2);
store.evict_tenant(TENANT);
assert_eq!(
store.total_events(),
0,
"the cache should have been dropped"
);
assert_eq!(
store.get_entity_version("synthetic-entity"),
2,
"eviction lowered a version that is still on disk"
);
assert!(
store
.ingest_with_expected_version(&event(), Some(0))
.is_err(),
"a stale expected_version was accepted after eviction"
);
assert_eq!(
store
.ingest_with_expected_version(&event(), Some(2))
.unwrap(),
3
);
}
#[test]
fn ingest_persists_the_version_it_reports() {
let directory = TempDir::new().unwrap();
{
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
for expected in 1..=3 {
store.ingest(&event()).unwrap();
assert_eq!(store.get_entity_version("synthetic-entity"), expected);
}
let stored = store
.query(&QueryEventsRequest {
as_of_valid: None,
since_valid: None,
until_valid: None,
tenant_id: Some(TENANT.into()),
..Default::default()
})
.unwrap();
assert_eq!(
stored.iter().map(|e| e.version).collect::<Vec<_>>(),
vec![1, 2, 3],
"the reported versions were never written onto the events"
);
store.flush_storage().unwrap();
}
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
assert_eq!(
store
.ingest_with_expected_version(&event(), Some(3))
.unwrap(),
4,
"a restart forgot versions that ingest had already persisted"
);
}
#[test]
fn conditional_write_resolves_version_without_loading_the_tenant() {
let directory = TempDir::new().unwrap();
{
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
store
.ingest_with_expected_version(&event(), Some(0))
.unwrap();
store
.ingest_with_expected_version(&event(), Some(1))
.unwrap();
store.flush_storage().unwrap();
}
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
assert_eq!(store.total_events(), 0);
assert!(
store
.ingest_with_expected_version(&event(), Some(0))
.is_err()
);
assert_eq!(
store
.ingest_with_expected_version(&event(), Some(2))
.unwrap(),
3
);
assert!(
!store.is_tenant_loaded(TENANT),
"resolving a version must not hydrate the tenant"
);
}
#[test]
fn resident_counter_counts_only_the_new_batch() {
let store = EventStore::new();
store.ingest_batch(vec![event(), event(), event()]).unwrap();
store.ingest_batch(vec![event(), event()]).unwrap();
assert_eq!(store.stats().total_ingested, 5);
assert_eq!(store.total_events(), 5);
}
#[test]
fn resident_and_archive_windows_agree_in_record_and_valid_order() {
use chrono::TimeZone;
let valid_on = |day: u32| chrono::Utc.with_ymd_and_hms(2026, 1, day, 0, 0, 0).unwrap();
let fact = |valid_from| {
Event::from_strings(
"synthetic.fact".into(),
"synthetic-fact".into(),
TENANT.into(),
serde_json::json!({}),
None,
)
.unwrap()
.with_valid_time(valid_from, None)
.unwrap()
};
let (a, b, c) = (
fact(Some(valid_on(10))),
fact(Some(valid_on(1))),
fact(None),
);
let (id_a, id_b, id_c) = (a.id(), b.id(), c.id());
let directory = TempDir::new().unwrap();
{
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
for event in [&a, &b, &c] {
store.ingest(event).unwrap();
}
store.flush_storage().unwrap();
}
let request = QueryEventsRequest {
tenant_id: Some(TENANT.into()),
entity_id: Some("synthetic-fact".into()),
..Default::default()
};
let scope = ReadScope::unrestricted();
let cases = [
(WindowOrder::RecordTime, false, vec![id_a, id_b, id_c]),
(WindowOrder::RecordTime, true, vec![id_c, id_b, id_a]),
(WindowOrder::ValidTime, false, vec![id_b, id_a, id_c]),
(WindowOrder::ValidTime, true, vec![id_c, id_a, id_b]),
];
for (order, descending, expected) in cases {
let resident =
EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
let (events, total) = resident
.query_window_scoped_ordered(&request, 0, descending, &scope, order)
.unwrap();
assert_eq!(total, 3);
let ids: Vec<_> = events.iter().map(Event::id).collect();
assert_eq!(ids, expected, "resident {order:?} descending={descending}");
let cold = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
let (events, total) = cold
.query_window_from_archive(&request, 0, descending, &scope, order)
.unwrap();
assert_eq!(total, 3);
let ids: Vec<_> = events.iter().map(Event::id).collect();
assert_eq!(ids, expected, "archive {order:?} descending={descending}");
}
}
#[tokio::test(flavor = "current_thread")]
async fn eviction_between_hydration_and_version_check_cannot_authorize_a_stale_write() {
let directory = TempDir::new().unwrap();
{
let store = EventStore::with_config(EventStoreConfig::with_persistence(directory.path()));
store
.ingest_with_expected_version(&event(), Some(0))
.unwrap();
store.flush_storage().unwrap();
}
let store = Arc::new(EventStore::with_config(EventStoreConfig::with_persistence(
directory.path(),
)));
let gate_store = Arc::clone(&store);
let (held_tx, held_rx) = tokio::sync::oneshot::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let holder = std::thread::spawn(move || {
let _gate = gate_store.durability_gate.write();
held_tx.send(()).unwrap();
release_rx.recv_timeout(Duration::from_secs(3))
});
held_rx.await.unwrap();
let writer_store = Arc::clone(&store);
let writer = tokio::task::spawn_blocking(move || {
writer_store.ingest_with_expected_version(&event(), Some(0))
});
tokio::time::timeout(Duration::from_secs(1), async {
while !store
.version_index_entities
.contains_key("synthetic-entity")
{
tokio::time::sleep(Duration::from_millis(1)).await;
}
})
.await
.unwrap();
let eviction_store = Arc::clone(&store);
let (evicted_tx, mut evicted_rx) = tokio::sync::oneshot::channel();
let eviction = tokio::task::spawn_blocking(move || {
eviction_store.evict_tenant(TENANT);
let _ = evicted_tx.send(());
});
let _ = tokio::time::timeout(Duration::from_millis(100), &mut evicted_rx).await;
release_tx.send(()).unwrap();
let result = writer.await.unwrap();
eviction.await.unwrap();
holder.join().unwrap().unwrap();
assert!(
result.is_err(),
"eviction authorized a stale write: {result:?}"
);
assert_eq!(
store
.query(&QueryEventsRequest {
as_of_valid: None,
since_valid: None,
until_valid: None,
tenant_id: Some(TENANT.into()),
..Default::default()
})
.unwrap()
.len(),
1
);
}