fix(memory): use SetHistory in migration for crash idempotency

MigrateFromJSON previously called AddFullMessage in a loop, then
renamed the .json file to .json.migrated. If the process crashed
after appending some messages but before the rename, a retry would
re-read the same .json and append all messages again — duplicating
whatever was written before the crash.

Switch to SetHistory which atomically replaces the session contents.
A retry after crash overwrites the partial data instead of appending.
This commit is contained in:
xiaoen committed 2026-02-26 16:15:11 +08:00
1 parent 9c72317b9b
commit e810331dd8
2 files changed
+67 -10

No files matched your search

+11 -10
View File
@@ -74,19 +74,20 @@ func MigrateFromJSON(
key = strings.TrimSuffix(name, ".json")
}
for _, msg := range sess.Messages {
addErr := store.AddFullMessage(ctx, key, msg)
if addErr != nil {
return migrated, fmt.Errorf(
"memory: migrate %s: add message: %w",
name, addErr,
)
}
// Use SetHistory (atomic replace) instead of per-message
// AddFullMessage. This makes migration idempotent: if the
// process crashes after writing messages but before the
// rename below, a retry replaces the partial data cleanly
// instead of duplicating messages.
if setErr := store.SetHistory(ctx, key, sess.Messages); setErr != nil {
return migrated, fmt.Errorf(
"memory: migrate %s: set history: %w",
name, setErr,
)
}
if sess.Summary != "" {
sumErr := store.SetSummary(ctx, key, sess.Summary)
if sumErr != nil {
if sumErr := store.SetSummary(ctx, key, sess.Summary); sumErr != nil {
return migrated, fmt.Errorf(
"memory: migrate %s: set summary: %w",
name, sumErr,