logos-delivery/tests/persistency/test_sds_persistency.nim
NagyZoltanPeter e8566db8ee
fix(persistency): own Persistency per node instead of a process-global singleton (#4109)
* fix(persistency): own Persistency per node instead of a process-global singleton

The Persistency singleton (gPersistency) was allocated on whichever FFI
thread first ran waku.start; under --mm:refc its memory belonged to that
thread's heap, so a second library context adopting it read a foreign
heap (SIGSEGV in sdsPersistence -> openJob -> tables.rawGet), one
context's stop stole the other's SDS persistence, and a destroyed
context poisoned re-init with a different local-storage-path.

- remove the singleton (instance/reset/gPersistency); Persistency.new is
  the public constructor, no lock needed (instances are thread-confined)
- own the instance as Waku.persistency: created and provided in
  waku.start, cleared and closed in waku.stop on the owning thread
- expose it via a sync GetPersistency RequestBroker scoped to the node's
  BrokerContext; sdsPersistence resolves through it (same-thread ref
  return, no marshalling)
- add InMemoryStoragePath (":memory:") support: private in-memory SQLite
  per job worker, for tests
- rewrite test_singleton as per-instance + broker coverage; rewrite
  test_thread_affinity from a known-failing UB repro into a regression
  guard (two in-memory jobs, worker spinup/teardown, cross-thread broker
  denial) and register it in test_all; migrate remaining tests to
  new/close; the FFI lifecycle test's stop-steals and different-paths
  cases now pass against the real dylib

The FFI destroy-without-stop teardown gap remains tracked in #4108.

Fixes #4103

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(persistency): create the instance only after startup fully succeeds

waku.start has many error return paths; creating Persistency early meant
every one of them left the field set and the GetPersistency provider
installed with no teardown. Persistency.new is inert (no threads or
files until the first openJob) and every consumer runs post-start, so
creating and providing it as the last startup step removes the need for
any error-path cleanup entirely.

Addresses PR #4109 review feedback.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(persistency): create early for startup-stage restores, tear down on failed start

Creating the instance as the last startup step made it impossible for
any stage of start to restore persisted data (e.g. a future store-state
restore). Restore the original ordering -- create and provide the
instance first -- and cover every error return path of waku.start with a
success-flag defer that clears the provider and closes the instance.
Teardown is factored into closePersistency, shared by stop and the
failed-start path.

Addresses PR #4109 review discussion.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(persistency): address remaining Copilot review findings

- document that Persistency instances are thread-confined (not
  thread-safe) on the type itself, pointing at the GetPersistency broker
  as the sanctioned access path
- use tryRemoveFile for the FFI test's log cleanup so an unremovable
  file cannot fail the test for unrelated reasons

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix comment

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 23:35:10 +02:00

156 lines
5.1 KiB
Nim

{.used.}
## Behavioural tests for the SDS Persistence adapter (nim-sds 0.3.0 snapshot
## model). Importing `sds_persistency` also compile-checks the real adapter.
##
## Writes go through the fire-and-forget Job path (the Future resolves when
## the op is queued, not applied — Persistency v1), so every read-back polls
## until the row appears/disappears.
import std/[os, times]
import chronos, results
import testutils/unittests
import logos_delivery/waku/persistency/persistency
import logos_delivery/waku/persistency/keys
import logos_delivery/waku/persistency/sds_persistency
proc tmpRoot(label: string): string =
let p = getTempDir() / ("sds_persistency_test_" & label & "_" & $epochTime().int)
removeDir(p)
p
proc pollExists(
t: Job, category: string, k: Key, timeoutMs = 1000
): Future[bool] {.async.} =
let deadline = epochTime() + (timeoutMs.float / 1000.0)
while epochTime() < deadline:
let r = await t.exists(category, k)
if r.isOk and r.get():
return true
await sleepAsync(chronos.milliseconds(2))
return false
proc pollGone(
t: Job, category: string, k: Key, timeoutMs = 1000
): Future[bool] {.async.} =
let deadline = epochTime() + (timeoutMs.float / 1000.0)
while epochTime() < deadline:
let r = await t.exists(category, k)
if r.isOk and not r.get():
return true
await sleepAsync(chronos.milliseconds(2))
return false
proc mkMsg(channelId: SdsChannelID, msgId: SdsMessageID, lamport: int64): SdsMessage =
SdsMessage.init(
messageId = msgId,
lamportTimestamp = lamport,
causalHistory = @[],
channelId = channelId,
content = @[byte(1), byte(2)],
bloomFilter = @[],
)
suite "SDS persistency adapter (0.3.0 snapshot model)":
asyncTest "saveChannelMeta + updateHistory round-trip via loadChannel":
let root = tmpRoot("roundtrip")
defer:
removeDir(root)
let p = Persistency.new(root).get()
defer:
p.close()
let job = p.openJob("sds").get()
let persistence = newSdsPersistence(job)
let channelId = "chan-1".SdsChannelID
var meta = ChannelMeta.init()
meta.lamportTimestamp = 42
check (await persistence.saveChannelMeta(channelId, meta)).isOk
check (await job.pollExists(CatMeta, toKey(channelId)))
# append out of (lamport) order on purpose; loadChannel must sort.
var upd = HistoryUpdate.init()
upd.append = @[mkMsg(channelId, "m2", 2), mkMsg(channelId, "m1", 1)]
check (await persistence.updateHistory(channelId, upd)).isOk
check (await job.pollExists(CatLog, key(channelId, "m2")))
let data = (await persistence.loadChannel(channelId)).valueOr:
check false
return
check data.meta.lamportTimestamp == 42
check data.messageHistory.len == 2
check data.messageHistory[0].messageId == "m1"
check data.messageHistory[1].messageId == "m2"
asyncTest "loadChannel on a fresh channel returns empty ChannelData":
let root = tmpRoot("empty")
defer:
removeDir(root)
let p = Persistency.new(root).get()
defer:
p.close()
let job = p.openJob("sds").get()
let persistence = newSdsPersistence(job)
let data = (await persistence.loadChannel("nope".SdsChannelID)).valueOr:
check false
return
check data.meta.lamportTimestamp == 0
check data.messageHistory.len == 0
asyncTest "updateHistory evict removes a log row":
let root = tmpRoot("evict")
defer:
removeDir(root)
let p = Persistency.new(root).get()
defer:
p.close()
let job = p.openJob("sds").get()
let persistence = newSdsPersistence(job)
let channelId = "c".SdsChannelID
var upd = HistoryUpdate.init()
upd.append = @[mkMsg(channelId, "a", 1), mkMsg(channelId, "b", 2)]
check (await persistence.updateHistory(channelId, upd)).isOk
check (await job.pollExists(CatLog, key(channelId, "b")))
var ev = HistoryUpdate.init()
ev.evict = @["a".SdsMessageID]
check (await persistence.updateHistory(channelId, ev)).isOk
check (await job.pollGone(CatLog, key(channelId, "a")))
let data = (await persistence.loadChannel(channelId)).valueOr:
check false
return
check data.messageHistory.len == 1
check data.messageHistory[0].messageId == "b"
asyncTest "dropChannel wipes meta and log":
let root = tmpRoot("drop")
defer:
removeDir(root)
let p = Persistency.new(root).get()
defer:
p.close()
let job = p.openJob("sds").get()
let persistence = newSdsPersistence(job)
let channelId = "d".SdsChannelID
var meta = ChannelMeta.init()
meta.lamportTimestamp = 7
check (await persistence.saveChannelMeta(channelId, meta)).isOk
var upd = HistoryUpdate.init()
upd.append = @[mkMsg(channelId, "x", 1)]
check (await persistence.updateHistory(channelId, upd)).isOk
check (await job.pollExists(CatMeta, toKey(channelId)))
check (await job.pollExists(CatLog, key(channelId, "x")))
check (await persistence.dropChannel(channelId)).isOk
check (await job.pollGone(CatMeta, toKey(channelId)))
let data = (await persistence.loadChannel(channelId)).valueOr:
check false
return
check data.meta.lamportTimestamp == 0
check data.messageHistory.len == 0