[InternalMetrics] Fix undefined behavior in measuring LocalAggregateStorage size

Change-Id: Ie734b6a5c1f565603ad3bcdd5e2536bd096d3f9e
Reviewed-on: https://fuchsia-review.googlesource.com/c/cobalt/+/522021
Fuchsia-Auto-Submit: Zach Bush <zmbush@google.com>
Reviewed-by: Cameron Dale <camrdale@google.com>
Commit-Queue: Auto-Submit <auto-submit@fuchsia-infra.iam.gserviceaccount.com>
diff --git a/src/local_aggregation_1_1/local_aggregate_storage/delayed_local_aggregate_storage.cc b/src/local_aggregation_1_1/local_aggregate_storage/delayed_local_aggregate_storage.cc
index 0a0d0d9..d764bd8 100644
--- a/src/local_aggregation_1_1/local_aggregate_storage/delayed_local_aggregate_storage.cc
+++ b/src/local_aggregation_1_1/local_aggregate_storage/delayed_local_aggregate_storage.cc
@@ -153,7 +153,13 @@
       // While everything is unlocked, track the current storage usage.
       // This cannot cause an infinite loop, since we are already in the 'data_modified' state,
       // which will be reset to false at the end of this block.
-      auto size = static_cast<int64_t>(aggregates_.ByteSizeLong());
+      int64_t size;
+      {
+        // Take the data lock briefly so we can measure the size of aggregates_ without it being
+        // modified.
+        std::scoped_lock<std::mutex> data_lock(data_mutex_);
+        size = static_cast<int64_t>(aggregates_.ByteSizeLong());
+      }
       internal_metrics_->TrackDiskUsage(
           logger::InternalMetrics::StorageClass::LocalAggregateStorage, size);