macro_rules! must {
($fixture:ident : $capability:ident) => {
if let Some(reason) = <$fixture as $crate::ProjectionFixture>::$capability.reason() {
panic!(
"this projection fixture declines `{}`, which is a MUST and not \
a trade the suite can record as a skip. Every rule in this \
family reads the read model and the checkpoint back through a \
*fresh* handle, because PS-1's coupling is only observable from \
outside the connection that made the commit: a store whose \
commit is visible to its own session alone satisfies every \
single-handle assertion and loses a half the moment anything \
else looks. A fixture that cannot open a second handle cannot \
observe the invariant this port exists for at all. Hold the \
backing store behind an `Arc` or an `Rc` and return a fresh \
handle from each `connect` — `fixtures::MemoryProjectionFixture` \
is the reference implementation. Reason given: {reason}",
::core::stringify!($capability),
);
}
};
}
macro_rules! require {
($fixture:ident : $capability:ident) => {
if let Some(reason) = <$fixture as $crate::ProjectionFixture>::$capability.reason() {
return $crate::RuleOutcome::Skipped {
capability: ::core::stringify!($capability),
reason,
};
}
};
}
macro_rules! require_read_through {
($fixture:ident) => {
#[rustfmt::skip]
let __reads_through_batch = <<$fixture as $crate::__private::ProjectionFixture>::Store as $crate::__private::ProjectionProbe>::READS_THROUGH_BATCH;
if !__reads_through_batch {
return $crate::RuleOutcome::Skipped {
capability: $crate::NO_BATCH_READ_PATH,
reason: $crate::NO_BATCH_READ_PATH_REASON,
};
}
};
}
pub mod rules {
#![allow(clippy::missing_panics_doc)]
use happenstance_core::{
Authority, Checkpoint, CommitError, ProjectionId, ProjectionProbe, ProjectionStore,
ResetError, SequencePosition,
};
use crate::{ProjectionFixture, RuleOutcome};
const PROBE_KEY: &str = "depot-7";
const PROBE_VALUE: u64 = 12;
const SECOND_KEY: &str = "depot-11";
const SECOND_VALUE: u64 = 37;
const REBUILD_SEQUENCE: [&str; 6] = [
PROBE_KEY, PROBE_KEY, SECOND_KEY, PROBE_KEY, SECOND_KEY, PROBE_KEY,
];
const ANCHOR_KEY: &str = "depot-3";
async fn begin_ok<S: ProjectionStore>(store: &S) -> S::Batch {
match store.begin().await {
Ok(batch) => batch,
Err(err) => panic!("opening a batch should succeed, got {err:?}"),
}
}
async fn probe_write_ok<S: ProjectionProbe>(
store: &S,
batch: &mut S::Batch,
key: &str,
value: u64,
) {
if let Err(err) = store.probe_write(batch, key, value).await {
panic!("writing a probe row into an open batch should succeed, got {err:?}");
}
}
async fn probe_delete_all_ok<S: ProjectionProbe>(store: &S, batch: &mut S::Batch) {
if let Err(err) = store.probe_delete_all(batch).await {
panic!("queuing a delete-all into an open batch should succeed, got {err:?}");
}
}
async fn probe_read_through_ok<S: ProjectionProbe>(
store: &S,
batch: &mut S::Batch,
key: &str,
) -> Option<u64> {
match store.probe_read_through(batch, key).await {
Ok(row) => row,
Err(err) => panic!("reading through an open batch should succeed, got {err:?}"),
}
}
async fn commit_ok<S: ProjectionStore>(
store: &S,
batch: S::Batch,
id: &ProjectionId,
position: SequencePosition,
authority: Authority,
) {
if let Err(err) = store.commit(batch, id, position, authority).await {
panic!("commit should succeed, got {err:?}");
}
}
async fn checkpoint_ok<S: ProjectionStore>(store: &S, id: &ProjectionId) -> Checkpoint {
match store.checkpoint(id).await {
Ok(checkpoint) => checkpoint,
Err(err) => panic!("reading a checkpoint should succeed, got {err:?}"),
}
}
async fn probe_read_ok<S: ProjectionProbe>(store: &S, key: &str) -> Option<u64> {
match store.probe_read(key).await {
Ok(row) => row,
Err(err) => panic!("reading the read model should succeed, got {err:?}"),
}
}
async fn rollback_ok<S: ProjectionStore>(store: &S, batch: S::Batch) {
if let Err(err) = store.rollback(batch).await {
panic!("rolling a batch back should succeed, got {err:?}");
}
}
async fn reset_ok<S: ProjectionStore>(store: &S, batch: S::Batch, id: &ProjectionId) {
if let Err(err) = store.reset(batch, id).await {
panic!("reset should succeed, got {err:?}");
}
}
fn resumes_over(checkpoint: Checkpoint, position: SequencePosition) -> bool {
match checkpoint {
Checkpoint::NeverRun => true,
Checkpoint::Live { through } | Checkpoint::Rebuilding { through } => position > through,
_ => panic!(
"this store reported a checkpoint variant this rule has never \
been taught to resume from: {checkpoint:?}. `Checkpoint` grew a \
variant and PS-20's derivation has not been extended to cover it"
),
}
}
fn after(position: SequencePosition) -> SequencePosition {
match position.next() {
Some(next) => next,
None => panic!(
"this rule needs the position after {position}, and there is \
none: the store is at the top of the key space. That is a real \
answer from `SequencePosition::next`, not a rule failure — but \
no rule in this family can run against a store there"
),
}
}
pub async fn commit_advances_the_checkpoint<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("commit_advances_the_checkpoint");
let position = SequencePosition::FIRST;
let mut batch = begin_ok(&writer).await;
probe_write_ok(&writer, &mut batch, PROBE_KEY, PROBE_VALUE).await;
commit_ok(&writer, batch, &id, position, Authority::Live).await;
let observer = fixture.connect().await;
assert_eq!(
checkpoint_ok(&observer, &id).await,
Checkpoint::Live { through: position },
"a commit reported as successful must move this projection's \
checkpoint to the position it was given, and a fresh handle must \
see it: a `commit` that returns `Ok` and makes nothing durable \
satisfies PS-1's \"or not at all\" arm and is rejected here"
);
RuleOutcome::Ran
}
pub async fn commit_is_atomic_with_the_read_model<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("commit_is_atomic_with_the_read_model");
let mut batch = begin_ok(&writer).await;
probe_write_ok(&writer, &mut batch, PROBE_KEY, PROBE_VALUE).await;
commit_ok(
&writer,
batch,
&id,
SequencePosition::FIRST,
Authority::Live,
)
.await;
let observer = fixture.connect().await;
let row = probe_read_ok(&observer, PROBE_KEY).await;
let checkpoint = checkpoint_ok(&observer, &id).await;
let row_is_durable = row.is_some();
let checkpoint_is_durable = checkpoint != Checkpoint::NeverRun;
assert_eq!(
row_is_durable, checkpoint_is_durable,
"the read-model write and the checkpoint write must become durable \
together or not at all, and a fresh handle saw one without the \
other: row {row:?}, checkpoint {checkpoint:?}. A store that \
commits the checkpoint and discards the write set replays nothing \
and skips everything the discarded batch would have written"
);
RuleOutcome::Ran
}
pub async fn failed_commit_leaves_both_unchanged<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
require!(F: COMMIT_FAULT);
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("failed_commit_leaves_both_unchanged");
let anchored = SequencePosition::FIRST;
let mut anchor = begin_ok(&writer).await;
probe_write_ok(&writer, &mut anchor, ANCHOR_KEY, PROBE_VALUE).await;
commit_ok(&writer, anchor, &id, anchored, Authority::Live).await;
let before = checkpoint_ok(&fixture.connect().await, &id).await;
fixture.arm_commit_fault().await;
let mut faulted = begin_ok(&writer).await;
probe_write_ok(&writer, &mut faulted, PROBE_KEY, SECOND_VALUE).await;
let outcome = writer
.commit(faulted, &id, after(anchored), Authority::Live)
.await;
assert!(
outcome.is_err(),
"a fixture declaring `COMMIT_FAULT` supported MUST arm a fault its \
store cannot absorb, so that the next `commit` answers `Err`. This \
one armed a fault and the commit succeeded, which is what a fixture \
whose `arm_commit_fault` has an empty body does — and it turns this \
rule into a green result about a store nothing has faulted. A store \
that can absorb every fault its fixture is able to arm must DECLINE \
the capability with that as its stated reason. Got {outcome:?}"
);
let observer = fixture.connect().await;
assert_eq!(
probe_read_ok(&observer, PROBE_KEY).await,
None,
"a commit that reported failure must leave the read model as it \
was, and a fresh handle saw a row the failed batch carried. An \
adapter that applies its rows one statement at a time and writes \
the checkpoint last keeps those rows when the checkpoint write \
fails, reports the error honestly, and has silently applied part \
of a batch its caller believes was refused"
);
assert_eq!(
checkpoint_ok(&observer, &id).await,
before,
"a commit that reported failure must leave the checkpoint exactly \
as the last successful commit left it"
);
RuleOutcome::Ran
}
pub async fn rollback_leaves_both_unchanged<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("rollback_leaves_both_unchanged");
let position = SequencePosition::FIRST;
let mut anchor = begin_ok(&writer).await;
probe_write_ok(&writer, &mut anchor, ANCHOR_KEY, PROBE_VALUE).await;
commit_ok(&writer, anchor, &id, position, Authority::Live).await;
let before = checkpoint_ok(&fixture.connect().await, &id).await;
let mut discarded = begin_ok(&writer).await;
probe_write_ok(&writer, &mut discarded, PROBE_KEY, SECOND_VALUE).await;
rollback_ok(&writer, discarded).await;
let observer = fixture.connect().await;
assert_eq!(
probe_read_ok(&observer, PROBE_KEY).await,
None,
"an explicit rollback must leave the read model as it was, and a \
fresh handle can still see a row the rolled-back batch carried. A \
`rollback` that discards its own buffer while the statements it \
already sent stay durable returns `Ok` and loses nothing an adapter \
author would notice"
);
assert_eq!(
checkpoint_ok(&observer, &id).await,
before,
"an explicit rollback must leave the checkpoint exactly as the last \
successful commit left it"
);
RuleOutcome::Ran
}
pub async fn dropped_batch_leaves_store_usable<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("dropped_batch_leaves_store_usable");
let position = SequencePosition::FIRST;
let mut abandoned = begin_ok(&writer).await;
probe_write_ok(&writer, &mut abandoned, PROBE_KEY, PROBE_VALUE).await;
drop(abandoned);
let mut second = begin_ok(&writer).await;
probe_write_ok(&writer, &mut second, SECOND_KEY, SECOND_VALUE).await;
commit_ok(&writer, second, &id, position, Authority::Live).await;
let observer = fixture.connect().await;
assert_eq!(
probe_read_ok(&observer, PROBE_KEY).await,
None,
"dropping a batch without `commit` or `reset` must roll it back, and \
a fresh handle saw a row the dropped batch carried"
);
assert_eq!(
probe_read_ok(&observer, SECOND_KEY).await,
Some(SECOND_VALUE),
"dropping a batch must leave the store **usable**: a second batch \
opened on the same handle committed, and its row is not there. An \
adapter whose `begin` checks out a pooled connection that `Drop` \
returns to nothing answers `Busy` from here on, and a rule asserting \
only that the first write rolled back would certify it"
);
assert_eq!(
checkpoint_ok(&observer, &id).await,
Checkpoint::Live { through: position },
"the second batch's commit must have moved the checkpoint, or the \
store is not usable after a dropped batch"
);
RuleOutcome::Ran
}
pub async fn commit_rejects_a_foreign_batch<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
let first = open().await;
let second = open().await;
let origin = first.connect().await;
let stranger = second.connect().await;
let id = ProjectionId::new("commit_rejects_a_foreign_batch");
let position = SequencePosition::FIRST;
let mut batch = begin_ok(&origin).await;
probe_write_ok(&origin, &mut batch, PROBE_KEY, PROBE_VALUE).await;
match stranger.commit(batch, &id, position, Authority::Live).await {
Err(CommitError::ForeignBatch) => {}
outcome => panic!(
"a batch begun on a different store instance must be rejected as \
`CommitError::ForeignBatch`, and this store accepted it: \
{outcome:?}. The check is one integer comparison on a path that \
is already doing I/O — `begin` stamps an identity minted per \
store instance and `commit` compares it"
),
}
for (store, which) in [
(&origin, "the store the batch was begun on"),
(&stranger, "the store it was offered to"),
] {
assert_eq!(
checkpoint_ok(store, &id).await,
Checkpoint::NeverRun,
"a rejected commit must leave **both** stores unchanged, and \
{which} moved its checkpoint"
);
assert_eq!(
probe_read_ok(store, PROBE_KEY).await,
None,
"a rejected commit must leave **both** stores unchanged, and \
{which} kept a row the rejected batch carried"
);
}
RuleOutcome::Ran
}
pub async fn commit_accepts_a_position_the_batch_did_not_write<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("commit_accepts_a_position_the_batch_did_not_write");
let position = SequencePosition::FIRST;
let considered_nothing = begin_ok(&writer).await;
commit_ok(&writer, considered_nothing, &id, position, Authority::Live).await;
let observer = fixture.connect().await;
assert_eq!(
checkpoint_ok(&observer, &id).await,
Checkpoint::Live { through: position },
"the checkpoint is a high-water mark of *consideration*, not of \
application: a commit MAY name a position no applied write occupies, \
and an adapter MUST NOT validate `position` against what the batch \
wrote. A projection that matches forty events in thirty-seven \
thousand must be able to move past the rest"
);
RuleOutcome::Ran
}
pub async fn commit_rejects_a_regressing_position<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("commit_rejects_a_regressing_position");
let earlier = SequencePosition::FIRST;
let later = after(earlier);
let mut anchor = begin_ok(&writer).await;
probe_write_ok(&writer, &mut anchor, ANCHOR_KEY, PROBE_VALUE).await;
commit_ok(&writer, anchor, &id, later, Authority::Live).await;
let mut regressing = begin_ok(&writer).await;
probe_write_ok(&writer, &mut regressing, PROBE_KEY, SECOND_VALUE).await;
match writer
.commit(regressing, &id, earlier, Authority::Live)
.await
{
Err(CommitError::CheckpointRegression { current, attempted }) => {
assert_eq!(
(current, attempted),
(later, earlier),
"`CheckpointRegression` must carry the checkpoint the store \
already holds and the position it was actually given, so a \
caller can log the gap rather than re-derive it with a \
second round trip"
);
}
outcome => panic!(
"a commit naming a position strictly below the current checkpoint \
must be refused as `CommitError::CheckpointRegression`, and this \
store answered {outcome:?}. An unconditional `UPDATE checkpoint \
SET position = ?` turns a stale runner into a silent \
double-apply"
),
}
let observer = fixture.connect().await;
assert_eq!(
probe_read_ok(&observer, PROBE_KEY).await,
None,
"a refused commit must leave the read model unchanged, and a fresh \
handle saw a row the refused batch carried"
);
assert_eq!(
checkpoint_ok(&observer, &id).await,
Checkpoint::Live { through: later },
"a refused commit must leave the checkpoint unchanged"
);
RuleOutcome::Ran
}
pub async fn distinct_projections_advance_independently<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let slower = ProjectionId::new("distinct_projections_advance_independently.slower");
let faster = ProjectionId::new("distinct_projections_advance_independently.faster");
let earlier = SequencePosition::FIRST;
let later = after(earlier);
let mut first = begin_ok(&writer).await;
probe_write_ok(&writer, &mut first, PROBE_KEY, PROBE_VALUE).await;
commit_ok(&writer, first, &slower, earlier, Authority::Live).await;
let mut second = begin_ok(&writer).await;
probe_write_ok(&writer, &mut second, SECOND_KEY, SECOND_VALUE).await;
commit_ok(&writer, second, &faster, later, Authority::Live).await;
let observer = fixture.connect().await;
assert_eq!(
checkpoint_ok(&observer, &slower).await,
Checkpoint::Live { through: earlier },
"one commit advances exactly one projection, and committing the \
second one moved the first one's checkpoint. A single-row checkpoint \
table does this silently, and the projection that lost the race \
skips every event between the two positions forever"
);
assert_eq!(
checkpoint_ok(&observer, &faster).await,
Checkpoint::Live { through: later },
"each projection must read back its own checkpoint"
);
assert_eq!(
probe_read_ok(&observer, PROBE_KEY).await,
Some(PROBE_VALUE),
"neither projection's commit may disturb the other's rows, and the \
row the first commit wrote is not readable"
);
assert_eq!(
probe_read_ok(&observer, SECOND_KEY).await,
Some(SECOND_VALUE),
"neither projection's commit may disturb the other's rows, and the \
row the second commit wrote is not readable"
);
RuleOutcome::Ran
}
pub async fn reset_clears_rows_and_checkpoint_together<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("reset_clears_rows_and_checkpoint_together");
let position = SequencePosition::FIRST;
let mut batch = begin_ok(&writer).await;
probe_write_ok(&writer, &mut batch, PROBE_KEY, PROBE_VALUE).await;
probe_write_ok(&writer, &mut batch, SECOND_KEY, SECOND_VALUE).await;
commit_ok(&writer, batch, &id, position, Authority::Live).await;
let before = fixture.connect().await;
let rows_before = (
probe_read_ok(&before, PROBE_KEY).await,
probe_read_ok(&before, SECOND_KEY).await,
);
let checkpoint_before = checkpoint_ok(&before, &id).await;
let stranger_fixture = open().await;
let stranger = stranger_fixture.connect().await;
let mut foreign = begin_ok(&stranger).await;
probe_delete_all_ok(&stranger, &mut foreign).await;
match writer.reset(foreign, &id).await {
Err(ResetError::ForeignBatch) => {}
outcome => panic!(
"a `reset` handed a batch begun on a different store instance \
must be refused as `ResetError::ForeignBatch`, and this store \
answered {outcome:?}. The refusal is what makes PS-16's \
failure-injecting half reachable without a fixture that can arm \
a fault"
),
}
let after_failure = fixture.connect().await;
assert_eq!(
(
probe_read_ok(&after_failure, PROBE_KEY).await,
probe_read_ok(&after_failure, SECOND_KEY).await,
),
rows_before,
"a `reset` that reported failure must leave the read model exactly \
as it was, and a fresh handle saw it change. The deletes the \
refused batch carried are the caller's, and a store that applied \
them anyway has cleared a read model whose caller was told the \
operation failed"
);
assert_eq!(
checkpoint_ok(&after_failure, &id).await,
checkpoint_before,
"a `reset` that reported failure must leave the checkpoint exactly \
as the last successful commit left it"
);
let mut clearing = begin_ok(&writer).await;
probe_delete_all_ok(&writer, &mut clearing).await;
reset_ok(&writer, clearing, &id).await;
let observer = fixture.connect().await;
assert_eq!(
(
probe_read_ok(&observer, PROBE_KEY).await,
probe_read_ok(&observer, SECOND_KEY).await,
),
(None, None),
"a successful `reset` must apply the caller's deletes, and a fresh \
handle can still read a row the reset batch asked to remove"
);
assert_eq!(
checkpoint_ok(&observer, &id).await,
Checkpoint::NeverRun,
"a successful `reset` must return this projection's checkpoint to \
`NeverRun` in the **same** unit of work as the deletes it applied, \
and the rows went while the checkpoint stayed. That is the runbook \
procedure — two statements on two connections — and a runner that \
restarts between them reads the old checkpoint, resumes past it, \
and applies the rest of the log into an empty table while reporting \
healthy"
);
RuleOutcome::Ran
}
pub async fn reset_is_scoped_to_one_projection<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let van_stock = ProjectionId::new("reset_is_scoped_to_one_projection.van_stock");
let fgas_ledger = ProjectionId::new("reset_is_scoped_to_one_projection.fgas_ledger");
let rebuilt_through = SequencePosition::FIRST;
let protected_through = after(rebuilt_through);
let mut rebuildable = begin_ok(&writer).await;
probe_write_ok(&writer, &mut rebuildable, PROBE_KEY, PROBE_VALUE).await;
commit_ok(
&writer,
rebuildable,
&van_stock,
rebuilt_through,
Authority::Live,
)
.await;
let mut protected = begin_ok(&writer).await;
probe_write_ok(&writer, &mut protected, SECOND_KEY, SECOND_VALUE).await;
commit_ok(
&writer,
protected,
&fgas_ledger,
protected_through,
Authority::Live,
)
.await;
let before = fixture.connect().await;
let protected_row_before = probe_read_ok(&before, SECOND_KEY).await;
let protected_checkpoint_before = checkpoint_ok(&before, &fgas_ledger).await;
reset_ok(&writer, begin_ok(&writer).await, &van_stock).await;
let observer = fixture.connect().await;
assert_eq!(
checkpoint_ok(&observer, &fgas_ledger).await,
protected_checkpoint_before,
"a `reset` must be scoped to one `(store, ProjectionId)` pair, and \
resetting one projection moved another one's checkpoint. A `reset` \
that truncates the checkpoint table is one statement and it returns \
every projection in the store to `NeverRun` — including the \
append-only ledger that must never be rebuilt, which is then \
rebuilt from an event log that no longer holds the events it was \
built from"
);
assert_eq!(
probe_read_ok(&observer, SECOND_KEY).await,
protected_row_before,
"a `reset` must be scoped to one `(store, ProjectionId)` pair, and \
resetting one projection removed another one's rows — which this \
reset's batch did not ask for, because it carried no deletes at all"
);
assert_eq!(
checkpoint_ok(&observer, &van_stock).await,
Checkpoint::NeverRun,
"the reset projection's own checkpoint must have returned to \
`NeverRun`, or this rule is asserting scoping about an operation \
that did nothing"
);
RuleOutcome::Ran
}
pub async fn refused_reset_changes_nothing<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
require!(F: RESET_REFUSAL);
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("refused_reset_changes_nothing");
let position = SequencePosition::FIRST;
let mut batch = begin_ok(&writer).await;
probe_write_ok(&writer, &mut batch, PROBE_KEY, PROBE_VALUE).await;
commit_ok(&writer, batch, &id, position, Authority::Live).await;
fixture.protect_from_reset(&id).await;
let before = fixture.connect().await;
let row_before = probe_read_ok(&before, PROBE_KEY).await;
let checkpoint_before = checkpoint_ok(&before, &id).await;
let mut clearing = begin_ok(&writer).await;
probe_delete_all_ok(&writer, &mut clearing).await;
match writer.reset(clearing, &id).await {
Err(ResetError::Refused) => {}
outcome => panic!(
"this fixture declares `RESET_REFUSAL` supported and asked its \
store to protect this projection, so `reset` must answer \
`Err(ResetError::Refused)` — and it answered {outcome:?}. A \
refusal reported as success is the operator's runbook \
succeeding against the one projection the domain protects"
),
}
let observer = fixture.connect().await;
assert_eq!(
probe_read_ok(&observer, PROBE_KEY).await,
row_before,
"a refused `reset` must leave the read model exactly as it was, and \
a fresh handle saw it change. A store that issues its deletes and \
checks its protection policy afterwards reports the refusal \
perfectly honestly over a read model that is already gone, and \
every rule asserting only the error variant certifies it"
);
assert_eq!(
checkpoint_ok(&observer, &id).await,
checkpoint_before,
"a refused `reset` must leave the checkpoint exactly as it was: a \
refusal is not success, and a projection whose rows survived while \
its checkpoint went to `NeverRun` is rebuilt from the top over rows \
that are still there"
);
RuleOutcome::Ran
}
pub async fn fresh_projection_has_no_checkpoint<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
let fixture = open().await;
let store = fixture.connect().await;
let unseen = ProjectionId::new("fresh_projection_has_no_checkpoint.never-committed-to");
assert_eq!(
checkpoint_ok(&store, &unseen).await,
Checkpoint::NeverRun,
"a projection this store has never seen must read back as \
`Checkpoint::NeverRun`. A store that resolves a missing checkpoint \
row to `Live` has told a runner that a read model nobody has ever \
built is authoritative and already considered through a position — \
so the runner resumes past the events it has never applied, and \
they are skipped permanently and silently"
);
RuleOutcome::Ran
}
pub async fn reset_is_not_commit_at_first<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let rebuilt = ProjectionId::new("reset_is_not_commit_at_first.reset");
let substituted = ProjectionId::new("reset_is_not_commit_at_first.commit_at_first");
let first = SequencePosition::FIRST;
let mut applied = begin_ok(&writer).await;
probe_write_ok(&writer, &mut applied, PROBE_KEY, PROBE_VALUE).await;
commit_ok(&writer, applied, &rebuilt, first, Authority::Live).await;
let mut clearing = begin_ok(&writer).await;
probe_delete_all_ok(&writer, &mut clearing).await;
reset_ok(&writer, clearing, &rebuilt).await;
let after_reset = checkpoint_ok(&fixture.connect().await, &rebuilt).await;
commit_ok(
&writer,
begin_ok(&writer).await,
&substituted,
first,
Authority::Live,
)
.await;
let after_substitute = checkpoint_ok(&fixture.connect().await, &substituted).await;
assert_ne!(
core::mem::discriminant(&after_reset),
core::mem::discriminant(&after_substitute),
"a projection that was `reset` and one that was committed at the \
first position must be **distinguishable by variant**, and this \
store reported {after_reset:?} for the reset one and \
{after_substitute:?} for the substitute. Collapsing the two is the \
defect this rule exists for: `commit(empty, id, FIRST)` reads back \
as a position, so a runner resumes after it"
);
assert!(
resumes_over(after_reset, first),
"a runner resuming from {after_reset:?} must start at the store's \
first position **inclusive**, so the event at {first} is applied \
after a reset. A reset that leaves any position behind makes the \
rebuild it exists for start one event late"
);
assert!(
!resumes_over(after_substitute, first),
"a runner resuming from {after_substitute:?} resumes **strictly \
after** the recorded position, so the event at {first} is not \
applied — which is exactly why `commit(empty, id, FIRST)` is not a \
reset. This store answered {after_substitute:?} and a replay would \
still apply event 1, so the two states are the same state and the \
rule above only appeared to hold"
);
RuleOutcome::Ran
}
pub async fn batch_reads_reflect_pending_writes<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
require_read_through!(F);
let fixture = open().await;
let writer = fixture.connect().await;
let mut batch = begin_ok(&writer).await;
probe_write_ok(&writer, &mut batch, PROBE_KEY, PROBE_VALUE).await;
assert_eq!(
probe_read_through_ok(&writer, &mut batch, PROBE_KEY).await,
Some(PROBE_VALUE),
"a store declaring `READS_THROUGH_BATCH` must let an open batch see \
its own pending writes, and this one answered from committed state. \
A projection doing `get` then `set` inside one batch then reads the \
value from *before* the batch began, and every increment after the \
first is lost — with no error, and least visibly when the chunk is \
largest"
);
RuleOutcome::Ran
}
pub async fn rebuild_is_chunk_size_invariant<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
require_read_through!(F);
let mut runs = Vec::new();
for chunk in [1_usize, 3, REBUILD_SEQUENCE.len()] {
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("rebuild_is_chunk_size_invariant");
let mut position = SequencePosition::FIRST;
for slice in REBUILD_SEQUENCE.chunks(chunk) {
let mut batch = begin_ok(&writer).await;
for key in slice {
let seen = probe_read_through_ok(&writer, &mut batch, key)
.await
.unwrap_or(0);
probe_write_ok(&writer, &mut batch, key, seen + 1).await;
}
commit_ok(&writer, batch, &id, position, Authority::Rebuilding).await;
position = after(after(position));
}
runs.push((
chunk,
probe_read_ok(&writer, PROBE_KEY).await,
probe_read_ok(&writer, SECOND_KEY).await,
));
}
let (baseline_chunk, baseline_first, baseline_second) = runs[0];
for &(chunk, first, second) in &runs[1..] {
assert_eq!(
(first, second),
(baseline_first, baseline_second),
"a rebuild must produce the same read model however it is \
chunked, and replaying the same sequence at chunk size {chunk} \
produced a different read model from chunk size \
{baseline_chunk}. Every step of that sequence reads its key \
through the open batch and writes one more than it saw, so a \
store whose batch reads answer from committed state — or whose \
batch keeps the first staged value for a key rather than the \
last — loses every write after the first *within* a chunk, and \
the operator's memory budget silently becomes a correctness \
variable"
);
}
RuleOutcome::Ran
}
pub async fn rebuilding_is_distinguishable_from_live<F: ProjectionFixture>(
open: impl AsyncFn() -> F,
) -> RuleOutcome {
must!(F: SECOND_HANDLE);
let fixture = open().await;
let writer = fixture.connect().await;
let id = ProjectionId::new("rebuilding_is_distinguishable_from_live");
let mut clearing = begin_ok(&writer).await;
probe_delete_all_ok(&writer, &mut clearing).await;
reset_ok(&writer, clearing, &id).await;
let first_chunk = SequencePosition::FIRST;
let second_chunk = after(first_chunk);
let caught_up = after(second_chunk);
for (position, key, value) in [
(first_chunk, PROBE_KEY, PROBE_VALUE),
(second_chunk, SECOND_KEY, SECOND_VALUE),
] {
let mut batch = begin_ok(&writer).await;
probe_write_ok(&writer, &mut batch, key, value).await;
commit_ok(&writer, batch, &id, position, Authority::Rebuilding).await;
let observer = fixture.connect().await;
let checkpoint = checkpoint_ok(&observer, &id).await;
assert!(
matches!(checkpoint, Checkpoint::Rebuilding { .. }),
"a commit claiming `Authority::Rebuilding` must leave a \
checkpoint a reader can recognise as a rebuild in flight, and \
this store reported {checkpoint:?}. A store that rebuilds in \
place behind a single position field says `Live` over a \
half-built read model, and every reader that asked whether the \
rows were authoritative was told yes"
);
}
let mut caught_up_batch = begin_ok(&writer).await;
probe_write_ok(&writer, &mut caught_up_batch, ANCHOR_KEY, PROBE_VALUE).await;
commit_ok(&writer, caught_up_batch, &id, caught_up, Authority::Live).await;
let observer = fixture.connect().await;
let checkpoint = checkpoint_ok(&observer, &id).await;
assert!(
matches!(checkpoint, Checkpoint::Live { .. }),
"the commit that finishes a rebuild claims `Authority::Live`, and \
the checkpoint must then say the rows are authoritative — this \
store reported {checkpoint:?}. A store that cannot leave the \
rebuilding state leaves every reader treating a finished read model \
as untrustworthy for ever"
);
RuleOutcome::Ran
}
}
#[macro_export]
macro_rules! for_each_projection_store_rule {
($($callback:tt)+) => {
$($callback)+! {
commit_advances_the_checkpoint,
commit_is_atomic_with_the_read_model,
failed_commit_leaves_both_unchanged,
rollback_leaves_both_unchanged,
dropped_batch_leaves_store_usable,
commit_rejects_a_foreign_batch,
commit_accepts_a_position_the_batch_did_not_write,
commit_rejects_a_regressing_position,
distinct_projections_advance_independently,
reset_clears_rows_and_checkpoint_together,
reset_is_scoped_to_one_projection,
refused_reset_changes_nothing,
fresh_projection_has_no_checkpoint,
reset_is_not_commit_at_first,
batch_reads_reflect_pending_writes,
rebuild_is_chunk_size_invariant,
rebuilding_is_distinguishable_from_live,
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __emit_projection_tokio {
($($name:ident),* $(,)?) => {
$(
#[tokio::test]
async fn $name() {
$crate::__private::projection_rules::$name(__conformance_fixture)
.await
.report(::core::stringify!($name));
}
)*
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __emit_projection_blocking {
($($name:ident),* $(,)?) => {
$(
#[test]
fn $name() {
$crate::__private::block_on($crate::__private::projection_rules::$name(__conformance_fixture))
.report(::core::stringify!($name));
}
)*
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __emit_projection_wasm {
($($name:ident),* $(,)?) => {
$(
#[::wasm_bindgen_test::wasm_bindgen_test]
async fn $name() {
let __outcome = $crate::__private::projection_rules::$name(__conformance_fixture).await;
if let Some(__line) = __outcome.skip_line(::core::stringify!($name)) {
::wasm_bindgen_test::console_log!("{}", __line);
}
}
)*
};
}
#[cfg(test)]
fn declared_projection_rules() -> Vec<&'static str> {
const SOURCE: &str = include_str!("projection.rs");
const PREFIX: &str = " pub async fn ";
SOURCE
.lines()
.filter_map(|line| line.strip_prefix(PREFIX))
.map(|rest| {
rest.split(|c: char| !c.is_alphanumeric() && c != '_')
.next()
.unwrap_or("")
})
.collect()
}
#[cfg(test)]
#[test]
fn no_orphan_projection_rules() {
let registered = crate::for_each_projection_store_rule!(crate::__emit_rule_names);
let declared = declared_projection_rules();
let orphans: Vec<_> = declared
.iter()
.filter(|name| !registered.contains(*name))
.collect();
assert!(
orphans.is_empty(),
"these rules exist in `projection::rules` but are absent from \
`for_each_projection_store_rule!`, so no harness runs them: {orphans:?}"
);
let missing: Vec<_> = registered
.iter()
.filter(|name| !declared.contains(*name))
.collect();
assert!(
missing.is_empty(),
"these rules are registered but were not found in `projection.rs` — \
either they moved, or the source scan no longer matches the way they \
are written: {missing:?}"
);
}
#[cfg(test)]
#[test]
fn a_declined_reset_refusal_is_reported_with_the_fixtures_reason() {
use crate::fixtures::MemoryProjectionFixture;
use crate::{ProjectionFixture, RuleOutcome};
let stated = <MemoryProjectionFixture as ProjectionFixture>::RESET_REFUSAL
.reason()
.expect("the reference projection fixture declines `RESET_REFUSAL`");
let outcome = crate::block_on(rules::refused_reset_changes_nothing(async || {
MemoryProjectionFixture::new()
}));
assert_eq!(
outcome,
RuleOutcome::Skipped {
capability: "RESET_REFUSAL",
reason: stated,
},
"a fixture whose store holds no protection policy must get \
`refused_reset_changes_nothing` as a skip naming the associated const \
it can change and carrying its own stated reason — never a silent pass, \
and never a rule `#[cfg]`-ed out of the binary"
);
}
#[cfg(test)]
#[test]
fn two_opens_make_two_isolated_stores() {
use happenstance_core::{
Authority, Checkpoint, ProjectionId, ProjectionStore, SequencePosition,
};
use crate::ProjectionFixture;
use crate::fixtures::MemoryProjectionFixture;
crate::block_on(async {
let open = async || MemoryProjectionFixture::new();
let first = open().await;
let second = open().await;
let writer = first.connect().await;
let observer = second.connect().await;
let id = ProjectionId::new("two_opens_make_two_isolated_stores");
let position = SequencePosition::FIRST;
let mut batch = writer
.begin()
.await
.expect("opening a batch on the first fixture's store should succeed");
happenstance_core::ProjectionProbe::probe_write(&writer, &mut batch, "depot-7", 12)
.await
.expect("writing a probe row into the batch should succeed");
writer
.commit(batch, &id, position, Authority::Live)
.await
.expect("committing to the first fixture's store should succeed");
assert_eq!(
writer
.checkpoint(&id)
.await
.expect("reading the first store's checkpoint should succeed"),
Checkpoint::Live { through: position },
"the commit must actually have landed in the first fixture's store"
);
assert_eq!(
observer
.checkpoint(&id)
.await
.expect("reading the second store's checkpoint should succeed"),
Checkpoint::NeverRun,
"two fixture instances must share no backing store, but the second \
saw a checkpoint committed through the first"
);
assert_eq!(
happenstance_core::ProjectionProbe::probe_read(&observer, "depot-7")
.await
.expect("reading the second store's read model should succeed"),
None,
"two fixture instances must share no backing store, but the second \
saw a row written through the first"
);
});
}