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

110 lines
4.3 KiB
Nim

## Reliable Channel layer API — channel lifecycle
## (createReliableChannel / closeChannel).
import std/tables
import results, chronos, chronicles
import logos_delivery/api/types
import logos_delivery/api/messaging_client_api
import logos_delivery/channels/reliable_channel_manager
import logos_delivery/channels/reliable_channel
import logos_delivery/waku/persistency/sds_persistency
# ReliableChannel, config and wire-version markers.
export reliable_channel
const SdsJobId = "sds"
## One persistency job shared by every channel's SDS state; rows are
## keyed by channelId.
proc sdsPersistence(brokerCtx: BrokerContext): Opt[Persistence] =
## SDS backend from the node's Persistency instance, resolved via the
## context-scoped GetPersistency broker; memory-only fallback when no
## provider is installed (e.g. unit tests).
let p = GetPersistency.request(brokerCtx).valueOr:
info "SDS persistence disabled, running memory-only", reason = $error
return Opt.none(Persistence)
let job = p.openJob(SdsJobId).valueOr:
warn "SDS persistence disabled, could not open persistency job",
jobId = SdsJobId, reason = $error
return Opt.none(Persistence)
return Opt.some(newSdsPersistence(job))
proc createReliableChannel*(
self: ReliableChannelManager,
channelId: ChannelId,
contentTopic: ContentTopic,
senderId: SdsParticipantID,
): Result[ChannelId, string] =
## Encryption and egress providers must be installed (or `setNoopEncryption()`)
## before traffic flows on the channel.
## Subscribes to `contentTopic`; without a `MessagingSubscribe` provider the
## subscription is deferred to `ReliableChannelManager.start`.
if self.channels.hasKey(channelId):
return err("channel already exists: " & channelId)
# Subscribe before constructing so a failure leaks no listeners.
if MessagingSubscribe.isProvided(self.brokerCtx):
MessagingSubscribe.request(self.brokerCtx, contentTopic).isOkOr:
return err("failed to subscribe to content topic: " & error)
else:
debug "no MessagingSubscribe provider, deferring content topic subscription",
channelId = channelId, contentTopic = contentTopic
let cc = self.conf
let segConfig = SegmentationConfig(
segmentSizeBytes: cc.segmentationSegmentSizeBytes.get(DefaultSegmentSizeBytes),
enableReedSolomon: cc.segmentationEnableReedSolomon.get(false),
persistence: nil,
)
let sdsConfig = SdsConfig(
acknowledgementTimeoutMs:
cc.sdsAcknowledgementTimeoutMs.get(DefaultAcknowledgementTimeoutMs),
maxRetransmissions: cc.sdsMaxRetransmissions.get(DefaultMaxRetransmissions),
causalHistorySize: cc.sdsCausalHistorySize.get(DefaultCausalHistorySize),
persistence: sdsPersistence(self.brokerCtx),
)
let chn = ReliableChannel.new(
channelId = channelId,
contentTopic = contentTopic,
senderId = senderId,
segConfig = segConfig,
sdsConfig = sdsConfig,
brokerCtx = self.brokerCtx,
)
self.channels[channelId] = chn
return ok(channelId)
proc channelExists*(self: ReliableChannelManager, channelId: ChannelId): bool =
## True while the channel is held by the manager, i.e. between a successful
## `createReliableChannel` and `closeChannel`. Persisted SDS state for a
## closed channel does not count as existing.
return self.channels.hasKey(channelId)
proc closeChannel*(
self: ReliableChannelManager, channelId: ChannelId
): Future[Result[void, string]] {.async: (raises: []).} =
## Stops the channel's SDS loops and releases the channel. Persisted SDS
## state survives, so re-creating the channel restores it. Unsubscribes the
## content topic unless another open channel still uses it.
let chn = self.channels.getOrDefault(channelId)
if chn.isNil():
return err("unknown channel: " & channelId)
self.channels.del(channelId)
await chn.stop()
# After `stop` so in-flight sends cannot auto-resubscribe; best-effort.
let contentTopic = chn.getContentTopic()
var topicStillUsed = false
for other in self.channels.values:
if other.getContentTopic() == contentTopic:
topicStillUsed = true
break
if not topicStillUsed and MessagingUnsubscribe.isProvided(self.brokerCtx):
MessagingUnsubscribe.request(self.brokerCtx, contentTopic).isOkOr:
warn "failed to unsubscribe closed channel's content topic",
channelId = channelId, contentTopic = contentTopic, error = error
return ok()