@rbxts/scribe 2.5.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,6 +28,9 @@ local Rng = require(Internal.Rng)
28
28
 
29
29
  local Persistence = {}
30
30
 
31
+ -- Wipe-guard summary of `_Scribe`.
32
+ type LedgerShape = { Present: { [string]: true }, Version: number? }
33
+
31
34
  export type Entry = {
32
35
  Player: Player,
33
36
  UserId: number,
@@ -70,6 +73,10 @@ export type Entry = {
70
73
  -- Top-level keys of the last successful save. The wipe guard's baseline, kept
71
74
  -- here so the store does not have to keep a second copy of the whole profile.
72
75
  LastSavedKeys: { [string]: true }?,
76
+ -- Ledger shape from the same save as LastSavedKeys.
77
+ LastSavedLedger: LedgerShape?,
78
+ -- Intentional OnPlayerInit removals, cleared after a successful unblocked save.
79
+ InitRemovedKeys: { [string]: true }?,
73
80
  LiveSize: number?, -- approx bytes measured at the start of the last save attempt
74
81
  SizeWarned: boolean,
75
82
  TornDown: boolean,
@@ -89,6 +96,11 @@ export type Entry = {
89
96
  -- broken transport cannot cost one encode per frame.
90
97
  ResyncPending: boolean?,
91
98
  LastResyncAt: number?,
99
+ -- Failed snapshot: stop holding replies until one lands.
100
+ ResyncFailed: boolean?,
101
+ -- Replies waiting for a repair snapshot, with their earliest release deadline.
102
+ HeldReplies: { buffer }?,
103
+ HeldDeadline: number?,
92
104
  Queue: { any },
93
105
  QueueIndex: { [string]: number },
94
106
  SharedQueue: { any },
@@ -111,7 +123,7 @@ export type Entry = {
111
123
  LastRateLimitLog: number?, -- os.clock of the last emitted COMMAND_RATE_LIMITED
112
124
  -- Why the store last failed for this key. StartSessionAsync answers nil with no reason
113
125
  -- of its own, so this is the only way a load failure can tell a throttle apart.
114
- LastStoreErrorClass: Failure.Class?,
126
+ LastStoreErrorThrottled: boolean?,
115
127
  LastStoreErrorAt: number?, -- monotonic
116
128
  -- A parallel field, not a fourth State, so nothing switching on State changes
117
129
  -- meaning. nil once Ready.
@@ -149,6 +161,8 @@ local WIPE_GUARD_RATIO_DEFAULT = 0.6 -- a profile shrinking past 60% looks like
149
161
  -- Matches the store's ASSUME_DEAD. Its own constant rather than read from the module,
150
162
  -- so the operator paths behave identically against an injected store that lacks it.
151
163
  local ASSUME_DEAD_SECONDS = 630
164
+ -- Two intervals leave 30 seconds before ASSUME_DEAD_SECONDS after one failed save.
165
+ local MAX_SAVE_INTERVAL = 300
152
166
 
153
167
  -- Share of the shutdown budget the OnPlayerLeaving phase may spend. Hooks come first
154
168
  -- because their writes are the only thing here that cannot be rebuilt; the remainder
@@ -170,47 +184,6 @@ local function watchdog(seconds: number, callback: () -> ()): () -> ()
170
184
  end
171
185
  end
172
186
 
173
- --- A copy of the exchange ledger, for comparing across a hook that writes raw.
174
- ---
175
- --- OnPlayerInit and Scribe.Dynamic factories are handed `profile.Data` DIRECTLY, before
176
- --- the tree exists, so the accessor refusal that protects the reserved root has nothing
177
- --- to refuse through. A starter kit that clears `_Scribe` to "start clean" would destroy
178
- --- an in-flight exchange with no report at all.
179
- local function exchangeSnapshot(data: any): any
180
- local reserved = if type(data) == "table" then data[Template.RESERVED_ROOT] else nil
181
- if type(reserved) ~= "table" then
182
- return nil
183
- end
184
- return {
185
- Exchange = if type(reserved.Exchange) == "table" then Util.deepClone(reserved.Exchange) else nil,
186
- ExchangeInbox = if type(reserved.ExchangeInbox) == "table" then Util.deepClone(reserved.ExchangeInbox) else nil,
187
- }
188
- end
189
-
190
- --- Deep equality over two exchange snapshots, tolerating either side being absent.
191
- local function sameExchangeState(a: any, b: any): boolean
192
- local function eq(x: any, y: any): boolean
193
- if type(x) ~= type(y) then
194
- return false
195
- end
196
- if type(x) ~= "table" then
197
- return x == y
198
- end
199
- for key, value in x do
200
- if not eq(value, y[key]) then
201
- return false
202
- end
203
- end
204
- for key in y do
205
- if x[key] == nil then
206
- return false
207
- end
208
- end
209
- return true
210
- end
211
- return eq(a, b)
212
- end
213
-
214
187
  --- Does this stored profile hold exchange state that a wipe or a rollback would split?
215
188
  --- Value in flight sits in the reserved root while the matching hole sits in game data,
216
189
  --- so rolling one half back leaves the item in the inventory AND in the escrow, or takes
@@ -338,11 +311,7 @@ function Persistence.new(ctx: any)
338
311
  local THROTTLE_ATTRIBUTION_WINDOW = 15
339
312
  local function loadKickText(entry: Entry): string
340
313
  local at = entry.LastStoreErrorAt
341
- if
342
- entry.LastStoreErrorClass == "Throttled"
343
- and at ~= nil
344
- and (Clock.Monotonic() - at) <= THROTTLE_ATTRIBUTION_WINDOW
345
- then
314
+ if entry.LastStoreErrorThrottled and at ~= nil and (Clock.Monotonic() - at) <= THROTTLE_ATTRIBUTION_WINDOW then
346
315
  return kickText("RateLimited")
347
316
  end
348
317
  return kickText("Load")
@@ -461,6 +430,17 @@ function Persistence.new(ctx: any)
461
430
  )
462
431
  interval = MIN_SAVE_INTERVAL
463
432
  end
433
+ -- Leave room for one failed save before the session appears dead.
434
+ if interval > MAX_SAVE_INTERVAL then
435
+ Log.Warn(
436
+ "Persistence",
437
+ "SAVE_INTERVAL_CLAMPED",
438
+ `autosave interval above the {MAX_SAVE_INTERVAL}s ceiling (one failed save must stay under the `
439
+ .. `{ASSUME_DEAD_SECONDS}s after which another server takes a silent session); clamping`,
440
+ { Requested = interval, Applied = MAX_SAVE_INTERVAL }
441
+ )
442
+ interval = MAX_SAVE_INTERVAL
443
+ end
464
444
  -- Two bundles asking for different cadences is a real conflict; unreported it
465
445
  -- resolves as last-writer-wins, with the winner decided by require order.
466
446
  if Config.AutoSaveInterval ~= nil and Config.AutoSaveInterval ~= interval then
@@ -585,7 +565,7 @@ function Persistence.new(ctx: any)
585
565
  if entry.Key == profileKey then
586
566
  -- Outside the in-flight guard: a load has no save on the wire, and
587
567
  -- the load path is what needs the distinction. Dies with the entry.
588
- entry.LastStoreErrorClass = class
568
+ entry.LastStoreErrorThrottled = Failure.IsThrottleLike(message)
589
569
  entry.LastStoreErrorAt = Clock.Monotonic()
590
570
  end
591
571
  if entry.Key == profileKey and entry.SavesInFlight > 0 then
@@ -803,7 +783,7 @@ function Persistence.new(ctx: any)
803
783
 
804
784
  function self.UpdateSaveInfoMirror(entry: Entry)
805
785
  if entry.Tree and not entry.Tree.Dead then
806
- local accessor = entry.Tree.Accessor[Template.SESSION_ROOT].SaveInfo
786
+ local accessor = entry.Tree.ReservedSession.SaveInfo
807
787
  accessor.Set({
808
788
  LastSaveAt = entry.SaveInfo.LastSaveAt,
809
789
  LastResult = entry.SaveInfo.LastResult,
@@ -959,6 +939,62 @@ function Persistence.new(ctx: any)
959
939
  end
960
940
  end
961
941
 
942
+ -- Guard declared ledger parts even on small profiles. Obsolete keys may be removed.
943
+ local ledgerChildren: { string } = {}
944
+ do
945
+ local rootChildren = playerCompiled.Root.Children
946
+ local reservedSchema = if rootChildren then rootChildren[Template.RESERVED_ROOT] else nil
947
+ for key in (if reservedSchema then reservedSchema.Children else nil) or {} do
948
+ table.insert(ledgerChildren, key)
949
+ end
950
+ table.sort(ledgerChildren)
951
+ end
952
+
953
+ -- Every ledger part is a table except Version.
954
+ local function keptShape(key: string, value: any): boolean
955
+ return type(value) == (if key == "Version" then "number" else "table")
956
+ end
957
+
958
+ -- Ignore malformed parts so repairing them does not count as data loss.
959
+ local function ledgerShape(data: any): LedgerShape?
960
+ local reserved = if type(data) == "table" then data[Template.RESERVED_ROOT] else nil
961
+ if type(reserved) ~= "table" then
962
+ return nil
963
+ end
964
+ local present: { [string]: true } = {}
965
+ for _, key in ledgerChildren do
966
+ if keptShape(key, reserved[key]) then
967
+ present[key] = true
968
+ end
969
+ end
970
+ return { Present = present, Version = if type(reserved.Version) == "number" then reserved.Version else nil }
971
+ end
972
+
973
+ -- Detect lost ledger parts or a schema version that went backwards.
974
+ local function ledgerLoss(before: LedgerShape?, live: { [string]: any }): string?
975
+ if before == nil then
976
+ return nil
977
+ end
978
+ local reserved = live[Template.RESERVED_ROOT]
979
+ if type(reserved) ~= "table" then
980
+ return `"{Template.RESERVED_ROOT}" is no longer a table`
981
+ end
982
+ local missing = {}
983
+ for _, key in ledgerChildren do
984
+ if before.Present[key] and not keptShape(key, reserved[key]) then
985
+ table.insert(missing, `{Template.RESERVED_ROOT}.{key}`)
986
+ end
987
+ end
988
+ if #missing > 0 then
989
+ return `ledger entries vanished or replaced: {table.concat(missing, ", ")}`
990
+ end
991
+ local version = reserved.Version
992
+ if before.Version ~= nil and (type(version) ~= "number" or version < before.Version) then
993
+ return `ledger schema Version went backwards: {before.Version} -> {tostring(version)}`
994
+ end
995
+ return nil
996
+ end
997
+
962
998
  -- Wipe guard: compare against the last successful save. `liveSize` is passed in
963
999
  -- because onProfileSaving measures the same table in the same synchronous frame.
964
1000
  local function wipeGuardCheck(entry: Entry, liveSize: number?): (boolean, string?)
@@ -972,6 +1008,7 @@ function Persistence.new(ctx: any)
972
1008
  -- the two cases the summary cannot be: before the first save of a session, and
973
1009
  -- under WipeGuardPolicy = "Block", which writes those bytes back as the payload.
974
1010
  local keys: any = entry.LastSavedKeys
1011
+ local ledger = entry.LastSavedLedger
975
1012
  local oldSize = entry.LastSavedSize
976
1013
  if keys == nil then
977
1014
  local lastSaved = profile.LastSavedData
@@ -979,17 +1016,23 @@ function Persistence.new(ctx: any)
979
1016
  return false, nil
980
1017
  end
981
1018
  keys = lastSaved
1019
+ ledger = ledgerShape(lastSaved)
982
1020
  oldSize = oldSize or Util.approxSize(lastSaved)
983
1021
  end
984
1022
  local missing = {}
1023
+ local removedByInit = entry.InitRemovedKeys
985
1024
  for key in keys do
986
- if live[key] == nil then
1025
+ if live[key] == nil and not (removedByInit and removedByInit[key]) then
987
1026
  table.insert(missing, tostring(key))
988
1027
  end
989
1028
  end
990
1029
  if #missing > 0 then
991
1030
  return true, `top-level keys vanished: {table.concat(missing, ", ")}`
992
1031
  end
1032
+ local lost = ledgerLoss(ledger, live)
1033
+ if lost ~= nil then
1034
+ return true, lost
1035
+ end
993
1036
  local ratio = wipeGuardRatio
994
1037
  local newSize = liveSize or Util.approxSize(live)
995
1038
  if oldSize and newSize and oldSize > 1024 and newSize < oldSize * (1 - ratio) then
@@ -1100,6 +1143,24 @@ function Persistence.new(ctx: any)
1100
1143
  end
1101
1144
  end
1102
1145
 
1146
+ -- Use the saved payload: a blocked save persists the last-good snapshot, not live data.
1147
+ local function recordSavedBaseline(entry: Entry, lastSavedData: any): number?
1148
+ local size = Util.approxSize(lastSavedData)
1149
+ if size then
1150
+ entry.LastSavedSize = size
1151
+ entry.LiveSize = size
1152
+ end
1153
+ if type(lastSavedData) == "table" then
1154
+ local keys: { [string]: true } = {}
1155
+ for key in lastSavedData do
1156
+ keys[key :: string] = true
1157
+ end
1158
+ entry.LastSavedKeys = keys
1159
+ entry.LastSavedLedger = ledgerShape(lastSavedData)
1160
+ end
1161
+ return size
1162
+ end
1163
+
1103
1164
  local function onProfileSaved(entry: Entry, lastSavedData: any)
1104
1165
  -- ProfileStore fires OnAfterSave even when the session was STOLEN and nothing
1105
1166
  -- local persisted. Skip the success bookkeeping only for steals: a
@@ -1119,6 +1180,7 @@ function Persistence.new(ctx: any)
1119
1180
  -- migrated shape; the one-time post-migration skip is complete.
1120
1181
  if not entry.Blocked then
1121
1182
  entry.WipeGuardRebaselinePending = false
1183
+ entry.InitRemovedKeys = nil
1122
1184
  end
1123
1185
  Metrics.Add("SavesOk")
1124
1186
  if duration then
@@ -1127,24 +1189,10 @@ function Persistence.new(ctx: any)
1127
1189
  Health.ReportSuccess("Saves")
1128
1190
  ctx.Signals.OnSave:Fire({ Player = entry.Player, Ok = true, Duration = duration, At = Clock.Now() })
1129
1191
 
1130
- -- Record the size that actually persisted (the warning + anomaly are owned by
1131
- -- the pre-save check in onProfileSaving, which also fires when a save fails).
1132
- local size = Util.approxSize(lastSavedData)
1192
+ local size = recordSavedBaseline(entry, lastSavedData)
1133
1193
  if size then
1134
- entry.LastSavedSize = size
1135
- entry.LiveSize = size
1136
1194
  Metrics.Observe("ProfileSize", size)
1137
1195
  end
1138
- -- The other half of the wipe guard's baseline, from the payload that actually
1139
- -- persisted rather than from live data: a blocked save stores the last-good
1140
- -- snapshot, and the baseline has to describe what is on the key.
1141
- if type(lastSavedData) == "table" then
1142
- local keys: { [string]: true } = {}
1143
- for key in lastSavedData do
1144
- keys[key :: string] = true
1145
- end
1146
- entry.LastSavedKeys = keys
1147
- end
1148
1196
 
1149
1197
  self.UpdateSaveInfoMirror(entry)
1150
1198
  end
@@ -1310,7 +1358,7 @@ function Persistence.new(ctx: any)
1310
1358
  "MIGRATION_RESERVED_DISCARDED",
1311
1359
  `a migration step changed the reserved "{Template.RESERVED_ROOT}" root; the change was DISCARDED `
1312
1360
  .. `and the stored reserved state kept (it is library-owned: receipt dedupe, gift escrow, `
1313
- .. `perks, purchase logs, Timed) -- migrate your own keys only`,
1361
+ .. `gift credits, perks, purchase logs, Timed) -- migrate your own keys only`,
1314
1362
  { Player = entry.Player, Path = Template.RESERVED_ROOT, Stored = stored, Current = currentVersion }
1315
1363
  )
1316
1364
  end
@@ -1369,23 +1417,29 @@ function Persistence.new(ctx: any)
1369
1417
  entry.LiveData = profile.Data
1370
1418
  entry.SessionStore = Template.BuildDefaults(playerCompiled, "Session")
1371
1419
 
1420
+ -- Persistent writes dirty the profile even when replication is disabled.
1421
+ local function markWritten(op: Node.Op, schema: Template.SchemaNode?)
1422
+ local persists = if schema then schema.Persist else Template.PersistOf(compiled, op.Path)
1423
+ if persists and not entry.SaveInfo.Dirty then
1424
+ entry.SaveInfo.Dirty = true
1425
+ Sched.Defer(function()
1426
+ if entry.Tree and not entry.Tree.Dead and entry.SaveInfo.Dirty then
1427
+ self.UpdateSaveInfoMirror(entry)
1428
+ end
1429
+ end)
1430
+ end
1431
+ end
1432
+
1372
1433
  entry.Tree = Node.NewTree({
1373
1434
  Compiled = playerCompiled,
1374
1435
  Stores = { Persist = profile.Data, Session = entry.SessionStore },
1375
1436
  IsServer = true,
1376
1437
  Label = entry.Player.Name,
1377
1438
  OnOp = function(op: Node.Op, schema: Template.SchemaNode?)
1378
- local persists = if schema then schema.Persist else Template.PersistOf(compiled, op.Path)
1379
- if persists and not entry.SaveInfo.Dirty then
1380
- entry.SaveInfo.Dirty = true
1381
- Sched.Defer(function()
1382
- if entry.Tree and not entry.Tree.Dead and entry.SaveInfo.Dirty then
1383
- self.UpdateSaveInfoMirror(entry)
1384
- end
1385
- end)
1386
- end
1439
+ markWritten(op, schema)
1387
1440
  ctx.Replication.PushOp(entry, op, schema)
1388
1441
  end,
1442
+ OnUnreplicatedOp = markWritten,
1389
1443
  OnAnomaly = function(path, value, reason)
1390
1444
  Metrics.Add("Anomalies")
1391
1445
  Log.Warn("Integrity", "ANOMALY", `implausible write at "{Util.pathString(path)}": {reason}`, {
@@ -1503,11 +1557,26 @@ function Persistence.new(ctx: any)
1503
1557
  ctx.Signals.SessionEnded:Fire(entry.Player, canonical)
1504
1558
  setState(entry, "SessionEnded", canonical)
1505
1559
 
1506
- ctx.Replication.OnEntryRemoved(entry)
1507
- ctx.Leaderboards.OnUnload(entry)
1508
- ctx.Monetization.OnUnload(entry)
1509
- ctx.Timed.OnUnload(entry)
1510
- ctx.Exchanges.OnUnload(entry)
1560
+ -- One failed hook must not skip the rest of teardown.
1561
+ for _, step in
1562
+ {
1563
+ { "Replication", ctx.Replication.OnEntryRemoved },
1564
+ { "Leaderboards", ctx.Leaderboards.OnUnload },
1565
+ { "Monetization", ctx.Monetization.OnUnload },
1566
+ { "Timed", ctx.Timed.OnUnload },
1567
+ { "Exchanges", ctx.Exchanges.OnUnload },
1568
+ } :: { { any } }
1569
+ do
1570
+ local ok, err = pcall(step[2], entry)
1571
+ if not ok then
1572
+ Log.Error(
1573
+ "Lifecycle",
1574
+ "SUBSYSTEM_HOOK_ERROR",
1575
+ `{step[1]} unload hook failed: {tostring(err)}`,
1576
+ { Player = entry.Player }
1577
+ )
1578
+ end
1579
+ end
1511
1580
 
1512
1581
  if entry.Tree then
1513
1582
  entry.Tree:Destroy()
@@ -1548,6 +1617,17 @@ function Persistence.new(ctx: any)
1548
1617
  local profile = entry.Profile :: any
1549
1618
  local player = entry.Player
1550
1619
 
1620
+ -- Hooks may yield into a save before normal bookkeeping starts. Keep its baseline
1621
+ -- and mark it uncounted so settling it cannot decrement a later save's count.
1622
+ local earlyOnSave = profile.OnSave:Connect(function(saveContext: any)
1623
+ if type(saveContext) == "table" then
1624
+ saveContext.ScribeUncounted = true
1625
+ end
1626
+ end)
1627
+ local earlyAfterSave = profile.OnAfterSave:Connect(function(lastSavedData: any)
1628
+ recordSavedBaseline(entry, lastSavedData)
1629
+ end)
1630
+
1551
1631
  -- Marked for erasure: release without saving.
1552
1632
  local markedReserved = if type(profile.Data) == "table" then profile.Data[Template.RESERVED_ROOT] else nil
1553
1633
  if type(markedReserved) == "table" and type(markedReserved.Erase) == "table" then
@@ -1998,7 +2078,7 @@ function Persistence.new(ctx: any)
1998
2078
  end
1999
2079
 
2000
2080
  if ctx.DevMode then
2001
- local unknown = Template.UnknownRootKeys(compiled, profile.Data)
2081
+ local unknown = Template.UnknownRootKeys(playerCompiled, profile.Data)
2002
2082
  if #unknown > 0 then
2003
2083
  Log.Warn(
2004
2084
  "Persistence",
@@ -2013,9 +2093,6 @@ function Persistence.new(ctx: any)
2013
2093
  end
2014
2094
  end
2015
2095
 
2016
- -- Taken before BOTH hooks: Dynamic factories run above this point too.
2017
- local exchangeStateBefore = exchangeSnapshot(profile.Data)
2018
-
2019
2096
  if options.OnPlayerInit then
2020
2097
  -- A brand-new profile, a ResetData wipe, or a first-session crash recovery all
2021
2098
  -- mean "no prior saved data", which is what starter kits need. An IMPORTED
@@ -2025,30 +2102,50 @@ function Persistence.new(ctx: any)
2025
2102
  -- ImportLegacyData only fires for a player who has never saved, so a game
2026
2103
  -- already on Scribe finishes moving stores here instead. NOT behind the import
2027
2104
  -- cap: this runs on every join, and serialising those throttles ordinary logins.
2105
+ -- Hide the ledger from the hook but keep it in profile.Data for saves during yields.
2106
+ -- Nested edits stay live; fold top-level edits before saves and on return.
2107
+ local data = profile.Data
2108
+ local view = table.clone(data)
2109
+ view[Template.RESERVED_ROOT] = nil
2110
+ local keysBefore = table.clone(view)
2111
+ local function foldView()
2112
+ for key in data do
2113
+ if key ~= Template.RESERVED_ROOT and view[key] == nil then
2114
+ data[key] = nil
2115
+ end
2116
+ end
2117
+ for key, value in view do
2118
+ if key ~= Template.RESERVED_ROOT then
2119
+ data[key] = value
2120
+ end
2121
+ end
2122
+ end
2123
+ -- Include edits made before a yielding hook's autosave or final save.
2124
+ local foldOnSave = profile.OnSave:Connect(foldView)
2028
2125
  Util.safeCall(function(err)
2029
2126
  Log.Error("Lifecycle", "ON_PLAYER_INIT_ERROR", err, { Player = player })
2030
- end, options.OnPlayerInit, player, profile.Data, isNewProfile, migrationContext(entry))
2031
- end
2032
-
2033
- -- REVERTED rather than merely reported: a half-edited exchange record is worse than
2034
- -- either the original or a clean one, and the original is still in hand.
2035
- if exchangeStateBefore ~= nil or exchangeSnapshot(profile.Data) ~= nil then
2036
- local after = exchangeSnapshot(profile.Data)
2037
- if not sameExchangeState(exchangeStateBefore, after) then
2038
- local reserved = profile.Data[Template.RESERVED_ROOT]
2039
- if type(reserved) == "table" then
2040
- reserved.Exchange = if exchangeStateBefore then exchangeStateBefore.Exchange else {}
2041
- reserved.ExchangeInbox = if exchangeStateBefore then exchangeStateBefore.ExchangeInbox else {}
2042
- end
2127
+ end, options.OnPlayerInit, player, view, isNewProfile, migrationContext(entry))
2128
+ foldOnSave:Disconnect()
2129
+ if view[Template.RESERVED_ROOT] ~= nil then
2130
+ view[Template.RESERVED_ROOT] = nil
2043
2131
  Log.Error(
2044
2132
  "Lifecycle",
2045
- "EXCHANGE_INIT_TAMPER",
2046
- "OnPlayerInit or a Scribe.Dynamic factory changed the in-flight exchange ledger under "
2047
- .. `"{Template.RESERVED_ROOT}"; the change has been reverted. That state is Scribe's, `
2048
- .. "and editing it can duplicate or destroy an exchange in progress",
2133
+ "ON_PLAYER_INIT_LEDGER",
2134
+ `OnPlayerInit assigned "{Template.RESERVED_ROOT}", which its data table leaves out; the `
2135
+ .. "assignment was discarded and Scribe's ledger kept. That root holds receipt ids, perks "
2136
+ .. "and gift credits, and is changed only through the APIs that own it",
2049
2137
  { Player = player }
2050
2138
  )
2051
2139
  end
2140
+ foldView()
2141
+ -- Exempt intentional removals from the first save's missing-key check.
2142
+ for key in keysBefore do
2143
+ if data[key] == nil then
2144
+ local removed = entry.InitRemovedKeys or {}
2145
+ removed[key] = true
2146
+ entry.InitRemovedKeys = removed
2147
+ end
2148
+ end
2052
2149
  end
2053
2150
 
2054
2151
  -- Scribe.Dynamic factories and OnPlayerInit write raw into profile.Data without
@@ -2082,6 +2179,8 @@ function Persistence.new(ctx: any)
2082
2179
  )
2083
2180
  end
2084
2181
 
2182
+ earlyOnSave:Disconnect()
2183
+ earlyAfterSave:Disconnect()
2085
2184
  profile.OnSave:Connect(function(saveContext: any)
2086
2185
  -- Point the profile at a copy holding online-only cooldowns in their persisted
2087
2186
  -- form and keep the live deadlines aside. OnSave fires before the store reads
@@ -2098,6 +2197,10 @@ function Persistence.new(ctx: any)
2098
2197
  -- session ends, by which time teardown has detached this entry from Entries.
2099
2198
  if type((profile :: any).OnSettled) == "table" then
2100
2199
  (profile :: any).OnSettled:Connect(function(saveContext: any)
2200
+ -- Early saves were never counted.
2201
+ if type(saveContext) == "table" and saveContext.ScribeUncounted then
2202
+ return
2203
+ end
2101
2204
  entry.SavesInFlight = math.max(0, entry.SavesInFlight - 1)
2102
2205
  if entry.SavesInFlight == 0 then
2103
2206
  entry.SaveT0 = nil
@@ -2426,6 +2529,7 @@ function Persistence.new(ctx: any)
2426
2529
  ForceSaveOnce = false,
2427
2530
  LastSavedSize = nil,
2428
2531
  LastSavedKeys = nil,
2532
+ LastSavedLedger = nil,
2429
2533
  SizeWarned = false,
2430
2534
  TornDown = false,
2431
2535
  UnsettledMessages = 0,
@@ -3740,10 +3844,23 @@ function Persistence.new(ctx: any)
3740
3844
  })
3741
3845
  end
3742
3846
 
3743
- function self.BindShutdown()
3744
- game:BindToClose(function()
3847
+ -- The owner may release this registration after explicitly draining its store.
3848
+ -- Stop alone must not release it: stopped bundles can still own sessions or
3849
+ -- final saves. Roblox retains the bound callback, so clear its only reference
3850
+ -- to the bundle as well as making subsequent invocations inert.
3851
+ function self.BindShutdown(): () -> ()
3852
+ local shutdown: (() -> ())? = function()
3745
3853
  self.Shutdown(25)
3854
+ end
3855
+ game:BindToClose(function()
3856
+ local run = shutdown
3857
+ if run then
3858
+ run()
3859
+ end
3746
3860
  end)
3861
+ return function()
3862
+ shutdown = nil
3863
+ end
3747
3864
  end
3748
3865
 
3749
3866
  -- Release the process-global signal connections this bundle installed.