From a4088c6c17d1698c087cf5932ec037dfd7ac1f98 Mon Sep 17 00:00:00 2001 From: Nassim Date: Wed, 4 Nov 2026 12:37:06 +0100 Subject: [PATCH] Seed aggregate snapshot version from the loaded snapshot AggregateStateBuilder.populate/1 restored the aggregate version and state from a snapshot but left snapshotting.snapshot_version at 0, so the first command after a cold load snapshotted whenever version >= snapshot_every. Co-authored-by: Manuel Menendez Alfonso (cherry picked from commit 39a4387004cc8ac2a9f3190f6d9237b5c9708a5b) Signed-off-by: Yordis Prieto --- .../aggregates/aggregate_state_builder.ex | 3 ++- test/aggregates/snapshotting_test.exs | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/commanded/aggregates/aggregate_state_builder.ex b/lib/commanded/aggregates/aggregate_state_builder.ex index 0351d8e6..6b66b154 100644 --- a/lib/commanded/aggregates/aggregate_state_builder.ex +++ b/lib/commanded/aggregates/aggregate_state_builder.ex @@ -91,7 +91,8 @@ defmodule Commanded.Aggregates.AggregateStateBuilder do agg = %Aggregate{ state | aggregate_version: source_version, - aggregate_state: data + aggregate_state: data, + snapshotting: %{snapshotting | snapshot_version: source_version} } {agg, true, source_version} diff --git a/test/aggregates/snapshotting_test.exs b/test/aggregates/snapshotting_test.exs index 62a75400..9be2df24 100644 --- a/test/aggregates/snapshotting_test.exs +++ b/test/aggregates/snapshotting_test.exs @@ -208,6 +208,26 @@ defmodule Commanded.Aggregates.SnapshottingTest do assert_aggregate_version(ExampleAggregate, aggregate_uuid, 5) end + + test "should not snapshot again until interval reached since restored snapshot" do + aggregate_uuid = UUID.uuid4() + append_items(aggregate_uuid, 10) + + restart_aggregate(ExampleAggregate, aggregate_uuid) + + # Fewer events than `snapshot_every` since the restored snapshot + append_items(aggregate_uuid, 1) + assert_aggregate_version(ExampleAggregate, aggregate_uuid, 11) + + assert {:ok, %SnapshotData{source_version: 10}} = + EventStore.read_snapshot(DefaultApp, aggregate_uuid) + + append_items(aggregate_uuid, 9) + assert_aggregate_version(ExampleAggregate, aggregate_uuid, 20) + + assert {:ok, %SnapshotData{source_version: 20}} = + EventStore.read_snapshot(DefaultApp, aggregate_uuid) + end end describe "mismatched snapshot versions" do