We are going to design a testing harness for hot restart upgrades in stateful services.
The harness should support:
Snapshotting: taking a snapshot of the current state of the service.
Replay: replaying a sequence of events to bring the service to a desired state.
Abort logic: ability to abort the hot restart process at various points.
Validation metrics: metrics to validate that the service state after restart is consistent.
We assume the stateful service has an event-sourcing architecture or at least can be modeled as a state machine that processes events.
Steps for hot restart:
a) The service is running and processing events.
b) We want to upgrade the service (maybe a new version) without stopping the service (hot restart).
c) We take a snapshot of the current state (including the state of the state machine and any in-memory data that must be preserved).
d) We stop the current instance and start a new instance (with the new code) and load the snapshot.
e) We then replay events that occurred after the snapshot was taken (if any) to catch up to the current state.
However, during the hot restart, we must ensure that:
The service remains available (or at least the downtime is minimal).
The state is consistent after the restart.
The testing harness will simulate the entire process and verify that the state after restart matches the expected state.
Design:
We'll have:
A mock stateful service that we can control. It should:
Have a state that can be snapshotted and restored.
Accept events and update its state accordingly.
Keep a log of events (for replay) and also the current state.
A snapshot manager that can:
Instruct the service to take a snapshot (which returns a snapshot object and the last event ID included).
Instruct the service to restore from a snapshot.
An event log (which we can replay from). We'll generate events and feed them to the service.
A hot restart controller that:
Coordinates the snapshot, stopping the old service, starting the new service (with the snapshot), and replaying missed events.
Can be told to abort at various points (e.g., after snapshot, during replay, etc.)
A validator that compares the state of the service after restart with the expected state (which we can compute by just continuing the old service without restart).
Metrics: We'll collect metrics on:
Time taken for the entire process.
Number of events replayed.
State consistency (hash of state, or specific fields).
Whether the abort logic worked (if we aborted, the service should be in a consistent state and possibly we can retry).
Steps in the test:
Step 0: Start the service (old version) and replay a set of initial events to get to a base state.
Step 1: Generate a burst of events (let's call them "during snapshot" events). We want to take a snapshot at a known point.
Step 2: Trigger the snapshot. The snapshot should include events up to a certain event ID.
Step 3: Generate more events (after snapshot) that the new service will have to replay.
Step 4: Perform the hot restart (with the possibility to abort at various stages). The hot restart process:
a) Stop the old service (but we are in a test, so we'll just simulate by not sending more events to it).
b) Start a new service (new version) and restore the snapshot.
c) Replay the events that occurred after the snapshot (the ones from step 3) to the new service.
Step 5: Validate that the state of the new service matches the state of the old service would have had if we continued without restart.
Step 6: Also, we want to test abort scenarios. We can abort at:
- After snapshot taken but before stopping old service.
- After stopping old service but before starting new service.
- After starting new service but before replaying events.
- During replay (after some events).
For aborts, we want to ensure that:
- The old service can continue (if we abort before stopping it) and the events that were generated during the abort window are not lost.
- Or if we abort after stopping the old service, we might need to restart the old service from the snapshot? But note: in a real hot restart, if we abort after stopping the old service, we might have downtime until we restart the old service again. So in our test, we can simulate by restarting the old service from the snapshot and then replaying the events that occurred after the snapshot (which we have in the event log).
However, note: in a real system, if we abort after stopping the old service, we might not have the old service running until we decide to restart it. So we have two options:
Option 1: We design the hot restart to be atomic: either it completes or we roll back to the old service (if we haven't stopped it). But if we have stopped it, then we have to start it again from the snapshot.
For the harness, we'll assume that we have the ability to restart the old service from the snapshot (if we took one) and then replay the events that occurred after the snapshot (which we have in the event log). But note: during the abort, new events might have been generated. We must capture those events and then replay them to the restarted old service.
So we need an event queue that is shared between the old service and the new service? Actually, in a real system, events are being written to a log (like Kafka). So we can simulate that by having an event log that both services read from.
Let's assume we have an event log that is persistent and both the old and new service read from it. The event log is append-only and each event has a sequence number.
Then the process:
Old service starts from the beginning of the event log (or from a snapshot) and processes events up to event N.
We take a snapshot at event N (so the snapshot includes the state after event N).
Then we generate events N+1, N+2, ... which are written to the event log.
For hot restart:
a) We stop the old service (so it stops reading from the event log).
b) We start the new service and give it the snapshot (which includes state after event N). The new service then reads the event log from event N+1 onward and processes them.
If we abort at some point, we might stop the new service and then restart the old service from the snapshot (and it will also read from event N+1 onward). But note: if the new service has already processed some events (say up to event M, where M>N) then when we restart the old service, it will also process from N+1 to M? That would cause duplicate processing?
So we need to be careful: the event log must be designed so that each event is processed exactly once. We can do this by having each event have a unique ID and the service keeps track of the last processed event ID.
In the snapshot, we store the last processed event ID (N). Then when we restart (either old or new), we start from N+1.
But if we are in the middle of an abort, and the new service has processed up to M, then when we restart the old service, it will start from N+1 and process up to M? That would be a problem because the events N+1 to M would be processed twice?
Actually, in a real system, if we are doing a hot restart and we abort after the new service has processed some events, then we have two services that have processed some events? That's a problem.
So the hot restart process must be designed so that during the restart, the old service is stopped and no new events are processed until the new service is ready. Then the new service starts processing from the last snapshot point (N) and then processes the events from N+1 onward. But if we abort, we must stop the new service and then restart the old service from the snapshot (so it will process from N+1 onward). However, if the new service has already processed some events (say up to M) then those events are already in the event log. When we restart the old service, it will process from N+1 to M again? That would be a duplicate.
Therefore, we must have a way to mark events as processed by a particular service instance? Or we must ensure that during the hot restart, the event log is not being written to? But that would break availability.
Alternatively, we can design the event log to be idempotent? Or we can have a way to checkpoint the event log so that when we restart the old service, we start from the last event that was processed by the old service (which is N) and then we skip the events that were processed by the new service? But how does the old service know which events were processed by the new service?
This is getting complex. Let's step back.
In a typical hot restart (or blue-green deployment) for stateful services, we might have:
code
- The old service is still running and processing events.
- We take a snapshot of the old service (at event N).
- We start a new service with the snapshot and then we start sending new events to both the old and new service? No, that would cause both to process the same events? Actually, we want to switch over.
Usually, we would have a load balancer that starts sending new events to the new service after it's ready. But then the old service might still get some events? We need to avoid that.
Alternatively, we can pause the event log (or the producers) during the restart? But that might not be acceptable for availability.
Given the complexity, for the purpose of this harness, we'll assume:
code
- We have an event log that is append-only and we can control the flow of events.
- We can pause the event log (stop new events from being written) during the hot restart? But then we are not testing the scenario where events come in during the restart.
Alternatively, we can simulate the event log as a queue that both services can read from, but we must ensure that each event is processed by exactly one service. We can do this by having the event log assign each event to a service instance? But that's not typical.
Let's think of a more typical pattern:
code
We have a set of event producers that write events to a log (like Kafka). Then we have a consumer group with multiple consumers (the old service and the new service). But in a consumer group, each partition is consumed by only one consumer in the group. So if we have two services (old and new) in the same consumer group, then they would share the partitions and each event would be processed by only one of them. But then when we switch, we would remove the old service from the consumer group and the new service would take over all partitions. However, during the restart, we would have the old service and the new service in the same group? That would cause a rebalance and both might processing some partitions? And then when we remove the old service, the new service would take over all partitions and continue from the last offset it committed.
This is getting too specific to Kafka. Let's abstract:
We'll assume that the event log is a sequence of events with increasing sequence numbers. The service (old or new) will process events in order and keep track of the last processed event ID (committed offset). When we restart a service (old or new) from a snapshot, we start from the last processed event ID in the snapshot and then process events that have a higher sequence number.
But note: if we have two services (old and new) running at the same time and both are reading from the same event log, they would both try to process the same events? Unless we have a way to partition the events by service instance? That doesn't make sense.
So in a hot restart, we typically stop the old service from reading the event log (by taking it out of the consumer group or by pausing it) and then start the new service. Then we switch the event log to be read by the new service only.
Therefore, for the harness, we can simulate:
code
- We have an event log that we control. We can write events to it and we can read from it.
- The old service is reading from the event log (and processing events) until we stop it.
- We stop the old service (so it stops reading).
- We start the new service and give it the snapshot (which includes the last processed event ID, say N). The new service then reads from the event log starting at N+1.
But what about events that are written while the old service is stopped and the new service is starting? They are written to the event log and the new service will read them.
So the process:
code
Let the event log have events up to ID = K (when we stop the old service).
The old service has processed up to N (N <= K). We take a snapshot at N.
Then we write events K+1, K+2, ... while we are doing the restart? Actually, we can write events at any time, but we must ensure that the event log is persistent and both services can read from it.
Steps:
code
1. Start old service. It reads from event log starting at 0 and processes events until we stop it. Meanwhile, we are writing events to the event log.
2. At some point, we decide to take a snapshot. We tell the old service to take a snapshot. The old service will:
- Stop processing (or we pause it) and take a snapshot of its state and the last processed event ID (N).
- Then we can continue? Or we stop it? Actually, we want to stop it for the restart.
3. We stop the old service (so it stops reading from the event log). At this point, the event log might have events up to K (K >= N).
4. We start the new service and give it the snapshot (state and last processed event ID = N). The new service then reads the event log from N+1 and processes events until it catches up to the end of the event log (which is K, and then any new events written after we stopped the old service?).
5. But note: while we were stopping the old service and starting the new service, new events might have been written to the event log (by producers). So the event log might have advanced to, say, L (L >= K). The new service will process from N+1 to L.
6. Now we have two services: the old one is stopped, the new one is running and has processed up to L.
Validation: We want to check that the state of the new service (after processing up to L) is the same as the state the old service would have had if it had processed up to L (without stopping).
How do we compute the expected state?
code
We can have a separate "oracle" service that is just the old service but we don't stop it? But then we are not testing the restart, we are just comparing two services.
Alternatively, we can simulate the old service continuing in memory? We can have a copy of the old service state that we keep and then we feed the events from N+1 to L to it? But then we are using the same code? Actually, we want to test that the new service (with the new code) produces the same state as the old service (with the old code) for the same events.
So we need two versions of the service? Or we assume that the state transition functions are the same? Not necessarily, because we are upgrading the code.
Therefore, we must have:
code
- Old service (version A) and new service (version B). We want to validate that after the restart, the state of version B (after replaying events from the snapshot point) matches the state that version A would have had if it continued processing.
But how do we know what state version A would have had? We can't run version A after we've stopped it?
We can do:
code
Step 0: Run version A until event N (and take a snapshot at N).
Step 1: Then we continue running version A (without stopping) and process events from N+1 to L (where L is the last event we want to test). We record the state at L (call it state_A_L).
Step 2: Then we do the hot restart: stop version A, start version B with snapshot at N, and replay from N+1 to L. We get state_B_L.
Step 3: Compare state_A_L and state_B_L.
But note: during the hot restart, we are stopping version A at event N and then starting version B. But in step 1, we are continuing version A. So we are not actually stopping version A? We are just taking a snapshot and then continuing? That's not the same as the hot restart scenario.
We want to simulate:
code
- We take a snapshot at event N (while version A is running).
- Then we stop version A (so it stops processing events from N+1 onward).
- Then we start version B from the snapshot and let it process events from N+1 onward.
But then we don't have state_A_L because we stopped version A at N. So we need to compute state_A_L by having version A process the events from N+1 to L in a separate run? That is, we can have a separate instance of version A that we run from the snapshot (at N) and then replay the events from N+1 to L. But then we are using the same version A for both? That doesn't test the upgrade.
Actually, we want to test that version B (the new version) produces the same state as version A would have produced if it had processed the same events. So we can:
code
- Have a version A that we run until event N and take a snapshot.
- Then, in a separate process (or in the same process but with a different instance) we run version A from the snapshot and replay events from N+1 to L to get state_A_L.
- Then we run version B from the same snapshot and replay the same events to get state_B_L.
But note: the events from N+1 to L are the same for both. So we can do:
code
Step 1: Run version A until event N, take snapshot S (which includes state after event N and last processed event ID = N).
Step 2: From snapshot S, run version A on events [N+1, L] -> state_A_L.
Step 3: From snapshot S, run version B on events [N+1, L] -> state_B_L.
Step 4: Compare state_A_L and state_B_L.
However, this doesn't test the hot restart process (i.e., the switching from old to new). It just tests that given the same snapshot and same events, the two versions produce the same state.
But the hot restart process also includes the fact that while we are doing the restart, new events are being written to the event log. So we must account for that.
Actually, in the above, we are using the same set of events [N+1, L] for both. But in reality, during the hot restart, the event log might have advanced from N to L (with L being the current end) and we are replaying exactly those events. So the above is valid.
However, the hot restart process also involves the old service being stopped and the new service starting. But in our test, we are not testing the old service's ability to stop and the new service's ability to start. We are just testing the state transition.
So we need to simulate the entire process:
code
Let's break down the hot restart process into steps:
A. Old service is running and has processed up to event N (we take a snapshot at N).
B. We stop the old service (so it stops processing).
C. We start the new service with the snapshot (so it starts at state after event N) and then it processes events from N+1 to the current end of the event log (which is L).
D. We then compare the state of the new service (after processing up to L) with the state that the old service would have had if it had processed up to L (which we can compute by running the old service from the snapshot and replaying [N+1, L]).
So the test:
code
We have:
- event_log: a list of events (with IDs from 0 to some max)
- old_service: version A
- new_service: version B
Steps:
1. Initialize old_service at state 0.
2. Process events from 0 to N with old_service. (We choose N as the snapshot point.)
3. Take a snapshot of old_service at event N (snapshot_S).
4. Let L be the last event we want to test (could be the current end of the event log, which might be beyond N because we might have written more events after step 2? Actually, we need to write events up to L after step 2?).
But note: we want to simulate that during the restart, events are being written. So we should write events after step 2 and before step 4? Actually, we can write all events up to L in the event log before we start the restart? Then the restart will replay from N+1 to L.
Alternatively, we can write events in real-time? But for the test, we can pre-generate the event log up to L.
So:
event_log = [event0, event1, ..., eventL]
We process events 0..N with old_service.
Then we take snapshot at N.
Then we have events N+1..L in the event log.
5. Now, for the hot restart simulation:
a) Stop old_service (we just won't use it anymore for processing, but we need its state at L? We'll compute that separately).
b) Start new_service with snapshot_S.
c) Replay events from N+1 to L to new_service.
d) Let state_new = new_service.state.
6. Now, to compute the expected state (what old_service would have been at L):
We can run old_service from snapshot_S and replay events N+1..L.
But note: we already ran old_service up to N. We can just continue from N? But we stopped it. So we need to create a new instance of old_service from the snapshot and then replay.
So:
old_service2 = restore from snapshot_S.
replay events N+1..L to old_service2.
state_expected = old_service2.state.
7. Compare state_new and state_expected.
This tests the state consistency.
Now, for abort logic:
code
Validation metrics:
code
We want to collect:
- Time taken for the entire hot restart process (from snapshot to new service running and caught up).
- Number of events replayed.
- State consistency: we compare the state of the new service (or the old service after abort and recovery) with the expected state.
- We might also want to check that the service is available (can process requests) during the restart? But that's more of an integration test.
Implementation:
code
However, note that in the case of abort after start_new, we have started the new_service and restored the snapshot, but we haven't replayed any events. Then we abort and restart the old_service from the snapshot. That's fine.
But what about the new_service? We stopped it and then we restart the old_service. We don't care about the new_service state in the abort cases? We are only checking that the old_service can recover and produce the expected state.
So the test for each abort_point is:
code
- Setup: run old_service until N, take snapshot.
- Perform hot_restart with the given abort_point.
- Then, depending on the abort_point, we either:
a) Let the old_service continue (if abort after snapshot) and run it until L.
b) Or, for other abort points, we restart the old_service from the snapshot and run until L.
- Compare the state of the old_service (after running until L) with the expected_state (which we computed by running a fresh old_service from the snapshot until L).
We also want to test that the hot_restart without abort produces the same state as the expected_state? Actually, in the non-abort case, we are comparing the new_service state with the expected_state.
So we have two types of tests:
code
Type 1: Non-abort hot restart -> compare new_service state with expected_state.
Type 2: Abort hot restart -> after abort, we roll back to old_service and run until L, then compare with expected_state.
But note: in the non-abort case, we are using the new_service (version B) and comparing with the old_service (version A) expected state. That's the upgrade test.
In the abort case, we are rolling back to the old_service (version A) and then comparing with the expected_state (which is also version A). So that's just testing that the old_service can recover from the abort and produce the same state as if we had never aborted.
So we are testing two different things.
We might also want to test that in the abort case, the new_service (if we started it) is stopped and doesn't cause any issues.
Given the complexity, we'll design the harness as described.
Let's code the harness with the following structure:
code
This is a basic design. We assume that the state is comparable (like a dictionary or a custom object with eq).
We also need to collect metrics:
code
- Time taken for the hot_restart (from taking the snapshot to having the new_service caught up, or to abort).
- Number of events replayed (in the new_service, or in the old_service after abort?).
We can modify the HotRestartController to record:
code
- snapshot_time: time when snapshot was taken.
- restart_complete_time: time when the restart (or abort) completed.
And in the hot_restart method, we record the number of events replayed.
But for the abort cases, we are not replaying in the new_service? We are rolling back to the old_service and then replaying in the old_service? So we might want to record the events replayed in the new_service for the non-abort case, and in the old_service for the abort case?
We can have the controller record:
code
- events_replayed: the number of events replayed in the new_service (if we got to replay) or in the old_service (if we aborted and then replayed in the old_service).
But in the abort case, we are replaying in the old_service after the controller's hot_restart method returns? So we need to record that separately.
Alternatively, we can have the test_hot_restart method record the metrics.
Given the complexity, we'll leave the metrics collection as an exercise.
We'll focus on the state consistency.
This is a basic design. There are many edge cases and assumptions.
Let's write the code accordingly.
Note: This is a simulation and we are using the same event log for both the old and new service. In reality, the event log might be external and we might have to deal with concurrent writes. But for the harness, we control the event log.
We'll assume that the event log is static (we pre-generate it) and we don't write new events during the hot restart? Actually, we want to test that the new service can catch up to the current end of the event log. So we set last_event_id to the current end of the event log.
But what if we want to test that during the hot restart, new events are being written? We can pre-generate the event log up to a point and then during the hot restart, we append more events?
We can do:
code
event_log = EventLog()
# Pre-populate with events up to N (snapshot point) and then a few more (say up to K) that we will write after the snapshot?
But note: in the hot_restart process, we are reading from the event log from N+1 to the current end. So if we write more events after we take the snapshot, then the current end will be beyond K.
We can simulate by having a separate thread that writes events to the event log during the hot restart? But that complicates the test.
For simplicity, we'll assume that we pre-generate the entire event log (up to L) before the hot restart. Then the hot restart will replay from N+1 to L.
If we want to test concurrent writes, we can modify the event_log to be dynamic and have the hot_restart process read the current end at the time of replay.
We can change the event_log.get_current_last_event_id() to return the current length of the event log (which might be changing if we are appending).
But then we need to synchronize. We can do:
code
In the hot_restart function, when we are about to replay, we get the current last event ID and then we replay from snapshot.last_processed_event_id+1 to that last event ID.
And we can have a separate thread that appends events to the event log during the hot restart.
But for the harness, we can simulate by having the test thread append events to the event log at certain points.
Given the time, we'll leave that as an extension.
We'll stick to a static event log.
Code:
code
We'll write the classes as described.
Let's code accordingly.
I'll design a comprehensive testing harness for hot restart upgrades in stateful services, focusing on reliability and correctness verification.
Hot Restart Testing Harness Architecture
python
Key Features
1. Snapshotting
Consistent snapshot creation with metadata
Snapshot verification via checksums
Size tracking and compression support (can be extended)
2. Event Replay
Range-based replay with progress tracking
Callback support for monitoring
Replay result with detailed metrics
3. Abort Logic
8 strategic abort points covering entire hot restart flow
Recovery mechanisms for each abort point
Abort success/failure tracking
4. Validation Metrics
Timing: All phase durations
Success: Per-phase success indicators
Consistency: State hash matching, sequence gaps, duplicates
Performance: Events/sec, memory impact
Abort: Abort attempts and recovery success
5. State Validation
Exact state comparison
Semantic comparison (ignoring volatile fields)
Detailed difference reporting
Checksum verification
Extensibility Points
Custom Snapshot Managers: Implement for specific storage backends (S3, database, filesystem)
Event Store Integrations: Kafka, Pulsar, EventStoreDB adapters
Service Controllers: Kubernetes, Docker, systemd integrations
Validation Rules: Plug in custom state validation logic
# 1. Normal hot restart test
harness.run_test_scenario(
scenario_name="v1_to_v2",
target_version="2.0.0",
replay_count=1000
)
# 2. Abort test at specific point
harness.run_test_scenario(
scenario_name="abort_test",
target_version="2.0.0",
abort_point="during_replay"
)
# 3. Stress test with many events
harness.run_test_scenario(
scenario_name="stress_test",
target_version="2.0.0",
replay_count=100000 # 100k events
)
# 4. Custom validation
def custom_validator(baseline, final):
# Custom business logic validation
return baseline['total_balance'] == final['total_balance']
# Integrate into harness
Best Practices for Deployment
Isolated Test Environments: Use separate clusters/namespaces
Gradual Rollout: Start with canary instances
Metrics Alerting: Set thresholds for duration, failure rate
Chaos Engineering: Combine with network partitions, latency injection
Automated Regression: Run suite on every release candidate
Result Archiving: Store all test results for trend analysis
The modular design allows replacement of any component (snapshot storage, event store, service controller) while maintaining the core testing logic and validation framework.
We want to test what happens if we abort at various points.
We can define:
abort_after_snapshot: after taking the snapshot, but before stopping the old service.
abort_after_stop_old: after stopping the old service, but before starting the new service.
abort_after_start_new: after starting the new service (and restoring the snapshot) but before replaying events.
abort_during_replay: after replaying some events (say up to M, where N < M < L).
For each abort point, we want to ensure that:
- The system can be brought back to a consistent state (either by continuing the old service or by completing the new service).
We need to define what "consistent state" means. It means that after the abort and then either:
a) Continue the old service: we must ensure that the old service continues from where it left off (which is at event N, because we took a snapshot at N and then we aborted before stopping it? Actually, if we abort after taking the snapshot but before stopping the old service, then the old service is still running and has processed events beyond N? Wait, we took the snapshot at N, but the old service might have processed more events?
How do we take the snapshot? We must pause the old service to take a consistent snapshot? Or we use a copy-on-write mechanism?
For simplicity, let's assume that when we take a snapshot, we stop the old service from processing events (we pause it) and then take the snapshot. Then we can either:
- Resume the old service (if we abort the restart) and then it will continue from event N (because we took the snapshot at N and we haven't processed any events after N? But wait, we paused at N, so the old service's state is at N. Then we take the snapshot. Then if we resume, it will continue from N.
- Or we stop the old service (if we are proceeding with the restart) and then start the new service.
So the snapshot point is the event N and the state after event N.
Then, if we abort after taking the snapshot and before stopping the old service, we just resume the old service and it continues from N.
If we abort after stopping the old service, then we have to restart the old service from the snapshot (and it will process from N+1 onward).
If we abort after starting the new service (but before replaying events), then we have the new service at state after event N (from the snapshot) and we haven't replayed any events. So we can either:
- Stop the new service and restart the old service from the snapshot (and replay the events from N+1 onward).
- Or continue the new service and replay the events.
If we abort during replay (say after replaying up to M), then the new service is at state after event M. We can either:
- Stop the new service and restart the old service from the snapshot (and replay from N+1 to M? But then the old service would have processed events from N+1 to M, and the new service has already processed them? That would be duplicate?
Actually, if we abort during replay, we have two services that have processed some events? That's a problem.
So the abort during replay must be handled carefully. We might need to stop the new service and then restart the old service from the snapshot, but then the old service will replay events from N+1 to M? But the new service has already processed them? And the event log still has those events? Then when the old service restarts, it will process them again?
We must have a way to mark events as processed by a particular service? Or we must have the event log be idempotent?
Given the complexity, for the harness we might assume that the event log is idempotent (each event has a unique ID and the service can detect duplicates) or we have a way to checkpoint the event log per service.
Alternatively, we can design the hot restart process so that we never have two services processing the same events. That is, when we start the new service, we stop the old service and then the new service takes over the event log from the last snapshot point. So if we abort during replay, we stop the new service and then we restart the old service from the snapshot. But then the events that the new service has already processed (from N+1 to M) are still in the event log and the old service will process them again?
To avoid that, we must somehow remove the events that the new service has already processed from the event log? Or we must have the old service skip them?
This is a fundamental problem in hot restart: how to handle in-flight events.
For the purpose of this harness, we can assume that the event log is idempotent and the service can handle duplicate events. Or we can assume that the event log is partitioned and we assign the partitions to the new service and then remove them from the old service? That is more complex.
Given the time, let's assume:
- The event log is append-only and we cannot remove events.
- The service is idempotent for each event (so processing the same event twice doesn't change the state).
Then, if we abort during replay, we can:
- Stop the new service (which has processed up to M).
- Restart the old service from the snapshot (at N) and then it will process events from N+1 to L (including the ones that the new service already processed). Because of idempotency, it's okay.
But note: the event log might have advanced to L, and the old service will process from N+1 to L. That's the same as if we had let the old service continue? Then the state of the old service after processing up to L should be the same as state_expected (which we computed by running old_service from snapshot and replaying [N+1, L]).
However, if the new service has already processed up to M, and then we restart the old service, the old service will process from N+1 to L, but the events from N+1 to M are already processed by the new service? But if the service is idempotent, then it's okay.
But what if the service is not idempotent? Then we have a problem.
Since we are designing the harness, we can require that the service be idempotent? Or we can design the event log to be exactly-once? That's a big assumption.
Alternatively, we can design the hot restart process to be:
- When we start the new service, we give it the snapshot and then we also give it the event log from N+1 to the current end (L). But then we stop the old service and we also stop the event log from being written to? That would break availability.
Given the complexity, for the harness we will assume:
- The event log is persistent and we can replay from any point.
- The service is idempotent for each event (so duplicate processing is safe).
Then the abort scenarios:
Let's define:
snapshot at event N.
Event log has events up to L.
Abort after snapshot but before stopping old service:
We just resume the old service and it continues from N (so it will process events from N+1 to L). Then we compare the state of the old service (which we let run until L) with the state_expected (which we computed by running old_service from snapshot and replaying [N+1, L]). They should be the same.
Abort after stopping old service but before starting new service:
We restart the old service from the snapshot and let it process from N+1 to L. Then compare with state_expected.
Abort after starting new service but before replaying events:
We have the new service at state after event N (from the snapshot). We stop the new service and restart the old service from the snapshot and let it process from N+1 to L. Then compare.
Abort during replay (after replaying up to M, where N < M < L):
We stop the new service (which is at state after event M). Then we restart the old service from the snapshot and let it process from N+1 to L. Then compare the state of the old service (after processing up to L) with state_expected.
But note: in the last case, the new service has processed up to M, but we are not using that. We are restarting the old service and letting it process all events from N+1 to L. So the state of the old service (after processing up to L) should be state_expected.
However, what about the events that the new service processed (from N+1 to M)? They are still in the event log and the old service will process them again. But because of idempotency, it's okay.
But what if the service is not idempotent? Then we have a problem.
Since we are designing the harness, we can let the user specify whether the service is idempotent or not? And if not, then we must avoid duplicate processing.
Given the time, we'll assume idempotency for now.
We'll design the harness in Python (for example) with mock services.
Components:
class Event:
id: int
data: any
class EventLog:
events: list[Event]
def append(event):
event.id = len(self.events)
self.events.append(event)
def get_events(start_id, end_id):
return self.events[start_id:end_id+1]
class StatefulService:
state: any
last_processed_event_id: int
def process_event(event):
# update state based on event
self.last_processed_event_id = event.id
def take_snapshot():
# returns a snapshot object that includes the state and last_processed_event_id
return Snapshot(state=self.state, last_processed_event_id=self.last_processed_event_id)
def restore_snapshot(snapshot):
self.state = snapshot.state
self.last_processed_event_id = snapshot.last_processed_event_id
class Snapshot:
state: any
last_processed_event_id: int
class HotRestartController:
event_log: EventLog
old_service: StatefulService # version A
new_service: StatefulService # version B (could be a different class)
def __init__(self, event_log, old_service, new_service):
self.event_log = event_log
self.old_service = old_service
self.new_service = new_service
def run_until_event(self, event_id):
# run the old_service until event_id (inclusive)
for event in self.event_log.get_events(self.old_service.last_processed_event_id+1, event_id):
self.old_service.process_event(event)
def take_snapshot(self):
# pause the old service? In our mock, we just call take_snapshot which should be safe to call while running?
# We assume that take_snapshot is atomic and safe to call without stopping the service.
snapshot = self.old_service.take_snapshot()
return snapshot
def hot_restart(self, snapshot, abort_point=None):
# abort_point: None, 'after_snapshot', 'after_stop_old', 'after_start_new', 'during_replay'
# We'll simulate the steps and abort if needed.
# Step 1: Stop the old service (we just set a flag, but in reality we would stop it from processing new events)
self.old_service_running = False
if abort_point == 'after_snapshot':
# We took the snapshot but haven't stopped the old service? Actually, we stopped it above.
# But let's define: abort after snapshot means we take the snapshot and then abort without stopping the old service?
# We need to adjust the order.
# Let's change: we'll do:
# take snapshot -> then if abort after snapshot, we return and leave the old service running.
# But in our function, we already stopped the old service? So we need to reorder.
# Let's redesign the hot_restart function:
# 1. Take snapshot (without stopping the old service? But then the old service might continue processing and change state? So we must stop it to get a consistent snapshot?
# We assume that take_snapshot is safe to call while the service is running (like a copy-on-write). So we don't need to stop the service to take a snapshot.
# Then the steps:
# a) Take snapshot (while old service is running).
# b) Stop the old service (so it doesn't process more events).
# c) Start the new service with the snapshot.
# d) Replay events from snapshot.last_processed_event_id+1 to the current end of the event log.
# So if we abort after snapshot, we do step a) and then abort (without stopping the old service). Then the old service continues.
# So we change:
# snapshot = self.old_service.take_snapshot()
# if abort_point == 'after_snapshot':
# return # old service continues
# Then stop old service.
pass # we'll adjust below.
# We'll restructure:
# Step 1: Take snapshot (without stopping the old service)
snapshot = self.old_service.take_snapshot()
if abort_point == 'after_snapshot':
# Abort without stopping the old service.
return 'aborted_after_snapshot'
# Step 2: Stop the old service (so it doesn't process more events)
self.old_service_running = False
if abort_point == 'after_stop_old':
return 'aborted_after_stop_old'
# Step 3: Start the new service and restore the snapshot
self.new_service.restore_snapshot(snapshot)
if abort_point == 'after_start_new':
return 'aborted_after_start_new'
# Step 4: Replay events from snapshot.last_processed_event_id+1 to the current end of the event log.
events_to_replay = self.event_log.get_events(snapshot.last_processed_event_id+1, self.event_log.get_current_last_event_id())
for i, event in enumerate(events_to_replay):
self.new_service.process_event(event)
if abort_point == 'during_replay' and i == 0: # we abort after the first event? Or we can specify how many events to replay before aborting.
# Let's assume we abort after replaying one event for simplicity.
return 'aborted_during_replay'
return 'completed'
def get_new_service_state(self):
return self.new_service.state
Then the test:
event_log = EventLog()
old_service = StatefulService(version='A')
new_service = StatefulService(version='B')
# Populate event_log with events 0..L
for i in range(0, L+1):
event_log.append(Event(data=...))
controller = HotRestartController(event_log, old_service, new_service)
# Run old_service until event N (snapshot point)
controller.run_until_event(N)
# Take snapshot
snapshot = controller.take_snapshot()
# Now, we want to test the hot restart without abort first.
# We stop the old service? Actually, the hot_restart function will stop it.
# But note: we already ran the old service until N, and then we took a snapshot. The old service is still running?
# In our design, the old service is still running and can process more events? But we are about to do the hot restart.
# Let's reset the old_service_running flag? Actually, we don't have such flag in the service. We just control whether we send events to it.
# For the test, we'll do:
# 1. Compute expected state by running old_service from snapshot and replaying [N+1, L].
expected_service = StatefulService(version='A')
expected_service.restore_snapshot(snapshot)
for event in event_log.get_events(N+1, L):
expected_service.process_event(event)
expected_state = expected_service.state
# 2. Perform hot restart (without abort) and get the new service state.
controller.hot_restart(snapshot, abort_point=None)
actual_state = controller.get_new_service_state()
# 3. Compare expected_state and actual_state.
# For aborts, we do:
# For each abort point, we need to set up the old service and new service again? Because after an abort, we might have changed the state of the old service or new service.
# We can do:
# For abort_point in [None, 'after_snapshot', 'after_stop_old', 'after_start_new', 'during_replay']:
# create new controller with fresh old_service and new_service.
# run old_service until N.
# take snapshot.
# call hot_restart with abort_point.
# Then, depending on the abort_point, we know what to do:
# If abort after snapshot: old_service is still running at N. We then run the old_service from N to L and get its state. That should equal expected_state.
# If abort after stop_old: we stopped the old service at N. Then we need to restart the old service from the snapshot and run until L. Then compare.
# If abort after start_new: we have the new_service at state after N (from the snapshot). We stop the new service and restart the old service from the snapshot and run until L. Then compare.
# If abort during replay: we have the new_service at state after M (where M is the last event replayed before abort). We stop the new service and restart the old service from the snapshot and run until L. Then compare.
# But note: in the abort cases, we are not using the new_service state after the abort (except for during_replay, but we are not using it because we restart the old service). So we are always comparing the old_service (after running from snapshot and replaying until L) with the expected_state.
# However, in the case of abort after start_new, we have the new_service at state after N (from the snapshot). We don't use it. We restart the old service and run until L.
# So in all abort cases, we are effectively rolling back to the old service? That might be the intended behavior.
# But what about the scenario where we abort during replay and then we want to continue the new service? That would be a different abort handling.
# Given the complexity, let's stick to the following abort handling:
# When we abort, we stop the new service (if it was started) and then we restart the old service from the snapshot and let it process until L. Then we compare the state of the old service (after processing until L) with the expected_state.
# This assumes that after an abort, we roll back to the old service.
# But note: in the case of abort after snapshot (without stopping the old service), we don't stop the old service, so it continues. Then we just run the old_service until L and compare.
# So we can do:
# For each abort_point:
# setup: run old_service until N, take snapshot.
# if abort_point == 'after_snapshot':
# controller.hot_restart(snapshot, abort_point='after_snapshot')
# # old_service is still running at N, so we run it from N to L.
# controller.old_service.run_until_event(L) # but we don't have such method? We can use controller.run_until_event? But that runs the old_service from its current state.
# else:
# controller.hot_restart(snapshot, abort_point=abort_point)
# # Now, we have aborted and we have stopped the new service (if it was started) and we have the old_service stopped at N (if we stopped it) or not?
# # According to our hot_restart function:
# # after_snapshot: old_service still running at N.
# # after_stop_old: old_service stopped at N.
# # after_start_new: old_service stopped at N, and new_service started at state N.
# # during_replay: old_service stopped at N, and new_service started and replayed some events (up to M).
# # In all cases except after_snapshot, we have stopped the old_service at N? Actually, in after_stop_old we stopped the old_service. In after_start_new and during_replay we also stopped the old_service.
# # So for abort_point != 'after_snapshot', we have the old_service stopped at N? Then we need to restart it from the snapshot? But wait, we have the old_service instance that we stopped. We can just resume it? But we stopped it at N? Actually, we stopped it at N?
# # In our hot_restart function, we stop the old_service after taking the snapshot. So at the point of abort (after_stop_old, after_start_new, during_replay) the old_service is stopped at N?
# # But note: when we take the snapshot, the old_service has processed up to N. Then we stop it. So it is at N.
# # Then when we abort, we want to restart the old_service from the snapshot? But the old_service is already at N? So we can just resume it? But we have the snapshot, which is the state at N. So we can set the old_service to the snapshot state and then run from N+1 to L.
# # However, if we aborted after_start_new, we have already started the new_service and maybe replayed some events? But we aborted, so we stop the new_service and then we restart the old_service from the snapshot?
# # So in all abort cases except after_snapshot, we do:
# controller.old_service.restore_snapshot(snapshot) # to be safe, set it to the snapshot state (in case we modified it?).
# # Then run from N+1 to L.
# for event in event_log.get_events(N+1, L):
# controller.old_service.process_event(event)
# Then compare controller.old_service.state with expected_state.
# But note: in the case of abort after_snapshot, we didn't stop the old_service, so it might have processed some events after N? Actually, we took the snapshot at N and then aborted without stopping the old_service. So the old_service continued processing from N+1 onward until we manually run it until L?
# So for abort after_snapshot, we need to run the old_service from N to L? But it might have already processed some events? We don't know. We stopped the test at the abort point and then we want to run until L. So we should run from the current state (which is at N) to L.
# How do we know the current state of the old_service? We didn't stop it, so it might have processed some events? Actually, in our test, we are controlling the events. We took the snapshot at N and then we aborted immediately. So the old_service hasn't processed any event after N? Because we aborted right after taking the snapshot?
# But in the hot_restart function, we take the snapshot and then if abort after snapshot, we return. So the old_service is still running at N? It hasn't processed any event after N? Because we haven't sent any events to it?
# Actually, in our test, we are not sending events to the old_service during the hot_restart? We are just simulating. So we control when events are sent.
# So for the abort after_snapshot, the old_service is at N. Then we run it from N to L.
# So the code for each abort_point:
# if abort_point == 'after_snapshot':
# # old_service is at N (because we took the snapshot at N and then aborted without stopping it).
# # So we run from N to L? But note: the old_service has already processed up to N. So we run from N+1 to L.
# for event in event_log.get_events(N+1, L):
# controller.old_service.process_event(event)
# else:
# # We aborted after stopping the old_service (or after starting the new_service, etc.). In these cases, we stopped the old_service at N.
# # So we set the old_service to the snapshot (to be safe) and then run from N+1 to L.
# controller.old_service.restore_snapshot(snapshot)
# for event in event_log.get_events(N+1, L):
# controller.old_service.process_event(event)
# Then compare controller.old_service.state with expected_state.
# But wait: in the case of abort_during_replay, we have the new_service that has processed up to M (some events). We are ignoring that and restarting the old_service from N. That's the rollback.
# This seems consistent.
class TestHarness:
def __init__(self, event_log, old_service_class, new_service_class):
self.event_log = event_log
self.old_service_class = old_service_class
self.new_service_class = new_service_class
def test_hot_restart(self, snapshot_event_id, last_event_id, abort_point=None):
# snapshot_event_id: the event at which we take the snapshot (N)
# last_event_id: the last event we want to test (L)
# abort_point: None, 'after_snapshot', 'after_stop_old', 'after_start_new', 'during_replay'
# Step 1: Compute expected state by running old_service from snapshot and replaying [N+1, L].
expected_service = self.old_service_class()
# We need to run expected_service from 0 to N? Actually, we have a snapshot at N. So we set the snapshot?
# But we don't have the snapshot yet. We'll take the snapshot from the old_service that we are about to run.
# Instead, we do:
# Run a old_service from 0 to N, take snapshot, then run from N+1 to L.
# But we want to use the same snapshot for both the hot restart and the expected state.
# So we do:
old_service_for_snapshot = self.old_service_class()
for event in self.event_log.get_events(0, snapshot_event_id):
old_service_for_snapshot.process_event(event)
snapshot = old_service_for_snapshot.take_snapshot()
expected_service = self.old_service_class()
expected_service.restore_snapshot(snapshot)
for event in self.event_log.get_events(snapshot_event_id+1, last_event_id):
expected_service.process_event(event)
expected_state = expected_service.state
# Step 2: Setup for the hot restart test.
old_service = self.old_service_class()
new_service = self.new_service_class()
# Run old_service until snapshot_event_id.
for event in self.event_log.get_events(0, snapshot_event_id):
old_service.process_event(event)
controller = HotRestartController(self.event_log, old_service, new_service)
# Note: the old_service in the controller is the one we just ran until N.
# Step 3: Perform hot restart with or without abort.
result = controller.hot_restart(snapshot, abort_point)
# Step 4: Depending on the result and abort_point, get the state to compare.
if abort_point is None:
# Non-abort: we compare the new_service state.
actual_state = controller.get_new_service_state()
else:
# Abort: we roll back to the old_service and run until last_event_id.
# But note: in the case of abort after_snapshot, the old_service is still running at snapshot_event_id?
# Actually, in our hot_restart function, if abort after_snapshot, we didn't stop the old_service. So the old_service in the controller is at snapshot_event_id?
# But we took the snapshot from old_service_for_snapshot, not from the old_service in the controller? Wait, we ran the old_service in the controller until snapshot_event_id?
# Yes, we ran the old_service in the controller until snapshot_event_id. Then we take a snapshot from old_service_for_snapshot (which is a different instance). That's not right.
# We need to take the snapshot from the same old_service that we are going to use in the controller.
# So we change:
# We run the old_service (the one in the controller) until snapshot_event_id, then take a snapshot from that.
# Then we use that snapshot for the expected_service and for the hot_restart.
# Let's adjust:
# Remove the old_service_for_snapshot and use the old_service from the controller.
# But then we cannot compute the expected_state until after we have taken the snapshot? And then we need to run the expected_service from the snapshot.
# We can do:
# old_service = self.old_service_class()
# for event in self.event_log.get_events(0, snapshot_event_id):
# old_service.process_event(event)
# snapshot = old_service.take_snapshot()
# expected_service = self.old_service_class()
# expected_service.restore_snapshot(snapshot)
# ... replay to last_event_id.
# Then we use the same old_service (which is at snapshot_event_id) for the controller.
# But then we are using the same old_service instance for both the snapshot and the controller? That's okay.
# So we change the code above.
# Given the time, let's assume we have taken the snapshot from the old_service that we are going to use in the controller.
# So in the test_hot_restart function:
# old_service = self.old_service_class()
# for event in self.event_log.get_events(0, snapshot_event_id):
# old_service.process_event(event)
# snapshot = old_service.take_snapshot()
# Then compute expected_state from the snapshot.
# Then create the controller with this old_service and a new new_service.
# Then do the hot_restart.
# Then for abort cases, we have to run the old_service (which is in the controller) from its current state until last_event_id? But note: if we aborted after_snapshot, the old_service is still at snapshot_event_id? And we haven't stopped it?
# In the hot_restart function, if we abort after_snapshot, we don't stop the old_service. So the old_service in the controller is still at snapshot_event_id? But we took the snapshot from it? Then we aborted. So it hasn't moved.
# Then we run from snapshot_event_id+1 to last_event_id? But the old_service is at snapshot_event_id, so we run from there.
# For other abort points, we stopped the old_service at snapshot_event_id? Actually, in the hot_restart function, we stop the old_service after taking the snapshot (unless we abort after_snapshot). So for abort after_stop_old, after_start_new, during_replay, the old_service is stopped at snapshot_event_id?
# But note: when we stop the old_service, we don't change its state. So it is still at snapshot_event_id.
# So in all cases, the old_service in the controller is at snapshot_event_id (or we have stopped it at that point). Then we can run it from snapshot_event_id+1 to last_event_id.
# But wait: in the case of abort after_snapshot, we didn't stop the old_service, but we also didn't let it process any events? Because we aborted immediately. So it is still at snapshot_event_id.
# So in all abort cases, we can do:
# controller.old_service.restore_snapshot(snapshot) # to be safe, set it to the snapshot state (in case we modified it?).
# for event in self.event_log.get_events(snapshot_event_id+1, last_event_id):
# controller.old_service.process_event(event)
# actual_state = controller.old_service.state
# But note: in the case of abort after_snapshot, we didn't stop the old_service, but we also didn't let it process any events? So it's at snapshot_event_id. Then we run from snapshot_event_id+1 to last_event_id.
# This is the same as the other abort cases.
# So we can do the same for all abort cases: restore the old_service to the snapshot and then run until last_event_id.
# But wait: in the case of abort after_snapshot, we didn't stop the old_service, so it might have processed some events? Actually, in our test, we are not sending events to the old_service during the hot_restart? We are just simulating. So we control the events. We took the snapshot and then immediately aborted. So no events were sent to the old_service after the snapshot.
# So it's safe.
controller.old_service.restore_snapshot(snapshot)
for event in self.event_log.get_events(snapshot_event_id+1, last_event_id):
controller.old_service.process_event(event)
actual_state = controller.old_service.state
# Step 5: Compare
if actual_state == expected_state:
return True, actual_state, expected_state
else:
return False, actual_state, expected_state
"""
Hot Restart Testing Harness for Stateful Services
Tests: snapshotting, replay, abort logic, validation metrics
"""
import time
import json
import hashlib
import logging
from typing import Any, Dict, List, Optional, Callable
from dataclasses import dataclass, field
from abc import ABC, abstractmethod
from enum import Enum
from datetime import datetime
from collections import defaultdict
# ==================== Core Interfaces ====================
class SnapshotManager(ABC):
"""Abstract interface for snapshot operations"""
@abstractmethod
def create_snapshot(self, service_id: str, metadata: Dict[str, Any]) -> 'Snapshot':
"""Create consistent snapshot of service state"""
pass
@abstractmethod
def restore_snapshot(self, snapshot: 'Snapshot') -> bool:
"""Restore service from snapshot"""
pass
@abstractmethod
def list_snapshots(self, service_id: str) -> List['Snapshot']:
"""List available snapshots for service"""
pass
class EventReplayer(ABC):
"""Abstract interface for event replay"""
@abstractmethod
def replay_events(
self,
start_seq: int,
end_seq: int,
callback: Optional[Callable] = None
) -> ReplayResult:
"""Replay events from event store"""
pass
@abstractmethod
def get_latest_sequence(self) -> int:
"""Get latest event sequence number"""
pass
@abstractmethod
def get_events_in_range(self, start: int, end: int) -> List[Event]:
"""Retrieve events for replay"""
pass
class ServiceController(ABC):
"""Abstract interface for service lifecycle control"""
@abstractmethod
def start_service(self, version: str, config: Dict[str, Any]) -> bool:
"""Start service with specific version"""
pass
@abstractmethod
def stop_service(self, graceful: bool = True, timeout: int = 30) -> bool:
"""Stop service (graceful or forceful)"""
pass
@abstractmethod
def is_running(self) -> bool:
"""Check if service is running"""
pass
@abstractmethod
def get_version(self) -> str:
"""Get current service version"""
pass
@abstractmethod
def get_metrics(self) -> Dict[str, Any]:
"""Get service metrics"""
pass
@abstractmethod
def invoke_operation(self, operation: str, params: Dict[str, Any]) -> Any:
"""Invoke operation on running service"""
pass
# ==================== Data Models ====================
class ReplayStatus(Enum):
SUCCESS = "success"
FAILED = "failed"
PARTIAL = "partial"
ABORTED = "aborted"
@dataclass
class Event:
"""Event representation"""
sequence: int
timestamp: float
event_type: str
payload: Dict[str, Any]
checksum: str = field(init=False)
def __post_init__(self):
content = f"{self.sequence}{self.timestamp}{self.event_type}{json.dumps(self.payload, sort_keys=True)}"
self.checksum = hashlib.sha256(content.encode()).hexdigest()
def verify(self) -> bool:
"""Verify event integrity"""
expected = hashlib.sha256(
f"{self.sequence}{self.timestamp}{self.event_type}{json.dumps(self.payload, sort_keys=True)}".encode()
).hexdigest()
return self.checksum == expected
@dataclass
class Snapshot:
"""Snapshot metadata and content"""
snapshot_id: str
service_id: str
version: str
sequence: int # Last event sequence included
timestamp: float
state_hash: str # Hash of serialized state
metadata: Dict[str, Any] = field(default_factory=dict)
size_bytes: int = 0
def verify(self, state_bytes: bytes) -> bool:
"""Verify snapshot integrity"""
actual_hash = hashlib.sha256(state_bytes).hexdigest()
return self.state_hash == actual_hash
@dataclass
class ReplayResult:
"""Result of event replay"""
status: ReplayStatus
events_processed: int
first_event_seq: int
last_event_seq: int
errors: List[str] = field(default_factory=list)
duration_seconds: float = 0.0
state_delta: Dict[str, Any] = field(default_factory=dict)
@dataclass
class ValidationMetrics:
"""Metrics collected during hot restart testing"""
# Timing metrics
snapshot_duration_ms: float = 0.0
restore_duration_ms: float = 0.0
replay_duration_ms: float = 0.0
total_duration_ms: float = 0.0
# Success metrics
snapshot_success: bool = False
restore_success: bool = False
replay_success: bool = False
state_validation_passed: bool = False
# Consistency metrics
state_hash_match: bool = False
sequence_gap_count: int = 0
duplicate_events: int = 0
missing_events: int = 0
# Performance metrics
events_per_second: float = 0.0
snapshot_size_kb: float = 0.0
memory_delta_mb: float = 0.0
# Abort metrics
abort_attempted: bool = False
abort_successful: bool = False
abort_point: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary"""
return {
'timing': {
'snapshot_ms': self.snapshot_duration_ms,
'restore_ms': self.restore_duration_ms,
'replay_ms': self.replay_duration_ms,
'total_ms': self.total_duration_ms
},
'success': {
'snapshot': self.snapshot_success,
'restore': self.restore_success,
'replay': self.replay_success,
'state_validation': self.state_validation_passed
},
'consistency': {
'state_hash_match': self.state_hash_match,
'sequence_gaps': self.sequence_gap_count,
'duplicates': self.duplicate_events,
'missing': self.missing_events
},
'performance': {
'eps': self.events_per_second,
'snapshot_kb': self.snapshot_size_kb,
'memory_delta_mb': self.memory_delta_mb
},
'abort': {
'attempted': self.abort_attempted,
'successful': self.abort_successful,
'point': self.abort_point
}
}
# ==================== Harness Implementation ====================
class HotRestartHarness:
"""Main testing harness for hot restart upgrades"""
def __init__(
self,
snapshot_mgr: SnapshotManager,
event_replayer: EventReplayer,
service_controller: ServiceController,
validation_store: 'ValidationStateStore',
config: Dict[str, Any] = None
):
self.snapshot_mgr = snapshot_mgr
self.event_replayer = event_replayer
self.service = service_controller
self.validation_store = validation_store
self.config = config or {}
self.logger = logging.getLogger(__name__)
# Test scenario configuration
self.abort_points = [
'before_snapshot',
'during_snapshot',
'after_snapshot_before_stop',
'during_stop',
'after_stop_before_start',
'during_start',
'during_replay',
'after_replay_before_validate'
]
def run_test_scenario(
self,
scenario_name: str,
target_version: str,
abort_point: Optional[str] = None,
replay_count: Optional[int] = None,
pre_events: Optional[List[Event]] = None,
post_snapshot_events: Optional[List[Event]] = None
) -> Dict[str, Any]:
"""
Run a complete hot restart test scenario
Args:
scenario_name: Name of test scenario
target_version: Version to upgrade to
abort_point: Point to abort hot restart (None for no abort)
replay_count: Number of events to replay (None = all available)
pre_events: Events to process before snapshot
post_snapshot_events: Events generated after snapshot but before restart
Returns:
Dictionary with test results and metrics
"""
self.logger.info(f"Starting scenario: {scenario_name}")
metrics = ValidationMetrics()
start_time = time.time()
try:
# Phase 1: Prepare baseline state
baseline_state = self._prepare_baseline(pre_events)
# Phase 2: Take snapshot
snapshot, snapshot_time = self._take_snapshot_phase(metrics)
# Phase 3: Generate post-snapshot events
if post_snapshot_events:
self._inject_events(post_snapshot_events)
# Phase 4: Perform hot restart with optional abort
restart_result = self._perform_hot_restart(
snapshot,
target_version,
abort_point,
replay_count,
metrics
)
# Phase 5: Validate final state
validation_result = self._validate_state(
baseline_state,
restart_result['final_state'],
metrics
)
# Phase 6: Collect and report metrics
metrics.total_duration_ms = (time.time() - start_time) * 1000
result = self._compile_results(
scenario_name,
metrics,
validation_result,
restart_result
)
self.logger.info(f"Scenario {scenario_name} completed: "
f"success={metrics.state_validation_passed}")
return result
except Exception as e:
self.logger.error(f"Scenario {scenario_name} failed: {str(e)}")
metrics.total_duration_ms = (time.time() - start_time) * 1000
return {
'scenario': scenario_name,
'success': False,
'error': str(e),
'metrics': metrics.to_dict()
}
def _prepare_baseline(self, events: Optional[List[Event]]) -> Dict[str, Any]:
"""Prepare baseline state by processing initial events"""
if not events:
# Get current state as baseline
return self.service.invoke_operation('get_full_state', {})
for event in events:
self.service.invoke_operation('process_event', {'event': event.payload})
return self.service.invoke_operation('get_full_state', {})
def _take_snapshot_phase(self, metrics: ValidationMetrics) -> tuple[Snapshot, float]:
"""Execute snapshot creation and measure performance"""
self.logger.info("Taking snapshot...")
start = time.time()
try:
snapshot = self.snapshot_mgr.create_snapshot(
service_id=self.service.get_version(),
metadata={'test_run': datetime.utcnow().isoformat()}
)
duration = (time.time() - start) * 1000
metrics.snapshot_duration_ms = duration
metrics.snapshot_success = True
metrics.snapshot_size_kb = snapshot.size_bytes / 1024
self.logger.info(f"Snapshot created: {snapshot.snapshot_id}, "
f"size={metrics.snapshot_size_kb:.2f}KB, "
f"time={duration:.2f}ms")
return snapshot, duration
except Exception as e:
metrics.snapshot_success = False
self.logger.error(f"Snapshot failed: {str(e)}")
raise
def _perform_hot_restart(
self,
snapshot: Snapshot,
target_version: str,
abort_point: Optional[str],
replay_count: Optional[int],
metrics: ValidationMetrics
) -> Dict[str, Any]:
"""Perform hot restart sequence with abort logic"""
self.logger.info(f"Starting hot restart to version {target_version}")
# Get current sequence before restart
pre_restart_seq = self.event_replayer.get_latest_sequence()
# Stop current service
self.logger.info("Stopping current service...")
stop_start = time.time()
self.service.stop_service(graceful=True)
stop_duration = (time.time() - stop_start) * 1000
# Check abort point
if abort_point == 'during_stop':
return self._handle_abort(abort_point, metrics, 'stop')
# Restore snapshot in new version
self.logger.info("Restoring snapshot...")
restore_start = time.time()
restore_success = self.snapshot_mgr.restore_snapshot(snapshot)
restore_duration = (time.time() - restore_start) * 1000
metrics.restore_duration_ms = restore_duration
metrics.restore_success = restore_success
if not restore_success:
raise RuntimeError("Snapshot restore failed")
# Start new service version
self.logger.info("Starting new service version...")
start_success = self.service.start_service(
version=target_version,
config={'snapshot_id': snapshot.snapshot_id}
)
if abort_point == 'during_start':
return self._handle_abort(abort_point, metrics, 'start')
if not start_success:
raise RuntimeError("Service start failed")
# Replay events
replay_start = time.time()
events_to_replay = self._get_events_to_replay(
snapshot.sequence,
replay_count
)
replay_result = self.event_replayer.replay_events(
start_seq=snapshot.sequence + 1,
end_seq=snapshot.sequence + len(events_to_replay),
callback=self._replay_callback if self.config.get('track_replay_progress') else None
)
replay_duration = (time.time() - replay_start) * 1000
metrics.replay_duration_ms = replay_duration
metrics.replay_success = (replay_result.status == ReplayStatus.SUCCESS)
if abort_point == 'during_replay':
return self._handle_abort(abort_point, metrics, 'replay', replay_result)
# Get final state
final_state = self.service.invoke_operation('get_full_state', {})
post_restart_seq = self.event_replayer.get_latest_sequence()
return {
'final_state': final_state,
'pre_restart_seq': pre_restart_seq,
'post_restart_seq': post_restart_seq,
'replay_result': replay_result,
'stop_duration_ms': stop_duration
}
def _handle_abort(
self,
abort_point: str,
metrics: ValidationMetrics,
phase: str,
replay_result: Optional[ReplayResult] = None
) -> Dict[str, Any]:
"""Handle abort scenario"""
self.logger.warning(f"Aborting at {abort_point} (phase: {phase})")
metrics.abort_attempted = True
metrics.abort_point = abort_point
# Attempt recovery
recovery_success = self._attempt_recovery(abort_point)
metrics.abort_successful = recovery_success
# Return current state
current_state = self.service.invoke_operation('get_full_state', {})
return {
'final_state': current_state,
'aborted': True,
'abort_point': abort_point,
'recovery_success': recovery_success,
'replay_result': replay_result
}
def _attempt_recovery(self, abort_point: str) -> bool:
"""Attempt to recover from abort point"""
try:
if abort_point in ['before_snapshot', 'during_snapshot']:
# No snapshot taken, continue with current service
return self.service.is_running()
elif abort_point in ['after_snapshot_before_stop', 'during_stop']:
# Snapshot exists but service stopped
# Could restart from previous version or retry
return self.service.start_service(
version=self.service.get_version(),
config={'recovery': True}
)
elif abort_point in ['after_stop_before_start', 'during_start']:
# Service stopped, need to restart
return self.service.start_service(
version=self.service.get_version(),
config={'recovery': True}
)
elif abort_point in ['during_replay', 'after_replay_before_validate']:
# Partial replay, could rollback or continue
return self.service.invoke_operation('rollback_to_last_checkpoint', {})
return False
except Exception as e:
self.logger.error(f"Recovery failed: {str(e)}")
return False
def _validate_state(
self,
baseline: Dict[str, Any],
final: Dict[str, Any],
metrics: ValidationMetrics
) -> Dict[str, Any]:
"""Comprehensive state validation"""
self.logger.info("Validating state consistency...")
validation_results = {
'exact_match': False,
'semantic_match': False,
'checksum_match': False,
'differences': {},
'warnings': []
}
# 1. Compute state hashes
baseline_hash = self._compute_state_hash(baseline)
final_hash = self._compute_state_hash(final)
metrics.state_hash_match = (baseline_hash == final_hash)
# 2. Structural comparison
if baseline == final:
validation_results['exact_match'] = True
validation_results['semantic_match'] = True
else:
# Semantic comparison (ignore timestamps, IDs)
baseline_semantic = self._strip_volatile_fields(baseline)
final_semantic = self._strip_volatile_fields(final)
validation_results['semantic_match'] = (baseline_semantic == final_semantic)
# Record differences
validation_results['differences'] = self._compute_differences(
baseline, final
)
# 3. Sequence validation
seq_validation = self._validate_sequence_continuity()
metrics.sequence_gap_count = seq_validation['gap_count']
metrics.duplicate_events = seq_validation['duplicates']
metrics.missing_events = seq_validation['missing']
# 4. Final decision
metrics.state_validation_passed = (
metrics.state_hash_match and
metrics.sequence_gap_count == 0 and
metrics.missing_events == 0
)
validation_results['checksum_match'] = metrics.state_hash_match
validation_results['passed'] = metrics.state_validation_passed
return validation_results
def _compute_state_hash(self, state: Dict[str, Any]) -> str:
"""Compute deterministic hash of service state"""
# Sort keys and normalize
normalized = json.dumps(state, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(normalized.encode()).hexdigest()
def _strip_volatile_fields(self, state: Dict[str, Any]) -> Dict[str, Any]:
"""Remove volatile fields (timestamps, IDs, etc.) for semantic comparison"""
volatile_keys = {'timestamp', 'last_updated', 'request_id', 'session_id'}
return {
k: v for k, v in state.items()
if k not in volatile_keys
}
def _compute_differences(self, baseline: Dict, final: Dict) -> Dict[str, Any]:
"""Compute detailed differences between states"""
diff = {
'added': {},
'removed': {},
'modified': {},
'type_changes': {}
}
baseline_keys = set(baseline.keys())
final_keys = set(final.keys())
diff['added'] = {k: final[k] for k in final_keys - baseline_keys}
diff['removed'] = {k: baseline[k] for k in baseline_keys - final_keys}
for key in baseline_keys & final_keys:
if baseline[key] != final[key]:
diff['modified'][key] = {
'before': baseline[key],
'after': final[key]
}
return diff
def _validate_sequence_continuity(self) -> Dict[str, int]:
"""Validate event sequence continuity"""
# Implementation depends on event store
# This is a placeholder
return {'gap_count': 0, 'duplicates': 0, 'missing': 0}
def _replay_callback(self, event: Event, index: int, total: int):
"""Callback during replay for progress tracking"""
if index % 1000 == 0:
self.logger.debug(f"Replay progress: {index}/{total} events")
def _get_events_to_replay(
self,
from_seq: int,
max_count: Optional[int]
) -> List[Event]:
"""Get events to replay based on configuration"""
latest = self.event_replayer.get_latest_sequence()
to_seq = latest if max_count is None else min(from_seq + max_count, latest)
if to_seq < from_seq:
return []
return self.event_replayer.get_events_in_range(from_seq, to_seq)
def _inject_events(self, events: List[Event]):
"""Inject events during test"""
for event in events:
self.service.invoke_operation('process_event', {'event': event.payload})
def _compile_results(
self,
scenario: str,
metrics: ValidationMetrics,
validation: Dict[str, Any],
restart_result: Dict[str, Any]
) -> Dict[str, Any]:
"""Compile final test results"""
return {
'scenario': scenario,
'success': metrics.state_validation_passed,
'timestamp': datetime.utcnow().isoformat(),
'metrics': metrics.to_dict(),
'validation': validation,
'restart': {
'aborted': restart_result.get('aborted', False),
'abort_point': restart_result.get('abort_point'),
'recovery_success': restart_result.get('recovery_success', False)
}
}
# ==================== Validation State Store ====================
class ValidationStateStore:
"""Stores baseline states for validation"""
def __init__(self):
self.baselines: Dict[str, Dict[str, Any]] = {}
self.snapshots: Dict[str, Snapshot] = {}
def store_baseline(self, service_id: str, state: Dict[str, Any]):
"""Store baseline state for service"""
self.baselines[service_id] = state.copy()
def get_baseline(self, service_id: str) -> Optional[Dict[str, Any]]:
"""Get stored baseline for service"""
return self.baselines.get(service_id)
def store_snapshot(self, snapshot: Snapshot):
"""Store snapshot metadata"""
self.snapshots[snapshot.snapshot_id] = snapshot
def get_snapshot(self, snapshot_id: str) -> Optional[Snapshot]:
"""Retrieve snapshot metadata"""
return self.snapshots.get(snapshot_id)
# ==================== Example Implementations ====================
class InMemorySnapshotManager(SnapshotManager):
"""In-memory snapshot manager for testing"""
def __init__(self):
self.snapshots: Dict[str, Snapshot] = {}
self.counter = 0
def create_snapshot(self, service_id: str, metadata: Dict[str, Any]) -> Snapshot:
"""Create snapshot from service state (mocked)"""
self.counter += 1
snapshot_id = f"snap_{self.counter:06d}"
# In real implementation, would serialize actual service state
mock_state = b'{"state": "mocked"}'
state_hash = hashlib.sha256(mock_state).hexdigest()
snapshot = Snapshot(
snapshot_id=snapshot_id,
service_id=service_id,
version="current",
sequence=1000, # Mock sequence
timestamp=time.time(),
state_hash=state_hash,
metadata=metadata,
size_bytes=len(mock_state)
)
self.snapshots[snapshot_id] = snapshot
return snapshot
def restore_snapshot(self, snapshot: Snapshot) -> bool:
"""Restore from snapshot (mocked)"""
return snapshot.snapshot_id in self.snapshots
def list_snapshots(self, service_id: str) -> List[Snapshot]:
"""List snapshots for service"""
return [s for s in self.snapshots.values() if s.service_id == service_id]
class InMemoryEventReplayer(EventReplayer):
"""In-memory event replayer for testing"""
def __init__(self, events: List[Event]):
self.events = sorted(events, key=lambda e: e.sequence)
self.current_seq = max([e.sequence for e in events]) if events else 0
def replay_events(
self,
start_seq: int,
end_seq: int,
callback: Optional[Callable] = None
) -> ReplayResult:
"""Replay events in memory"""
start_time = time.time()
errors = []
processed = 0
try:
events_to_replay = [
e for e in self.events
if start_seq <= e.sequence <= end_seq
]
for i, event in enumerate(events_to_replay):
if callback:
callback(event, i, len(events_to_replay))
processed += 1
status = ReplayStatus.SUCCESS if processed == len(events_to_replay) else ReplayStatus.PARTIAL
return ReplayResult(
status=status,
events_processed=processed,
first_event_seq=start_seq,
last_event_seq=end_seq,
errors=errors,
duration_seconds=time.time() - start_time,
state_delta={'events_processed': processed}
)
except Exception as e:
return ReplayResult(
status=ReplayStatus.FAILED,
events_processed=processed,
first_event_seq=start_seq,
last_event_seq=end_seq,
errors=[str(e)],
duration_seconds=time.time() - start_time
)
def get_latest_sequence(self) -> int:
"""Get latest sequence number"""
return self.current_seq
def get_events_in_range(self, start: int, end: int) -> List[Event]:
"""Get events in range"""
return [e for e in self.events if start <= e.sequence <= end]
class MockServiceController(ServiceController):
"""Mock service controller for testing"""
def __init__(self, initial_state: Dict[str, Any] = None):
self.state = initial_state or {}
self.running = False
self.version = "1.0.0"
self.metrics = {
'memory_mb': 100,
'cpu_percent': 5.0,
'request_count': 0
}
def start_service(self, version: str, config: Dict[str, Any]) -> bool:
"""Start mock service"""
self.version = version
self.running = True
self.state['start_time'] = time.time()
self.state['version'] = version
self.state.update(config)
return True
def stop_service(self, graceful: bool = True, timeout: int = 30) -> bool:
"""Stop mock service"""
self.running = False
self.state['stop_time'] = time.time()
return True
def is_running(self) -> bool:
return self.running
def get_version(self) -> str:
return self.version
def get_metrics(self) -> Dict[str, Any]:
return self.metrics.copy()
def invoke_operation(self, operation: str, params: Dict[str, Any]) -> Any:
"""Mock operation invocation"""
if not self.running:
raise RuntimeError("Service not running")
if operation == 'get_full_state':
return self.state.copy()
elif operation == 'process_event':
event = params['event']
# Simulate state update
self.state.setdefault('events', []).append(event)
self.state['last_event_time'] = time.time()
self.metrics['request_count'] += 1
return True
elif operation == 'rollback_to_last_checkpoint':
# Mock rollback
if 'checkpoint' in self.state:
self.state = self.state['checkpoint'].copy()
return True
else:
raise ValueError(f"Unknown operation: {operation}")
# ==================== Usage Example ====================
def example_usage():
"""Example of how to use the harness"""
# Setup test data
events = [
Event(i, time.time(), "operation", {"value": i})
for i in range(1, 1001)
]
# Initialize components
snapshot_mgr = InMemorySnapshotManager()
event_replayer = InMemoryEventReplayer(events)
service = MockServiceController({"initialized": True})
validation_store = ValidationStateStore()
# Create harness
harness = HotRestartHarness(
snapshot_mgr=snapshot_mgr,
event_replayer=event_replayer,
service_controller=service,
validation_store=validation_store,
config={'track_replay_progress': True}
)
# Run baseline
service.start_service("1.0.0", {})
for event in events[:500]: # Process first 500 events
service.invoke_operation('process_event', {'event': event.payload})
baseline = service.invoke_operation('get_full_state', {})
validation_store.store_baseline("test_service", baseline)
# Test scenarios
test_scenarios = [
{
'name': 'normal_hot_restart',
'target_version': '2.0.0',
'abort_point': None,
'replay_count': 500
},
{
'name': 'abort_after_snapshot',
'target_version': '2.0.0',
'abort_point': 'after_snapshot_before_stop',
'replay_count': 0
},
{
'name': 'abort_during_replay',
'target_version': '2.0.0',
'abort_point': 'during_replay',
'replay_count': 100 # Will abort after ~100 events
}
]
results = []
for scenario in test_scenarios:
result = harness.run_test_scenario(**scenario)
results.append(result)
# Log summary
metrics = result['metrics']
print(f"\nScenario: {scenario['name']}")
print(f" Success: {result['success']}")
print(f" Snapshot: {metrics['success']['snapshot']}, "
f"Restore: {metrics['success']['restore']}, "
f"Replay: {metrics['success']['replay']}")
print(f" State validation: {metrics['success']['state_validation']}")
print(f" Total time: {metrics['timing']['total_ms']:.2f}ms")
print(f" Events/sec: {metrics['performance']['eps']:.2f}")
return results
if __name__ == "__main__":
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Run example
results = example_usage()
# Save results to file
with open('hot_restart_test_results.json', 'w') as f:
json.dump(results, f, indent=2, default=str)
print(f"\nResults saved to hot_restart_test_results.json")