We are building a change data testing harness. This typically involves:
- Contracts: Define the expected behavior (e.g., state transitions, invariants) that must hold before and after a change.
- Invariants: Conditions that must always be true (e.g., total supply equals sum of balances, no duplicate IDs, etc.)
- Replays: The ability to replay a sequence of operations to verify that the system behaves consistently, especially after a change.
We'll design a generic harness that can be used for testing stateful systems (like a blockchain or a database) by:
- Defining a set of operations (transactions) that can be applied to the system.
- Defining a set of invariants that must hold after each operation.
- Having the ability to take a snapshot of the state and then replay operations from that snapshot.
We'll structure the code as follows:
-
Contract: An abstract base class for a specific system's contract. It should define:
initial_state: method to create the initial state.
apply(operation, state): apply an operation to a state and return the new state (or modify in place and return).
check_invariants(state): check all invariants for the given state, return a list of violations (empty if all hold).
-
Invariant: A condition that can be checked on a state. We can represent invariants as functions that take a state and return a boolean or a list of violations.
-
Harness: The main testing harness that:
- Can run a sequence of operations from an initial state and check invariants after each.
- Can take a snapshot of the state and then replay a sequence of operations from that snapshot.
- Can compare the state after replaying with a saved state (from the original run) to ensure consistency.
We'll assume that the state is a dictionary or an object that can be serialized (for snapshots). For simplicity, we'll use deep copies.
Steps for the harness:
a. Start with initial state.
b. For each operation in a list:
apply the operation to the current state.
check invariants on the new state.
if invariants fail, record the failure and stop (or continue, depending on configuration).
c. Optionally, at each step (or at selected steps) take a snapshot (deep copy of the state).
d. To replay: start from a snapshot and apply the same (or a different) sequence of operations and check invariants again.
We'll also allow for the possibility of having multiple invariants and reporting all violations.
Let's code accordingly.
Note: We are not building a specific system, but a framework. The user will define the contract (with initial state, apply, and invariants) and the operations.
Let's define:
class Contract(ABC):
@abstractmethod
def initial_state(self):
pass
@abstractmethod
def apply(self, operation, state):
pass
@abstractmethod
def invariants(self):
# returns a list of invariant functions (each function takes state and returns a list of violations)
pass
Then, the harness:
class Harness:
def init(self, contract):
self.contract = contract
def run(self, operations, check_invariants=True, snapshot_steps=[]):
# snapshot_steps: list of step indices (0-indexed) at which to take a snapshot (after applying the operation at that step)
state = self.contract.initial_state()
snapshots = {}
results = [] # list of (step, operation, state, violations) for each step
for i, op in enumerate(operations):
state = self.contract.apply(op, state)
violations = []
if check_invariants:
for inv in self.contract.invariants():
violations.extend(inv(state))
results.append((i, op, state, violations))
if i in snapshot_steps:
snapshots[i] = copy.deepcopy(state)
return state, snapshots, results
def replay(self, snapshot, operations, check_invariants=True):
# snapshot: a state (from a previous run) to start from
state = copy.deepcopy(snapshot) # we don't want to modify the original snapshot
results = []
for i, op in enumerate(operations):
state = self.contract.apply(op, state)
violations = []
if check_invariants:
for inv in self.contract.invariants():
violations.extend(inv(state))
results.append((i, op, state, violations))
return state, results
def compare_states(self, state1, state2):
# Compare two states (deep equality). This might be overridden for custom comparison.
return state1 == state2 # note: if state is a complex structure, we might need a custom comparer.
However, note: the state might be a complex object that doesn't support == by default. We can use deep_eq from testfixtures or write our own.
Alternatively, we can require that the contract provides a way to compare states? Or we can rely on the user to provide a comparator?
Since we are taking snapshots by deepcopy, we are assuming that the state is picklable or at least deepcopy-able.
But for comparison, we might need to compare in a way that is meaningful for the specific state.
Let's change the compare_states to be a method that can be overridden, and by default use == but if the user wants they can override.
Alternatively, we can have:
class Harness:
def init(self, contract, state_comparator=None):
self.contract = contract
self.state_comparator = state_comparator or (lambda x, y: x == y)
Then in run and replay we don't use the comparator, but when we want to compare two states (like in a test that checks replay consistency) we use the comparator.
Actually, the harness doesn't inherently compare two runs. The user would do:
state1, snapshots1, results1 = harness.run(ops1)
take a snapshot at step 5
snapshot = snapshots1[5]
state2, results2 = harness.replay(snapshot, ops1[5:]) # replay from step 5 to the end
Now compare state2 with the state from the original run at the end?
But note: the original run might have more operations? Actually, we replayed the same remaining operations.
We can also compare the entire sequence of states? Or just the final state?
The user might want to check that the state after replaying from a snapshot matches the state from the original run at the same step.
We can provide a method:
def check_replay_consistency(self, original_results, replay_results, start_step):
# original_results: the results from the original run (list of (step, op, state, violations))
# replay_results: the results from the replay (starting at start_step, so the replay_results[0] corresponds to step start_step in the original? Not exactly)
# We need to align the steps. Let's assume we replayed the same operations that were in the original from start_step to the end.
# Then, for each step in the original from start_step to end, we compare the state in the original and the state in the replay.
# But note: the replay_results are indexed from 0 for the first replayed operation (which is original step start_step).
for i in range(len(replay_results)):
orig_step = start_step + i
orig_state = original_results[orig_step][2] # state at that step in the original
replay_state = replay_results[i][2]
if not self.state_comparator(orig_state, replay_state):
return False, (orig_step, orig_state, replay_state)
return True, None
However, note: the original_results might have violations at each step, but the replay might have different violations? We are only comparing states.
Alternatively, we might want to compare the entire results (including violations) but that might be too strict? The violations might be expected to be the same.
But the point of replay is to ensure that the same operations lead to the same state (and same invariants) from the same starting point.
So we can compare both states and violations? Actually, the violations are derived from the state, so if the states are the same then the violations should be too? Not necessarily if the invariants are stateful? But invariants are pure functions of the state.
So if the states are equal, then the violations should be equal. So we can just compare states.
However, note: the state might be a mutable object and we are comparing by value? We are using the state_comparator.
Let's design:
The user uses the harness to run a sequence of operations, then picks a snapshot at a step, and then replays from that snapshot with the same operations (or a subset) and then compares the state at each step (or the final state) with the original run.
We can provide:
def run_and_replay_check(self, operations, snapshot_step, replay_operations=None):
# If replay_operations is None, then we replay the same operations from snapshot_step to the end.
# Otherwise, we replay the given operations (which should be a subset of the original? or any operations?).
# Step 1: run the original
state, snapshots, results = self.run(operations)
snapshot = snapshots.get(snapshot_step)
if snapshot is None:
raise ValueError(f"No snapshot taken at step {snapshot_step}")
# Step 2: replay
if replay_operations is None:
replay_ops = operations[snapshot_step:]
else:
replay_ops = replay_operations
replay_state, replay_results = self.replay(snapshot, replay_ops)
# Step 3: compare the states at each step of the replay with the corresponding step in the original.
# Note: the replay_results[0] corresponds to step snapshot_step in the original? Actually, the original results for step snapshot_step is the state after applying the operation at snapshot_step. But the snapshot was taken after that operation? Wait:
In the `run` method, we take the snapshot at step `i` after applying the operation at step `i`. So the snapshot at step `i` is the state after operation `i`.
Then, when we replay, we start from that snapshot and apply the next operation (which is operation at step `i+1` in the original). So the first replayed operation (index 0 in replay_ops) corresponds to step `i+1` in the original.
But note: the original results for step `i` is the state after operation `i` (which is the snapshot). Then step `i+1` in the original is after operation `i+1`.
In the replay, we start from the snapshot (state after operation `i`) and then apply the first operation in replay_ops (which is operation `i+1`). So the state after the first replayed operation should equal the original state after step `i+1`.
Therefore, we compare:
original_results[snapshot_step + j][2] (state after step snapshot_step+j)
with
replay_results[j][2] (state after j-th replayed operation)
for j from 0 to len(replay_ops)-1.
But note: the original_results has an entry for every step from 0 to len(operations)-1.
So:
for j in range(len(replay_ops)):
orig_step = snapshot_step + j
if orig_step >= len(original_results):
# We are trying to replay beyond the original? That's okay if we are checking a subset? But then we don't have original state to compare.
break
orig_state = original_results[orig_step][2]
replay_state = replay_results[j][2]
if not self.state_comparator(orig_state, replay_state):
return False, (orig_step, orig_state, replay_state)
return True, None
However, note: the replay might be with a different set of operations? Then we are comparing states that might not correspond to the same operations? So the user must be cautious.
Alternatively, we can just compare the final state of the replay with the final state of the original? But that might not catch intermediate inconsistencies.
Let's stick to comparing step by step for the length of the replay.
But what if the replay_operations are not the same as the original from snapshot_step? Then we are comparing apples to oranges? The user should use the same operations for replay to check consistency.
So we assume that the replay operations are the same as the original from the snapshot_step onward.
We can also check that the operations are the same? But that might be too restrictive? The point of replay is to check that the same starting state and same operations lead to the same state. So we should require that the operations are the same.
But in the method above, we don't check the operations. We only check the states.
We can also check that the operations are the same? But then if the user wants to replay with a different set, they are on their own.
Let's not check the operations. We just compare states.
Alternatively, we can have two modes: one that assumes the same operations and one that doesn't? But then the state comparison might not make sense.
I think the intended use is to replay the same operations. So we can document that.
Let's change the method to:
def run_and_replay_check(self, operations, snapshot_step, replay_operations=None):
if replay_operations is None:
replay_operations = operations[snapshot_step:]
# Then we run the original and replay and compare step by step.
But note: the replay_operations might be longer than the remaining operations in the original? Then we don't have original states to compare for the extra steps.
We can break when we run out of original states.
Alternatively, we can require that the replay_operations are exactly the remaining operations? We can check:
if replay_operations != operations[snapshot_step:]:
raise ValueError("Replay operations must be the same as the original operations from the snapshot step onward.")
But maybe the user wants to test that even if the operations are the same, the state should be the same? So we can enforce that.
Let's enforce that the replay_operations are the same as the original from snapshot_step.
However, note: the original run method runs from step0 to the end. We take a snapshot at step snapshot_step (after operation at that step). Then we replay from that snapshot with the operations from snapshot_step+1 to the end? Wait:
In the original run, the state at step snapshot_step is after applying operation snapshot_step. Then the next operation is snapshot_step+1.
So to replay from the snapshot (which is after step snapshot_step), we need to apply operations starting at snapshot_step+1.
But note: the run method records the state after each operation. So the state at step snapshot_step is the state after operation snapshot_step.
Therefore, the replay should start with the operation at index snapshot_step+1? Actually, the snapshot was taken at step snapshot_step (after that operation). So the next operation is at index snapshot_step+1 in the original list.
So the replay_operations should be operations[snapshot_step+1:]?
But wait: in the run method, we take the snapshot at step i (which is after applying operation i). Then we have:
step0: apply op0 -> state0 (after op0) -> snapshot if step0 in snapshot_steps?
step1: apply op1 -> state1 (after op1) -> ...
So if we take a snapshot at step i, that state is after operation i.
Then to replay from that snapshot, we should apply the operations starting at i+1? But note: the original run at step i is the state after op i. Then at step i+1 we apply op i+1 and get state after op i+1.
So if we start from the snapshot (state after op i) and apply op i+1, we should get the same state as the original at step i+1.
Therefore, the replay_operations should be operations[i+1:]? But wait: the snapshot_steps are taken at step i (after op i). So the next operation to apply is i+1.
However, the user might have taken a snapshot at step i and then wants to replay from that snapshot with the operations that were originally applied from step i onward? That would be operations[i:]? But then the first replayed operation would be op i, but we already applied op i to get the snapshot? That would be applying op i twice.
So we must be careful.
Let me clarify:
In the original run:
state0 = initial
for i, op in enumerate(ops):
state = apply(op, state)
if i in snapshot_steps:
snapshot[i] = copy(state)
So snapshot[i] is the state after applying op[i].
Then, to replay from snapshot[i], we want to start from that state and apply the remaining operations: from i+1 to the end.
Therefore, the replay_operations should be ops[i+1:].
But note: the method run_and_replay_check takes snapshot_step and then by default uses operations[snapshot_step+1:] for replay.
However, what if the user wants to replay a different set of operations? They can pass replay_operations but then they must ensure that the operations are the ones that should be applied after the snapshot.
Alternatively, we can change the design: when taking a snapshot, we also record the operation index? But we already have the step index.
Let's stick to: the snapshot at step i is after operation i. Then the replay should start with operation i+1.
But wait, what if the user wants to replay including the operation at step i? Then they should have taken the snapshot at step i-1?
So we assume that the snapshot is taken at a step and then we replay the subsequent operations.
Therefore, in run_and_replay_check:
original_ops = operations
snapshot_step = ... (say 5)
Then the replay_operations should be original_ops[snapshot_step+1:]
But note: the original run has steps 0..len(original_ops)-1.
The snapshot at step 5 is after op5. Then we replay ops from 6 to the end.
Then we compare:
original state at step 6 (after op6) with replay state after first replayed operation (which is op6).
So we compare:
for j in range(len(replay_ops)):
orig_step = snapshot_step + 1 + j # because the first replayed op is original step snapshot_step+1
if orig_step >= len(original_results):
break
...
But wait: the original_results are indexed by step (0-indexed). So:
original_results[snapshot_step] is the state after op[snapshot_step] (the snapshot).
original_results[snapshot_step+1] is the state after op[snapshot_step+1].
And the replay_results[0] is the state after applying the first replayed operation (which is op[snapshot_step+1]).
So we compare:
original_results[snapshot_step+1 + j] with replay_results[j]
for j from 0 to len(replay_ops)-1, but note that the replay_ops are exactly the operations from snapshot_step+1 onward, so we have:
len(replay_ops) = len(original_ops) - (snapshot_step+1)
And we compare until j reaches that length.
However, if the user provides a different replay_operations (maybe shorter or longer) then we adjust.
But note: the original_results only go up to len(original_ops)-1.
So:
for j in range(min(len(replay_ops), len(original_ops) - (snapshot_step+1))):
orig_step = snapshot_step+1+j
...
But what if the replay_operations are longer? Then we don't have original states to compare for the extra steps? So we break when orig_step exceeds.
Alternatively, we can require that the replay_operations are exactly the same as the original from snapshot_step+1 onward? That would be safer.
Let's change:
if replay_operations is None:
replay_operations = operations[snapshot_step+1:]
else:
# Check that replay_operations equals operations[snapshot_step+1: len(operations)]? But maybe the user wants to replay a subset? Then we compare only the subset.
pass
Actually, the user might want to replay a subset (for example, from the snapshot to a certain point). Then we compare only the steps that are in both.
So we don't enforce the same length, but we compare until we run out of either.
But note: the original run might have more operations after the snapshot than the replay? Then we are only comparing the replay part.
That seems acceptable.
So:
max_j = min(len(replay_ops), len(original_ops) - (snapshot_step+1))
for j in range(max_j):
orig_step = snapshot_step+1+j
...
And then if the replay_ops are shorter, we don't compare the rest of the original.
But what if the replay_ops are longer? Then we stop at the end of the original.
So:
max_j = min(len(replay_ops), len(original_ops) - (snapshot_step+1))
However, note: the original_results have steps from 0 to len(original_ops)-1. The last step is len(original_ops)-1.
So the available steps after the snapshot (snapshot_step) are from snapshot_step+1 to len(original_ops)-1, which is (len(original_ops) - (snapshot_step+1)) steps.
So:
max_j = min(len(replay_ops), len(original_ops) - snapshot_step - 1)
Then:
for j in range(max_j):
orig_step = snapshot_step+1+j
...
But wait: if the snapshot_step is the last step, then there are no more operations. Then we don't replay anything.
That's okay.
So let's code accordingly.
However, note: the run method returns results which has an entry for every step (including step0). So:
original_results[0] -> after op0
original_results[1] -> after op1
...
So the state at step `i` is in `original_results[i][2]`.
And the replay_results[0] is after the first replayed operation (which is op[snapshot_step+1] in the original).
So we compare:
original_results[snapshot_step+1][2] with replay_results[0][2]
original_results[snapshot_step+2][2] with replay_results[1][2]
...
So:
for j in range(max_j):
orig_step = snapshot_step+1+j
if orig_step >= len(original_results):
break
...
But note: `max_j` is already limited by the available steps in the original after the snapshot.
So:
for j in range(max_j):
orig_step = snapshot_step+1+j
orig_state = original_results[orig_step][2]
replay_state = replay_results[j][2]
if not self.state_comparator(orig_state, replay_state):
return False, (orig_step, orig_state, replay_state)
And we return True if all compared steps match.
But what about invariants? The `run` and `replay` methods already check invariants and record violations. We are only comparing states.
However, if the states are the same, then the invariants should be the same? Because invariants are a function of the state.
So we don't need to compare violations separately.
But note: the invariants might be non-deterministic? Then the same state might produce different violations? That would be a problem in the invariants.
We assume invariants are deterministic.
So we are good.
Let's code accordingly.
However, note: the run method records violations for each step. But in the replay, we run the same operations from the same state, so the violations should be the same as in the original for the same steps?
But wait: the original run might have had violations at some steps, and then fixed later? But if the states are the same, then the violations at that state must be the same.
So we are comparing states, which implicitly compares violations.
But what if the user wants to compare violations too? They can do that separately.
We'll stick to state comparison.
Let's write the code accordingly.
We'll also allow the user to pass a custom state comparator.
Implementation:
class Harness:
def init(self, contract, state_comparator=None):
self.contract = contract
self.state_comparator = state_comparator or (lambda x, y: x == y)
def run(self, operations, check_invariants=True, snapshot_steps=[]):
state = self.contract.initial_state()
snapshots = {}
results = []
for i, op in enumerate(operations):
state = self.contract.apply(op, state)
violations = []
if check_invariants:
for inv in self.contract.invariants():
violations.extend(inv(state))
results.append((i, op, copy.deepcopy(state), violations))
if i in snapshot_steps:
snapshots[i] = copy.deepcopy(state)
return state, snapshots, results
def replay(self, snapshot, operations, check_invariants=True):
state = copy.deepcopy(snapshot)
results = []
for i, op in enumerate(operations):
state = self.contract.apply(op, state)
violations = []
if check_invariants:
for inv in self.contract.invariants():
violations.extend(inv(state))
results.append((i, op, copy.deepcopy(state), violations))
return state, results
def run_and_replay_check(self, operations, snapshot_step, replay_operations=None):
# Run the original
final_state, snapshots, original_results = self.run(operations, check_invariants=True, snapshot_steps=[snapshot_step])
if snapshot_step not in snapshots:
raise ValueError(f"Snapshot at step {snapshot_step} not found. Make sure to include {snapshot_step} in snapshot_steps when running.")
snapshot = snapshots[snapshot_step]
if replay_operations is None:
replay_operations = operations[snapshot_step+1:]
# Replay
replay_state, replay_results = self.replay(snapshot, replay_operations, check_invariants=True)
# Compare states step by step
max_j = min(len(replay_operations), len(operations) - snapshot_step - 1)
for j in range(max_j):
orig_step = snapshot_step + 1 + j
orig_state = original_results[orig_step][2]
replay_state = replay_results[j][2]
if not self.state_comparator(orig_state, replay_state):
return False, (orig_step, orig_state, replay_state)
return True, None
But note: the run method by default checks invariants. We are checking invariants in both runs. But we are only comparing states.
Alternatively, we can also compare the violations? But if the states are the same, the violations should be the same.
However, what if the invariants are not pure? Then we have a problem. But we assume they are.
So we are good.
However, note: the run method returns the final state and the results. But in run_and_replay_check we only use the original_results for states at steps after the snapshot.
We are not using the final state from the original run? We are comparing step by step.
But what if the replay_operations are longer than the remaining operations in the original? Then we compare only up to the original's end.
And if they are shorter, we compare only the replay length.
This seems okay.
Let's test with a simple example.
Example: A simple counter.
class CounterContract(Contract):
def initial_state(self):
return {"count": 0}
def apply(self, operation, state):
# operation is either "inc" or "dec"
new_state = state.copy()
if operation == "inc":
new_state["count"] += 1
elif operation == "dec":
new_state["count"] -= 1
return new_state
def invariants(self):
return [lambda s: [] if s["count"] >= 0 else ["count must be non-negative"]]
Then:
contract = CounterContract()
harness = Harness(contract)
ops = ["inc", "inc", "dec", "inc"]
# Run and take snapshot at step 2 (after the first three operations: inc, inc, dec -> count=1)
success, diff = harness.run_and_replay_check(ops, snapshot_step=2)
Steps:
original run:
step0: inc -> count=1
step1: inc -> count=2
step2: dec -> count=1 (snapshot at step2)
step3: inc -> count=2
replay from snapshot at step2 (count=1) with ops[3:] which is ["inc"] -> count=2.
Compare:
original step3 (index 3) state: count=2
replay step0 state: count=2 -> match.
So it should return True.
Now, what if we change the contract? For example, we change the `apply` method to sometimes not increment? Then the replay might fail.
This is the idea.
However, note: the run method in the harness does:
state = self.contract.apply(op, state)
and then records a deepcopy of the state.
And the replay does the same.
So if the contract's apply method is deterministic, then from the same state and same operation we get the same state.
But what if the contract has randomness? Then we cannot guarantee the same state.
We assume deterministic contracts.
This harness is for testing change data (like a software update) that should not change the behavior.
So we assume the contract is deterministic.
If the contract is not deterministic, then we cannot use this for replay consistency? Then the user must provide a deterministic contract or a way to set the random seed? That's out of scope.
So we assume deterministic.
Also, note: the state must be deepcopy-able.
We are using `copy.deepcopy`.
Let's code accordingly.
But wait: the `run` method takes `snapshot_steps` as a list. In `run_and_replay_check` we only take one snapshot (at snapshot_step). So we pass [snapshot_step] to `run`.
And then we get the snapshot from the returned `snapshots` dict.
That's okay.
However, what if the user wants to take multiple snapshots? Then they should use `run` directly and then `replay` with the desired snapshot.
The `run_and_replay_check` is a convenience method for one snapshot.
We can also have a method that takes multiple snapshots and replays from each? But that might be overkill.
We'll leave it as one snapshot for now.
Alternatively, we can have:
def check_multiple_snapshots(self, operations, snapshot_steps):
# Run once, take snapshots at all given steps, then for each snapshot, replay from that step and check.
But that would run the original only once and then replay from each snapshot. That might be efficient.
But note: the replay for each snapshot will replay the remaining operations from that snapshot. And we compare the states from the original run at the corresponding steps.
We can do:
original_state, snapshots, original_results = self.run(operations, check_invariants=True, snapshot_steps=snapshot_steps)
for snapshot_step in snapshot_steps:
replay_ops = operations[snapshot_step+1:]
replay_state, replay_results = self.replay(snapshots[snapshot_step], replay_ops, check_invariants=True)
# then compare as above for this snapshot.
And we can return a dict of results for each snapshot.
But we don't have that method. We can add it if needed.
For now, we have `run_and_replay_check` for one snapshot.
Let's code accordingly.
We'll also note that the `run` method by default checks invariants. But what if the user doesn't want to check invariants in the original run? Then they can set `check_invariants=False` in `run_and_replay_check`? But then we are not checking invariants in the original? That might be okay for state comparison? But the point is to check invariants too.
We are only comparing states. But the original run might have had invariant violations and then fixed? But if the states are the same, then the violations are the same.
However, if we don't check invariants in the original run, then we don't record violations in the original_results? But we are not comparing violations.
So it's okay.
But note: the `run` method in `run_and_replay_check` is called with `check_invariants=True` by default. And the replay also checks invariants.
We are not using the violations in the comparison.
So we can leave it.
Let's code accordingly.
However, note: the `run` method returns `results` which includes violations. But we don't use them in the comparison.
We are only using the state.
So if the user wants to check that the violations are the same, they can do that separately.
But if the states are the same, the violations must be the same (if the invariants are deterministic and pure).
So we are safe.
Now, what about the initial state? We are not checking that the initial state is the same because we start the replay from a snapshot.
But the snapshot is taken from the original run, so we assume the original run's initial state is the same as the contract's initial_state? That is the contract's responsibility.
We are good.
Let's write the code.
But note: the `run` method returns the final state, which we don't use in `run_and_replay_check`.
We can change `run` to return the results and snapshots only? Actually, we return (state, snapshots, results). The state is the final state.
In `run_and_replay_check` we don't use the final state from the original run? We use the original_results for intermediate states.
So we are good.
One more thing: the `replay` method returns the final state and the results. We don't use the final state from the replay? We use the replay_results for intermediate states.
So we are good.
Let's code accordingly.
However, note: the `run` method does:
state = self.contract.initial_state()
and then for each operation:
state = self.contract.apply(op, state)
and then records a deepcopy of state.
So the state in the results is a deepcopy at that step.
And in the replay, we start from a deepcopy of the snapshot and then apply operations and record deepcopy at each step.
So we are comparing deepcopies, which is safe.
Now, what if the state is huge? Then deepcopy might be expensive. We are doing it at every step and also for snapshots.
That's a performance concern, but for testing it might be acceptable.
Alternatively, we can avoid deepcopy if the state is immutable? But we don't know.
We can let the user provide a snapshot function? Or we can assume the state is a dictionary and copy with `copy.deepcopy` is safe.
We'll stick to deepcopy.
Now, let's write the code.
We'll also add a method to just run and check invariants without replay? That's already in `run`.
And a method to just replay from a given state (without comparing) is `replay`.
And the combined method.
We are done.
But note: the `run` method takes `snapshot_steps` as a list of step indices. We are passing `[snapshot_step]` in `run_and_replay_check`.
That's okay.
Let's code accordingly.
However, note: the `run` method's `snapshot_steps` are the steps at which we take a snapshot (after applying the operation at that step). So if we want to replay from step `i`, we take a snapshot at step `i`.
Then we replay from step `i+1` (the next operation).
So in `run_and_replay_check` we take the snapshot at `snapshot_step` and then replay from `snapshot_step+1`.
That's consistent.
Now, what if the user wants to replay from the initial state? Then they would take a snapshot at step -1? That doesn't exist.
We can change the design to allow a snapshot at step -1 (the initial state) but then we would have to adjust.
Alternatively, we can have:
In `run`, we take snapshots at step `i` (after op `i`). Then the initial state is not in the snapshots unless we take a snapshot at step -1? We don't.
So to replay from the initial state, we can use the initial state from the contract.
We can change `run_and_replay_check` to allow snapshot_step = -1 to mean the initial state.
Or we can have a separate method that takes an initial state?
Let's change:
In `run_and_replay_check`, if snapshot_step is -1, then we use the initial state (and we don't require a snapshot). Then we replay from the beginning (operations[0:]).
But note: the original run starts from the initial state and applies all operations.
Then we would compare:
original step0 (after op0) with replay step0 (after op0) -> should be the same.
But wait: the original step0 is after op0, and the replay step0 is after op0? Yes.
So we can do:
if snapshot_step == -1:
snapshot = self.contract.initial_state()
# Then we replay all operations (from 0 to end) and compare with the original results for steps 0 to end.
else:
# as before
But note: the original run's step0 is after op0. So if we start from initial state and replay op0, we get the state after op0, which is original step0.
So we compare:
for j in range(min(len(operations), len(original_results))):
orig_state = original_results[j][2]
replay_state = replay_results[j][2]
But wait: if snapshot_step is -1, then we are replaying from the beginning, so we compare:
original step0 with replay step0 (which is after op0)
original step1 with replay step1 (after op1)
...
So we don't have the offset.
So we adjust:
if snapshot_step == -1:
offset = 0
else:
offset = snapshot_step+1
Then:
max_j = min(len(replay_ops), len(original_ops) - offset)
for j in range(max_j):
orig_step = offset + j
...
But note: when snapshot_step is -1, then offset=0, and replay_ops = operations[0:] (if not provided) so:
max_j = min(len(operations), len(original_ops) - 0) = len(operations) (since original_ops is the same as operations)
Then we compare for j from 0 to len(operations)-1:
orig_step = 0+j = j
so we compare original_results[j] with replay_results[j]
That's correct.
And if snapshot_step is 5, then offset=6, and we compare from step6 onward.
So we can do:
offset = snapshot_step+1 if snapshot_step >=0 else 0
And then:
max_j = min(len(replay_ops), len(original_ops) - offset)
But note: if snapshot_step is the last step (say 9 in a 10-step run, indices 0..9), then offset=10, and len(original_ops) - offset = 10-10=0 -> no comparison.
That's correct because there are no more operations.
So let's adjust the code:
if snapshot_step == -1:
snapshot = self.contract.initial_state()
if replay_operations is None:
replay_operations = operations
else:
if snapshot_step not in snapshots:
raise ...
snapshot = snapshots[snapshot_step]
if replay_operations is None:
replay_operations = operations[snapshot_step+1:]
offset = 0 if snapshot_step == -1 else snapshot_step+1
Then:
max_j = min(len(replay_operations), len(original_ops) - offset)
But wait: the original_ops is the same as `operations`? Yes.
So:
max_j = min(len(replay_operations), len(operations) - offset)
Then:
for j in range(max_j):
orig_step = offset + j
...
But note: the original_results are for steps 0..len(operations)-1.
So if offset+j >= len(original_results), we break? But we already limited by max_j.
So:
for j in range(max_j):
orig_step = offset + j
orig_state = original_results[orig_step][2]
replay_state = replay_results[j][2]
...
However, note: the original_results might have fewer steps than the operations? Because we record after each operation. So if we have n operations, we have n steps (0 to n-1).
So the condition is:
max_j = min(len(replay_operations), len(operations) - offset)
because len(original_results) == len(operations).
So we are safe.
Let's adjust the code accordingly.
We'll change:
def run_and_replay_check(self, operations, snapshot_step, replay_operations=None):
# Run the original
original_state, snapshots, original_results = self.run(operations, check_invariants=True, snapshot_steps=[snapshot_step] if snapshot_step>=0 else [])
if snapshot_step >=0 and snapshot_step not in snapshots:
raise ValueError(f"Snapshot at step {snapshot_step} not found. Make sure to include {snapshot_step} in snapshot_steps when running.")
if snapshot_step == -1:
snapshot = self.contract.initial_state()
if replay_operations is None:
replay_operations = operations
else:
snapshot = snapshots[snapshot_step]
if replay_operations is None:
replay_operations = operations[snapshot_step+1:]
offset = 0 if snapshot_step == -1 else snapshot_step+1
# Replay
replay_state, replay_results = self.replay(snapshot, replay_operations, check_invariants=True)
max_j = min(len(replay_operations), len(operations) - offset)
for j in range(max_j):
orig_step = offset + j
orig_state = original_results[orig_step][2]
replay_state = replay_results[j][2]
if not self.state_comparator(orig_state, replay_state):
return False, (orig_step, orig_state, replay_state)
return True, None
But wait: when snapshot_step is -1, we are taking the initial state. But note: the original run's step0 is after op0. So we are comparing:
original step0 (after op0) with replay step0 (after op0) -> which is correct.
However, note: the original run's step0 is recorded after applying op0. And the replay from initial state with op0 will also produce the state after op0.
So we are comparing the same.
But what about the initial state? We are not comparing the initial state because we start the replay from the initial state and then apply op0.
That's okay because the initial state is the same (the contract's initial_state) and then we apply the same op0.
So it's consistent.
However, note: the original run's step0 is after op0, and the replay's step0 is after op0. So we are comparing the state after op0.
But what if we want to compare the initial state? Then we would need to take a snapshot at step -1? We don't.
So the design is:
snapshot_step = -1 means start from the initial state and replay the given operations (or all operations if replay_operations is None).
Then we compare the state after each operation in the replay with the corresponding step in the original.
For step0 in the original (after op0) we compare with replay step0 (after op0).
That's correct.
But note: the original run's step0 is after op0, and the replay's step0 is after op0. So we are comparing the same.
However, what if the user wants to compare the initial state? Then they should take a snapshot at step -1? But we don't have a step -1.
Alternatively, we can change the snapshot_step to be the step at which we take the snapshot (after that step). Then the initial state is before step0.
So to compare the initial state, we would need to take a snapshot at step -1? That's not in the original run.
So we cannot compare the initial state with this method? Because the original run starts from the initial state and we don't record the initial state in the results? We record after each operation.
We can change the `run` method to record the initial state as step -1? But then the steps would be -1,0,1,... and the snapshot_steps would be indices? That might be confusing.
Alternatively, we can have a separate method to get the initial state.
But note: the contract has `initial_state`. So the user can get the initial state from the contract.
And if they want to check that the initial state is the same, they can just compare the contract's initial_state with the snapshot at step -1? But we don't have a snapshot at step -1.
Actually, the initial state is not a snapshot because we haven't applied any operation.
So perhaps we don't need to compare the initial state? Because the replay starts from the same initial state (if snapshot_step=-1) and then applies the same operations, so the initial state is the same by construction.
But what if the contract's initial_state is not deterministic? Then we have a problem.
We assume the contract's initial_state is deterministic.
So we are safe.
Therefore, we don't need to compare the initial state separately.
So the above code is fine.
Let's test with snapshot_step=-1:
operations = [op0, op1, op2]
original run:
step0: after op0
step1: after op1
step2: after op2
snapshot_step=-1: snapshot = initial_state
replay_operations = operations (if None) -> [op0, op1, op2]
Then:
offset = 0
max_j = min(3, 3-0)=3
j=0: orig_step=0, compare original_results[0] (after op0) with replay_results[0] (after op0)
j=1: orig_step=1, compare original_results[1] (after op1) with replay_results[1] (after op1)
j=2: orig_step=2, compare original_results[2] (after op2) with replay_results[2] (after op2)
That's correct.
Now, what if the user wants to replay a subset? For example, from the initial state only the first two operations?
Then they can pass replay_operations = [op0, op1]
Then max_j = min(2, 3-0)=2
And we compare:
j=0: orig_step=0 -> after op0
j=1: orig_step=1 -> after op1
And we don't compare step2.
That's correct.
So we are good.
One more: if snapshot_step=1 (in a 3-step run) then:
original run:
step0: after op0
step1: after op1 (snapshot at step1)
step2: after op2
Then:
snapshot = state after step1 (which is after op1)
replay_operations = [op2] (if None)
offset = 1+1 = 2
max_j = min(1, 3-2)=1
j=0: orig_step=2 -> after op2
replay_results[0] -> after op2
Correct.
So the code seems solid.
Let's write the code accordingly.
However, note: the `run` method in `run_and_replay_check` is called with `snapshot_steps=[snapshot_step]` only if snapshot_step>=0. If snapshot_step==-1, we don't take any snapshot? Actually, we don't need a snapshot because we use the initial state.
But wait: what if the user wants to take a snapshot at step -1? We don't support that.
We are using the contract's initial_state directly.
That's okay.
But note: the contract's initial_state might be different from the state after step -1? There is no step -1.
So we are using the same initial state as the original run? The original run starts with the contract's initial_state.
So yes.
Therefore, we are consistent.
Now, what about invariants? We are checking invariants in both runs, but we are not comparing the violations. We are only comparing states.
But if the states are the same, then the violations (which are a function of the state) should be the same.
However, what if the invariants are not pure? Then we have a problem.
We assume the invariants are pure.
So we are safe.
Let's code accordingly.
One more thing: the `run` method returns the final state, which we don't use. We can ignore it.
But note: the `run` method also returns the snapshots. We use the snapshot for the given step.
So we are good.
Now, let's write the code.
We'll also add a method to run a sequence and check invariants at each step without replay? That's just `run` with check_invariants=True.
And a method to just replay from a given state (without comparing) is `replay`.
So we have:
run(operations, check_invariants=True, snapshot_steps=[])
replay(snapshot, operations, check_invariants=True)
run_and_replay_check(operations, snapshot_step, replay_operations=None)
And we have the state_comparator.
We are done.
Let's code accordingly.
However, note: the `run` method records the state at each step (after applying the operation) and also the violations.
The `replay` method does the same.
In `run_and_replay_check` we are only comparing the states (the third element in the tuple) for the steps that are in the replay.
We are not comparing the operations or the violations.
That's by design.
If the user wants to compare the operations, they can do that separately.
But note: the replay_operations might be different from the original operations? Then the states might be different and that's expected.
We are comparing the states that result from the same operations (if the replay_operations are the same as the original from the snapshot onward) and the same starting state (the snapshot).
So if the states are the same, then the operations must have had the same effect? Not necessarily, because different operations could lead to the same state? But that's unlikely and would be a bug in the contract if two different operations lead to the same state? Not necessarily.
But we are comparing the state after each operation, so if the operations are different, then the states at the same step index might be after different operations?
For example:
Original: [op0, op1, op2]
Replay from step1 (after op1) with replay_operations=[opX] (not op2). Then we compare:
original step2 (after op2) with replay step0 (after opX)
That's comparing apples to oranges.
So the user must ensure that the replay_operations are the same as the original operations from the snapshot_step+1 onward.
We can check that:
if replay_operations != operations[snapshot_step+1:]:
raise ValueError("Replay operations must match the original operations from the snapshot step onward.")
But what if the user wants to replay a subset? Then they are only comparing the subset? That might be acceptable.
For example, if the original has 10 operations and the user wants to replay only the first 5 from the snapshot? Then they pass replay_operations = operations[snapshot_step+1:snapshot_step+1+5]
Then we compare:
original step (snapshot_step+1) with replay step0
...
original step (snapshot_step+5) with replay step4
And we don't care about the rest.
That's acceptable.
So we don't enforce that the replay_operations are exactly the same as the original from that point, but we do compare the states at the corresponding steps (which are after different operations if the replay_operations are different).
So the user must be cautious.
We can change the method to:
def run_and_replay_check(self, operations, snapshot_step, replay_operations=None, compare_operations=False):
And if compare_operations is True, then we also check that the operations are the same.
But then we are comparing two lists of operations.
Alternatively, we can just compare the states and let the user decide.
We'll leave it as is, and document that the replay_operations should be the same as the original from the snapshot_step+1 onward for a meaningful comparison.
We are done.
Let's code accordingly.
However, note: the `run` method's `snapshot_steps` are taken after the operation at that step. So if we want to replay from step `i`, we take a snapshot at step `i` and then replay from step `i+1`.
That's what we do.
Now, what if the user wants to replay from step `i` including the operation at step `i`? Then they should take a snapshot at step `i-1`.
So we are consistent.
Code:
We'll use `copy` module for deepcopy.
Let's write the code.
Note: We are using abstract base classes, so we need to import ABC and abstractmethod.
Let's do that.
We'll also make the `Contract` class an ABC.
Code:
import copy
from abc import ABC, abstractmethod
class Contract(ABC):
@abstractmethod
def initial_state(self):
pass
@abstractmethod
def apply(self, operation, state):
pass
@abstractmethod
def invariants(self):
# returns a list of functions (state -> list of violation strings)
pass
class Harness:
def __init__(self, contract, state_comparator=None):
self.contract = contract
self.state_comparator = state_comparator or (lambda x, y: x == y)
def run(self, operations, check_invariants=True, snapshot_steps=[]):
state = self.contract.initial_state()
snapshots = {}
results = []
for i, op in enumerate(operations):
state = self.contract.apply(op, state)
violations = []
if check_invariants:
for inv in self.contract.invariants():
violations.extend(inv(state))
results.append((i, op, copy.deepcopy(state), violations))
if i in snapshot_steps:
snapshots[i] = copy.deepcopy(state)
return state, snapshots, results
def replay(self, snapshot, operations, check_invariants=True):
state = copy.deepcopy(snapshot)
results = []
for i, op in enumerate(operations):
state = self.contract.apply(op, state)
violations = []
if check_invariants:
for inv in self.contract.invariants():
violations.extend(inv(state))
results.append((i, op, copy.deepcopy(state), violations))
return state, results
def run_and_replay_check(self, operations, snapshot_step, replay_operations=None):
# Run the original
original_state, snapshots, original_results = self.run(operations, check_invariants=True, snapshot_steps=[snapshot_step] if snapshot_step>=0 else [])
if snapshot_step >=0 and snapshot_step not in snapshots:
raise ValueError(f"Snapshot at step {snapshot_step} not found. Make sure to include {snapshot_step} in snapshot_steps when running.")
if snapshot_step == -1:
snapshot = self.contract.initial_state()
if replay_operations is None:
replay_operations = operations
else:
snapshot = snapshots[snapshot_step]
if replay_operations is None:
replay_operations = operations[snapshot_step+1:]
offset = 0 if snapshot_step == -1 else snapshot_step+1
# Replay
replay_state, replay_results = self.replay(snapshot, replay_operations, check_invariants=True)
max_j = min(len(replay_operations), len(operations) - offset)
for j in range(max_j):
orig_step = offset + j
orig_state = original_results[orig_step][2]
replay_state = replay_results[j][2]
if not self.state_comparator(orig_state, replay_state):
return False, (orig_step, orig_state, replay_state)
return True, None
That's it.
Let's test with the counter example.
We'll write a test.
But note: the `run_and_replay_check` returns a boolean and a tuple (if failure) or (True, None).
We are done.
However, note: the `run` method returns the final state, which we don't use in `run_and_replay_check`. We can ignore it.
But what if the user wants to get the final state from the replay? They can use the return value of `replay`? But `run_and_replay_check` doesn't return the replay final state? It returns only the comparison result.
We can change `run_and_replay_check` to return more information? But the user can just call `replay` separately if they want.
Alternatively, we can return (success, diff, replay_final_state, replay_results) but that might be too much.
We'll keep it simple: return (success, diff) where diff is the first mismatched step and states.
The user can call `replay` if they want the full results.
So we are good.
Let's write the code accordingly.
But note: the `run_and_replay_check` method does not return the original_results or the replay_results. Only the boolean and the first diff.
If the user wants to see all the steps, they can run `run` and `replay` separately.
That's acceptable.
We are done.
However, note: the `run` method records the state at each step. If the user wants to compare all steps (even the ones before the snapshot) they can do that with the original_results.
But in `run_and_replay_check` we only compare from the snapshot onward.
That's by design.
Now, what about the invariants? We are checking invariants in both runs, but we are not comparing the violations. We are only comparing states.
But if the states are the same, the violations should be the same.
So we are safe.
We are done.
Let me write the code with proper imports.
We'll also add type hints? Not necessary but helpful.
Let's do without for now.
We are done.</think>
I'll design a comprehensive Change Data Testing Harness that combines contracts, invariants, and replay capabilities for rigorous testing of stateful systems. This is particularly useful for blockchain applications, databases, financial systems, or any system with complex state transitions.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ CHANGE DATA TESTING HARNESS │
├─────────────┬─────────────┬─────────────┬─────────────────┤
│ CONTRACTS │ INVARIANTS │ REPLAYS │ SNAPSHOTS │
├─────────────┼─────────────┼─────────────┼─────────────────┤
│ • Pre-conditions │
│ • Post-conditions │
│ • State transition rules │
├─────────────┼─────────────┼─────────────┼─────────────────┤
│ • Invariant definitions │
│ • Invariant checking engine │
│ • Invariant violation reporting │
├─────────────┼─────────────┼─────────────┼─────────────────┤
│ • Operation recording │
│ • State snapshotting │
│ • Replay verification │
│ • State diff comparison │
├─────────────┴─────────────┴─────────────┴─────────────────┤
│ TEST EXECUTION ENGINE │
└─────────────────────────────────────────────────────────────┘
Core Implementation
import hashlib
import json
import copy
from typing import Any, Callable, List, Dict, Optional, Tuple, Set
from dataclasses import dataclass, asdict
from datetime import datetime
from enum import Enum
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class VerificationResult(Enum):
PASS = "PASS"
FAIL = "FAIL"
SKIPPED = "SKIPPED"
ERROR = "ERROR"
@dataclass
class Operation:
"""Represents a single state transition operation"""
operation_id: str
operation_type: str
payload: Dict[str, Any]
timestamp: datetime
metadata: Dict[str, Any] = None
def to_dict(self) -> Dict:
return {
**asdict(self),
"timestamp": self.timestamp.isoformat()
}
@classmethod
def from_dict(cls, data: Dict) -> 'Operation':
data['timestamp'] = datetime.fromisoformat(data['timestamp'])
return cls(**data)
@dataclass
class InvariantViolation:
"""Records an invariant violation"""
invariant_name: str
step: int
operation_id: str
message: str
state_snapshot: Dict[str, Any]
severity: str = "HIGH" # LOW, MEDIUM, HIGH, CRITICAL
@dataclass
class ContractSpecification:
"""Formal specification of system behavior"""
name: str
version: str
preconditions: List[Callable[[Dict, Operation], Tuple[bool, str]]]
postconditions: List[Callable[[Dict, Operation, Dict], Tuple[bool, str]]]
invariants: List[Callable[[Dict], List[str]]]
transition_rules: List[Callable[[Dict, Operation], bool]]
def validate_preconditions(self, state: Dict, operation: Operation) -> List[str]:
"""Validate all preconditions return list of failures"""
failures = []
for precondition in self.preconditions:
success, message = precondition(state, operation)
if not success:
failures.append(f"Precondition failed: {message}")
return failures
def validate_postconditions(self, prev_state: Dict, operation: Operation, new_state: Dict) -> List[str]:
"""Validate all postconditions"""
failures = []
for postcondition in self.postconditions:
success, message = postcondition(prev_state, operation, new_state)
if not success:
failures.append(f"Postcondition failed: {message}")
return failures
def check_invariants(self, state: Dict) -> List[str]:
"""Check all invariants on current state"""
violations = []
for invariant in self.invariants:
try:
result = invariant(state)
if result: # Non-empty list means violations
violations.extend(result)
except Exception as e:
violations.append(f"Invariant check error: {str(e)}")
return violations
def is_valid_transition(self, state: Dict, operation: Operation) -> bool:
"""Check if operation is allowed from current state"""
for rule in self.transition_rules:
if not rule(state, operation):
return False
return True
class ChangeDataHarness:
"""
Main harness for change data testing with contracts, invariants, and replay capabilities
"""
def __init__(
self,
contract_spec: ContractSpecification,
state_serializer: Optional[Callable] = None,
state_deserializer: Optional[Callable] = None
):
self.contract = contract_spec
self.state_serializer = state_serializer or self._default_serializer
self.state_deserializer = state_deserializer or self._default_deserializer
self.snapshots: Dict[str, Dict] = {}
self.operation_log: List[Operation] = []
self.invariant_violations: List[InvariantViolation] = []
self.current_state: Dict = {}
def _default_serializer(self, state: Dict) -> str:
"""Default JSON serializer with sorted keys for consistency"""
return json.dumps(state, sort_keys=True, separators=(',', ':'))
def _default_deserializer(self, serialized: str) -> Dict:
"""Default JSON deserializer"""
return json.loads(serialized)
def _compute_state_hash(self, state: Dict) -> str:
"""Compute deterministic hash of state"""
serialized = self.state_serializer(state)
return hashlib.sha256(serialized.encode()).hexdigest()
def initialize(self, initial_state: Dict) -> None:
"""Initialize system with starting state"""
self.current_state = copy.deepcopy(initial_state)
self.operation_log = []
self.invariant_violations = []
self.snapshots = {}
# Validate initial state against invariants
initial_violations = self.contract.check_invariants(initial_state)
for violation in initial_violations:
self.invariant_violations.append(
InvariantViolation(
invariant_name="initial_state",
step=0,
operation_id="INIT",
message=violation,
state_snapshot=copy.deepcopy(initial_state)
)
)
def execute_operation(
self,
operation: Operation,
check_contract: bool = True,
check_invariants: bool = True
) -> Tuple[VerificationResult, List[str], Dict]:
"""
Execute a single operation with full verification
Returns:
(result, messages, new_state)
"""
prev_state = copy.deepcopy(self.current_state)
all_messages = []
# 1. Check preconditions
if check_contract:
precondition_failures = self.contract.validate_preconditions(prev_state, operation)
all_messages.extend(precondition_failures)
if precondition_failures:
return VerificationResult.FAIL, precondition_failures, prev_state
# 2. Check transition rules
if not self.contract.is_valid_transition(prev_state, operation):
all_messages.append("Operation violates transition rules")
return VerificationResult.FAIL, all_messages, prev_state
# 3. Apply operation (user must implement this in subclass or provide apply_function)
new_state = self._apply_operation(prev_state, operation)
# 4. Check postconditions
if check_contract:
postcondition_failures = self.contract.validate_postconditions(
prev_state, operation, new_state
)
all_messages.extend(postcondition_failures)
# 5. Check invariants
if check_invariants:
invariant_failures = self.contract.check_invariants(new_state)
all_messages.extend(invariant_failures)
for violation in invariant_failures:
self.invariant_violations.append(
InvariantViolation(
invariant_name="runtime_invariant",
step=len(self.operation_log),
operation_id=operation.operation_id,
message=violation,
state_snapshot=copy.deepcopy(new_state)
)
)
# 6. Update state and log
self.current_state = new_state
self.operation_log.append(operation)
if all_messages:
return VerificationResult.FAIL, all_messages, new_state
return VerificationResult.PASS, [], new_state
def _apply_operation(self, state: Dict, operation: Operation) -> Dict:
"""
Abstract method - must be implemented by user to actually modify state
This should contain the actual business logic
"""
raise NotImplementedError(
"Must implement _apply_operation method in subclass"
)
def take_snapshot(self, snapshot_id: str, include_log: bool = True) -> Dict:
"""Take a snapshot of current state and optionally operation log"""
snapshot = {
"state": copy.deepcopy(self.current_state),
"state_hash": self._compute_state_hash(self.current_state),
"timestamp": datetime.utcnow().isoformat(),
"operation_count": len(self.operation_log)
}
if include_log:
snapshot["operations"] = [op.to_dict() for op in self.operation_log]
self.snapshots[snapshot_id] = snapshot
return snapshot
def replay_from_snapshot(
self,
snapshot_id: str,
operations: List[Operation],
stop_on_violation: bool = True
) -> Tuple[VerificationResult, List[InvariantViolation], Dict]:
"""
Replay operations from a snapshot and verify state consistency
Returns:
(result, violations, final_state)
"""
if snapshot_id not in self.snapshots:
raise ValueError(f"Snapshot {snapshot_id} not found")
snapshot = self.snapshots[snapshot_id]
state = copy.deepcopy(snapshot["state"])
violations = []
logger.info(f"Replaying {len(operations)} operations from snapshot {snapshot_id}")
for i, operation in enumerate(operations):
# Apply operation
prev_state = copy.deepcopy(state)
try:
state = self._apply_operation(state, operation)
except Exception as e:
violations.append(
InvariantViolation(
invariant_name="replay_error",
step=i,
operation_id=operation.operation_id,
message=f"Failed to apply operation: {str(e)}",
state_snapshot=prev_state
)
)
if stop_on_violation:
break
continue
# Check invariants
invariant_failures = self.contract.check_invariants(state)
for failure in invariant_failures:
violations.append(
InvariantViolation(
invariant_name="replay_invariant",
step=i,
operation_id=operation.operation_id,
message=failure,
state_snapshot=copy.deepcopy(state)
)
)
if violations and stop_on_violation:
break
# Compare final state with expected if we have original log in snapshot
if "operations" in snapshot and len(snapshot["operations"]) > 0:
# We have original operations in snapshot, so we can verify exact replay
expected_state = self._replay_operations(
copy.deepcopy(snapshot["state"]),
[Operation.from_dict(op) for op in snapshot["operations"]]
)
if self._compute_state_hash(state) != self._compute_state_hash(expected_state):
violations.append(
InvariantViolation(
invariant_name="state_mismatch",
step=-1,
operation_id="REPLAY_COMPARISON",
message="Replayed state does not match original execution",
state_snapshot=state
)
)
result = VerificationResult.PASS if not violations else VerificationResult.FAIL
return result, violations, state
def _replay_operations(
self,
initial_state: Dict,
operations: List[Operation]
) -> Dict:
"""Replay operations to compute expected final state"""
state = copy.deepcopy(initial_state)
for op in operations:
state = self._apply_operation(state, op)
return state
def verify_snapshot_consistency(
self,
snapshot_id1: str,
snapshot_id2: str
) -> Tuple[bool, Dict[str, Any]]:
"""
Verify that two snapshots represent equivalent states
(canonical comparison considering hash equality)
"""
if snapshot_id1 not in self.snapshots or snapshot_id2 not in self.snapshots:
raise ValueError("One or both snapshots not found")
snap1 = self.snapshots[snapshot_id1]
snap2 = self.snapshots[snapshot_id2]
hash1 = snap1["state_hash"]
hash2 = snap2["state_hash"]
is_consistent = hash1 == hash2
diff = {
"snapshot1": snapshot_id1,
"snapshot2": snapshot_id2,
"hash_match": is_consistent,
"hash1": hash1,
"hash2": hash2,
"timestamp1": snap1["timestamp"],
"timestamp2": snap2["timestamp"],
"operation_count1": snap1["operation_count"],
"operation_count2": snap2["operation_count"]
}
if not is_consistent:
# Compute actual state differences
state1 = snap1["state"]
state2 = snap2["state"]
diff["state_differences"] = self._compute_state_diff(state1, state2)
return is_consistent, diff
def _compute_state_diff(self, state1: Dict, state2: Dict) -> Dict:
"""Compute differences between two states"""
diff = {
"added": {},
"removed": {},
"modified": {}
}
all_keys = set(state1.keys()) | set(state2.keys())
for key in all_keys:
if key not in state1:
diff["added"][key] = state2[key]
elif key not in state2:
diff["removed"][key] = state1[key]
elif state1[key] != state2[key]:
diff["modified"][key] = {
"before": state1[key],
"after": state2[key]
}
return diff
def generate_test_report(
self,
include_snapshots: bool = False,
include_operations: bool = False
) -> Dict[str, Any]:
"""Generate comprehensive test report"""
report = {
"contract": self.contract.name,
"contract_version": self.contract.version,
"timestamp": datetime.utcnow().isoformat(),
"total_operations": len(self.operation_log),
"total_violations": len(self.invariant_violations),
"summary": {
"pass_rate": 0,
"failures_by_severity": {}
},
"violations": []
}
# Count by severity
for violation in self.invariant_violations:
report["summary"]["failures_by_severity"][violation.severity] = \
report["summary"]["failures_by_severity"].get(violation.severity, 0) + 1
report["violations"].append({
"invariant": violation.invariant_name,
"step": violation.step,
"operation_id": violation.operation_id,
"message": violation.message,
"severity": violation.severity
})
# Calculate pass rate
total_steps = len(self.operation_log)
if total_steps > 0:
violation_steps = {v.step for v in self.invariant_violations if v.step >= 0}
report["summary"]["pass_rate"] = (total_steps - len(violation_steps)) / total_steps
if include_snapshots:
report["snapshots"] = {
sid: {
"hash": snap["state_hash"],
"timestamp": snap["timestamp"],
"operation_count": snap["operation_count"]
}
for sid, snap in self.snapshots.items()
}
if include_operations:
report["operations"] = [op.to_dict() for op in self.operation_log]
return report
# Example Usage: Bank Account Contract
class BankAccountContract(ContractSpecification):
"""Example contract for a bank account system"""
def __init__(self):
super().__init__(
name="BankAccount",
version="1.0.0",
preconditions=[],
postconditions=[],
invariants=[
self.balance_non_negative,
self.account_exists,
self.max_balance_limit
],
transition_rules=[
self.can_debit,
self.can_credit
]
)
def balance_non_negative(self, state: Dict) -> List[str]:
"""Invariant: Balance cannot be negative"""
violations = []
for account_id, account in state.get("accounts", {}).items():
if account.get("balance", 0) < 0:
violations.append(f"Account {account_id} has negative balance: {account['balance']}")
return violations
def account_exists(self, state: Dict) -> List[str]:
"""Invariant: All referenced accounts must exist"""
violations = []
# Check transactions reference existing accounts
for tx in state.get("transactions", []):
if tx["from"] not in state.get("accounts", {}):
violations.append(f"Transaction {tx['id']} references non-existent from account: {tx['from']}")
if tx["to"] not in state.get("accounts", {}):
violations.append(f"Transaction {tx['id']} references non-existent to account: {tx['to']}")
return violations
def max_balance_limit(self, state: Dict) -> List[str]:
"""Invariant: Balance cannot exceed maximum"""
MAX_BALANCE = 10_000_000
violations = []
for account_id, account in state.get("accounts", {}).items():
if account.get("balance", 0) > MAX_BALANCE:
violations.append(f"Account {account_id} exceeds max balance: {account['balance']}")
return violations
def can_debit(self, state: Dict, operation: Operation) -> bool:
"""Rule: Can only debit if sufficient balance"""
if operation.operation_type == "debit":
account_id = operation.payload.get("account_id")
amount = operation.payload.get("amount", 0)
account = state.get("accounts", {}).get(account_id, {})
if account.get("balance", 0) < amount:
return False
return True
def can_credit(self, state: Dict, operation: Operation) -> bool:
"""Rule: Can only credit to existing accounts"""
if operation.operation_type == "credit":
account_id = operation.payload.get("account_id")
if account_id not in state.get("accounts", {}):
return False
return True
class BankAccountHarness(ChangeDataHarness):
"""Concrete implementation for bank accounts"""
def _apply_operation(self, state: Dict, operation: Operation) -> Dict:
"""Apply bank account operation to state"""
new_state = copy.deepcopy(state)
op_type = operation.operation_type
payload = operation.payload
if op_type == "create_account":
account_id = payload["account_id"]
new_state["accounts"][account_id] = {
"balance": payload.get("initial_balance", 0),
"owner": payload["owner"],
"created_at": operation.timestamp.isoformat()
}
elif op_type == "debit":
account_id = payload["account_id"]
amount = payload["amount"]
new_state["accounts"][account_id]["balance"] -= amount
new_state.setdefault("transactions", []).append({
"id": operation.operation_id,
"type": "debit",
"account": account_id,
"amount": amount,
"timestamp": operation.timestamp.isoformat()
})
elif op_type == "credit":
account_id = payload["account_id"]
amount = payload["amount"]
new_state["accounts"][account_id]["balance"] += amount
new_state.setdefault("transactions", []).append({
"id": operation.operation_id,
"type": "credit",
"account": account_id,
"amount": amount,
"timestamp": operation.timestamp.isoformat()
})
elif op_type == "transfer":
from_account = payload["from_account"]
to_account = payload["to_account"]
amount = payload["amount"]
new_state["accounts"][from_account]["balance"] -= amount
new_state["accounts"][to_account]["balance"] += amount
new_state.setdefault("transactions", []).append({
"id": operation.operation_id,
"type": "transfer",
"from": from_account,
"to": to_account,
"amount": amount,
"timestamp": operation.timestamp.isoformat()
})
return new_state
# Example Test Workflow
def test_bank_account_system():
"""Demonstrate complete testing workflow"""
# 1. Setup contract and harness
contract = BankAccountContract()
harness = BankAccountHarness(contract)
# 2. Define test scenario
initial_state = {
"accounts": {
"acc1": {"balance": 1000, "owner": "Alice"},
"acc2": {"balance": 500, "owner": "Bob"}
},
"transactions": []
}
operations = [
Operation(
operation_id="op1",
operation_type="create_account",
payload={"account_id": "acc3", "owner": "Charlie", "initial_balance": 200},
timestamp=datetime.utcnow()
),
Operation(
operation_id="op2",
operation_type="credit",
payload={"account_id": "acc3", "amount": 300},
timestamp=datetime.utcnow()
),
Operation(
operation_id="op3",
operation_type="transfer",
payload={"from_account": "acc1", "to_account": "acc3", "amount": 400},
timestamp=datetime.utcnow()
),
Operation(
operation_id="op4",
operation_type="debit",
payload={"account_id": "acc2", "amount": 200},
timestamp=datetime.utcnow()
)
]
# 3. Initialize and execute
harness.initialize(initial_state)
print("=== Executing Operations ===")
for op in operations:
result, messages, state = harness.execute_operation(op)
print(f"Operation {op.operation_id}: {result.value}")
if messages:
for msg in messages:
print(f" ❌ {msg}")
# 4. Take snapshot after successful execution
harness.take_snapshot("baseline_execution")
# 5. Test replay functionality
print("\n=== Testing Replay ===")
replay_ops = operations[1:3] # Replay subset
result, violations, final_state = harness.replay_from_snapshot(
"baseline_execution",
replay_ops
)
print(f"Replay result: {result.value}")
if violations:
for v in violations:
print(f" ❌ {v.message}")
# 6. Test with modified implementation (simulate bug)
print("\n=== Testing Against Modified Implementation ===")
# Create a fork of the harness with a bug (e.g., wrong transfer logic)
class BuggyBankAccountHarness(BankAccountHarness):
def _apply_operation(self, state: Dict, operation: Operation) -> Dict:
"""Buggy version: transfers don't subtract from source"""
new_state = copy.deepcopy(state)
op_type = operation.operation_type
if op_type == "transfer":
# BUG: Only credit destination, don't debit source
to_account = operation.payload["to_account"]
amount = operation.payload["amount"]
new_state["accounts"][to_account]["balance"] += amount
# Missing: new_state["accounts"][from_account]["balance"] -= amount
new_state.setdefault("transactions", []).append({
"id": operation.operation_id,
"type": "transfer",
"from": operation.payload["from_account"],
"to": to_account,
"amount": amount,
"timestamp": operation.timestamp.isoformat()
})
else:
new_state = super()._apply_operation(state, operation)
return new_state
buggy_harness = BuggyBankAccountHarness(contract)
buggy_harness.initialize(initial_state)
# Execute same operations
for op in operations:
buggy_harness.execute_operation(op)
# Compare results
is_consistent, diff = harness.verify_snapshot_consistency(
"baseline_execution",
"current_buggy" # Would need to take snapshot in buggy harness
)
# 7. Generate report
report = harness.generate_test_report(include_snapshots=True)
print("\n=== Test Report ===")
print(f"Contract: {report['contract']} v{report['contract_version']}")
print(f"Total operations: {report['total_operations']}")
print(f"Total violations: {report['total_violations']}")
print(f"Pass rate: {report['summary']['pass_rate']:.2%}")
if report['violations']:
print("\nTop violations:")
for v in report['violations'][:5]:
print(f" • Step {v['step']}: {v['message']} (Severity: {v['severity']})")
return report
if __name__ == "__main__":
# Run example test
report = test_bank_account_system()
# You can also save reports to disk
with open('test_report.json', 'w') as f:
json.dump(report, f, indent=2, default=str)
Key Features
1. Contracts Layer
- Pre-conditions: Validate operations before execution
- Post-conditions: Verify results after execution
- Transition rules: Define valid state transitions
- Invariants: System-wide properties that must always hold
2. Invariants System
- Multiple invariant types (balance, existence, limits, etc.)
- Severity levels (LOW, MEDIUM, HIGH, CRITICAL)
- Automatic checking after each operation
- Detailed violation reporting with state snapshots
3. Replay Mechanism
- Snapshot management: Save/load system states at any point
- Deterministic replay: Same operations → same state (if implementation correct)
- State comparison: Cryptographic hashing + deep comparison
- Partial replay: Replay subsets of operations
- Cross-implementation replay: Compare different implementations
4. Verification Features
- State hash comparison: Detect any state differences
- Operation idempotency testing: Replay same operations multiple times
- Regression testing: Compare before/after code changes
- Fork testing: Test different implementation branches
Advanced Usage Patterns
# Pattern 1: Regression Testing
def regression_test(old_harness: ChangeDataHarness, new_harness: ChangeDataHarness, operations: List[Operation]):
"""Ensure new implementation behaves identically to old"""
# Execute on old implementation
old_harness.initialize(initial_state)
for op in operations:
old_harness.execute_operation(op)
old_harness.take_snapshot("old_implementation")
# Execute on new implementation
new_harness.initialize(initial_state)
for op in operations:
new_harness.execute_operation(op)
new_harness.take_snapshot("new_implementation")
# Compare snapshots
is_consistent, diff = old_harness.verify_snapshot_consistency(
"old_implementation", "new_implementation"
)
if not is_consistent:
print(f"REGESSION DETECTED: {diff['state_differences']}")
return False
return True
# Pattern 2: Incremental Testing with Snapshots
def test_incremental_changes(base_operations: List[Operation], change_operations: List[Operation]):
"""Test that changes don't break existing behavior"""
harness = ChangeDataHarness(contract)
harness.initialize(initial_state)
# Execute base operations
for op in base_operations:
harness.execute_operation(op)
baseline_snapshot = harness.take_snapshot("baseline")
# Apply change operations
for op in change_operations:
result, _, _ = harness.execute_operation(op)
if result != VerificationResult.PASS:
print(f"Change operation failed: {op.operation_id}")
# Replay base operations from post-change state
result, violations, _ = harness.replay_from_snapshot(
"baseline",
base_operations[-10:] # Replay last 10 base operations
)
return result == VerificationResult.PASS and not violations
# Pattern 3: Property-Based Testing Integration
def property_based_test(harness: ChangeDataHarness, property_func: Callable):
"""Combine with property-based testing (hypothesis)"""
@given(operations=st.lists(st.builds(Operation, ...)))
def test_properties(operations):
harness.initialize(initial_state)
# Track if we ever violated invariants
had_violation = False
for op in operations:
result, messages, _ = harness.execute_operation(op)
if result != VerificationResult.PASS:
had_violation = True
break
# Property must hold
assert not had_violation, "Invariant violated during test"
assert property_func(harness.current_state), "Custom property failed"
Best Practices
-
Snapshot Strategically
- Take snapshots at major state transitions
- Use descriptive snapshot IDs (
"after_deposit_123")
- Periodically clean old snapshots
-
Invariant Design
- Keep invariants pure (no side effects)
- Make invariants composable
- Use severity levels appropriately
- Test invariants themselves
-
Replay Validation
- Always compare final state hashes
- Check intermediate states for cumulative errors
- Use deterministic operation IDs
- Log timestamps for temporal operations
-
Performance Optimization
- Use incremental hashing for large states
- Compress snapshots for storage
- Cache invariant results when possible
- Parallelize replay verification
-
Integration Testing
- Combine with CI/CD pipelines
- Store baseline hashes in version control
- Alert on state hash changes
- Keep test data reproducible
Extensions to Consider
class DistributedHarness(ChangeDataHarness):
"""For distributed systems with multiple nodes"""
def __init__(self, contract, node_count: int):
super().__init__(contract)
self.node_states = [copy.deepcopy(initial_state) for _ in range(node_count)]
self.in_transit_messages: List[Dict] = []
def simulate_network(self, message: Dict):
"""Simulate message passing between nodes"""
self.in_transit_messages.append(message)
# Eventually deliver to target node
...
class TemporalHarness(ChangeDataHarness):
"""For time-sensitive systems"""
def __init__(self, contract, time_steps: List[datetime]):
super().__init__(contract)
self.time_steps = time_steps
self.current_time_index = 0
def advance_time(self):
"""Move to next time step"""
self.current_time_index = min(
self.current_time_index + 1,
len(self.time_steps) - 1
)
This harness provides a solid foundation for rigorous change data testing. The key insight is treating snapshots + deterministic replay + invariant checking as the core verification triad, which catches both implementation bugs and specification violations.
Would you like me to elaborate on any specific aspect or adapt this for a particular domain (e.g., blockchain smart contracts, financial systems, game state management)?