Framework Migration Guide

swift-ddd-kit  1.4 → 1.5

withUnitOfWork: one atomic write across usecases and aggregates — an upgrade guide for projects that depend on swift-ddd-kit

target: swift-ddd-kit Swift 6.1+ / Ubuntu / macOS 15+ / iOS 18+ ⚠ source-breaking for custom EventStoreClient conformances audience: human + AI agent
version transition
FROM1.4
→
TO1.5

1.5 adds withUnitOfWork { work in … }: every repository.save inside the block is collected and written together when the block returns, or not at all when it throws. Existing usecases, repositories, generated code and the composition root take part unchanged. Code that never calls withUnitOfWork behaves as in 1.4, except that a read cancelled midway now throws CancellationError (BC7) and a read of a link stream skips links whose event is gone (BC8). What breaks the build is limited to custom EventStoreClient conformances, exhaustive switches over EventStoreClientError, a direct swift-kurrentdb requirement below 3.0.0, a bare CustomMetadata in a file that imports KurrentDB (SB4), and an unknown key in projection-model.yaml (SB5). The public signatures of Usecase, EventStore, EventSourcingRepository and KurrentStorageCoordinator do not change.

Who is affected

If your project…Read
depends on swift-kurrentdb directlySB3 swift-kurrentdb ≥ 3.0.0
names CustomMetadata in a file that imports KurrentDBSB4
reads aggregates through KurrentStorageCoordinator from tasks that can be cancelledBC7
has a projection-model.yamlSB5
reads streams of links (linkTo projections, $ce-, $et-) through LiveEventStoreClient or KurrentStorageCoordinatorBC8
implements or wraps EventStoreClientSB1, BC1
has a switch over EventStoreClientError without defaultSB2
adopts withUnitOfWorkBC2–BC6, behaviour inside a scope, rules inside the block, projections
only uses AggregateRoot / DomainEvent / Usecase and the built-in stores, without withUnitOfWorkbump the version and run the tests; also SB4, SB5, BC7 and BC8 if they apply

🤖 AI Migration Manifest (machine-readable)

If you are an AI agent upgrading a project that depends on swift-ddd-kit from 1.4 to 1.5, consume the JSON below. Each rule has a kind, mechanical (whether plain text replacement is enough), before/after (new rules give only after) and action. Apply order: source-breaking first so the project compiles, then check every behaviour-change (the compiler will not point these out). scope-rule entries apply to code that runs inside withUnitOfWork. scope says where to look.

{
  "schema": "swift-ddd-kit-migration/v1",
  "package": "swift-ddd-kit",
  "from": "1.4",
  "to": "1.5",
  "domainLayerImpact": "none",
  "applyOrder": ["source-breaking", "behaviour-change", "new", "scope-rule"],
  "rules": [
    {
      "id": "SB1",
      "kind": "source-breaking",
      "mechanical": false,
      "scope": "types conforming to EventStoreClient (wrappers, decorators, custom fakes)",
      "before": "no identity requirement",
      "after": "var identity: ObjectIdentifier { base.identity }   // a wrapper forwards the wrapped client's identity",
      "action": "Implement identity (no default; compile error otherwise). A wrapper forwards the identity of the client it wraps. Never return a constant shared by clients of different clusters: only clients with the same identity commit together in one unit of work."
    },
    {
      "id": "SB2",
      "kind": "source-breaking",
      "mechanical": false,
      "scope": "exhaustive switch statements over EventStoreClientError without a default",
      "before": "switch error { case .streamNotFound: ... }",
      "after": "add cases .consistencyViolations([StreamConflict]) and .atomicAppendUnsupported",
      "action": "Handle the two new enum cases or add a default."
    },
    {
      "id": "SB3",
      "kind": "source-breaking",
      "mechanical": true,
      "scope": "Package.swift of the downstream project, only if it depends on swift-kurrentdb directly",
      "before": ".package(url: \"https://github.com/gradyzhuo/swift-kurrentdb.git\", from: \"2.6.0\")",
      "after": ".package(url: \"https://github.com/gradyzhuo/swift-kurrentdb.git\", from: \"3.0.0\")",
      "action": "swift-ddd-kit 1.5 requires swift-kurrentdb 3.0.0. Raise any direct requirement to 3.0.0; a 2.x requirement no longer resolves next to it. Code that calls swift-kurrentdb itself follows https://gradyzhuo.github.io/swift-kurrentdb/documentation/kurrentdb/migrating-to-3.0."
    },
    {
      "id": "SB4",
      "kind": "source-breaking",
      "mechanical": true,
      "scope": "Swift files that import KurrentDB and also EventSourcing, KurrentSupport or DDDKit, and name CustomMetadata",
      "before": "KurrentStorageCoordinator",
      "after": "KurrentStorageCoordinator",
      "action": "swift-kurrentdb 3.0 adds its own CustomMetadata type, so a bare CustomMetadata is ambiguous in such a file. Qualify swift-ddd-kit's type as EventSourcing.CustomMetadata. Files that do not import KurrentDB, generated code included, are unchanged."
    },
    {
      "id": "SB5",
      "kind": "source-breaking",
      "mechanical": true,
      "scope": "projection-model.yaml files",
      "before": "a key the generator does not know was ignored, and a file that did not decode produced no models",
      "after": "both fail the build; the error names the model, the key and the known keys: category, createdEvents, deletedEvent, events, idField, idType, model",
      "action": "Build, then fix each key the error names. A misspelt key was ignored before, so its events were missing from the generated code: after fixing it, check that the read model now handles them as intended. A file with no YAML document (empty or comments only) still yields no models."
    },
    {
      "id": "BC1",
      "kind": "behaviour-change",
      "mechanical": false,
      "scope": "types conforming to EventStoreClient, including wrappers around LiveEventStoreClient",
      "before": "no appendAtomically requirement",
      "after": "func appendAtomically(_ batches: [StreamBatch]) async throws -> [StreamBatchResult] { try await base.appendAtomically(batches) }",
      "action": "Without it the conformance still compiles (deprecated default, warning), but a unit of work that writes two or more streams through it throws EventStoreClientError.atomicAppendUnsupported at commit. Implement or forward it."
    },
    {
      "id": "BC2",
      "kind": "behaviour-change",
      "mechanical": false,
      "scope": "usecases that publish events (EventBus.publish, notifications) right after repository.save",
      "before": "try await repository.save(aggregateRoot: x); try await eventBus.publish(event: e)",
      "after": "if let work = UnitOfWork.current { try work.onCommitted { ... } } else { ... }",
      "action": "Inside withUnitOfWork the publish happens before the commit. Register it with onCommitted when a unit of work is running, publish immediately otherwise."
    },
    {
      "id": "BC3",
      "kind": "behaviour-change",
      "mechanical": false,
      "scope": "composition roots that give repositories different KurrentDBClient instances (e.g. one KurrentDBPool.borrow() each)",
      "before": "any KurrentDBClient of the cluster",
      "after": "every repository that writes in one unit of work, or reads what the block saved, wraps the same KurrentDBClient instance",
      "action": "Identity is the client instance, not the cluster. The first write through a second instance throws DDDError.operationNotAllow. A read through another instance neither binds the unit of work nor sees its staged events, only what the server has; a read error through it still fails the unit of work like any store error. A usecase that reads what an earlier usecase in the same block saved needs a repository over the same KurrentDBClient instance."
    },
    {
      "id": "BC4",
      "kind": "behaviour-change",
      "mechanical": false,
      "scope": "custom repositories overriding find/save/delete/purge; code calling store.append or store.purge directly",
      "before": "n/a (new in 1.5)",
      "after": "only EventSourcingRepository's default implementations refuse non-participating stores inside a unit of work and fail the unit of work on store errors",
      "action": "Inside withUnitOfWork, call the default repository methods. Direct store.append or store.purge on InMemoryEventStore or PersistentEventStore still writes or purges immediately (a purge is permanent, even when the block then throws); an overriding repository does not fail the unit of work on store errors."
    },
    {
      "id": "BC5",
      "kind": "behaviour-change",
      "mechanical": false,
      "scope": "handlers that keep using aggregate instances after withUnitOfWork returns or throws",
      "before": "n/a (new in 1.5)",
      "after": "find the aggregate again after the block",
      "action": "Inside a unit of work the version after save is predicted; a differing server revision (e.g. a soft-deleted stream recreated continues from the old tail + 1) is only logged. After a block that threw, the instance still reflects the discarded save."
    },
    {
      "id": "BC6",
      "kind": "behaviour-change",
      "mechanical": false,
      "scope": "EventMetadata types saved inside withUnitOfWork",
      "before": "metadata stored as raw JSON bytes",
      "after": "a unit of work of two or more streams sends metadata as protobuf Value (AppendRecords properties)",
      "action": "Inside a unit of work, metadata must encode to a JSON object, or save throws operationNotAllow. NaN and ±infinity throw EncodingError from JSONEncoder at save (not operationNotAllow), in and out of a unit of work, as before 1.5. Inside a unit of work that writes two or more streams every number travels as the nearest Double: integers beyond ±2^53, including beyond 64 bits (e.g. a large Decimal), are rounded without an error, so store them as strings. On read the server adds $schema.name and $schema.format keys to every event of a commit of two or more streams: compare decoded structs, not raw bytes. An event saved with nil metadata is stored with only those keys; LiveEventStoreClient reads metadata whose keys are exactly those two back as empty, so through KurrentStorageCoordinator and the projection runners it reads as no metadata, as before 1.5. Metadata that encodes to {} reads back as nil after such a commit. Reading with KurrentDBClient directly, or through MigrationUtility, still shows the two keys."
    },
    {
      "id": "BC7",
      "kind": "behaviour-change",
      "mechanical": false,
      "scope": "find and fetchEvents through KurrentStorageCoordinator in a task that can be cancelled",
      "before": "the read fetched every event before returning, so a cancelled task still got the whole stream",
      "after": "swift-kurrentdb 3.0 reads as it iterates; a cancelled task throws CancellationError from find or fetchEvents",
      "action": "Catch CancellationError where a cancelled task must not count as a failed read."
    },
    {
      "id": "BC8",
      "kind": "behaviour-change",
      "mechanical": false,
      "scope": "reads of link streams through LiveEventStoreClient.readStream or KurrentStorageCoordinator.fetchEvents",
      "before": "the read threw KurrentError.unservicableEventLink at the first link whose event is gone, or reported the stream as missing",
      "after": "the read skips such links, logs a warning for each (logger label LiveEventStoreClient, metadata stream and link) and returns the remaining events",
      "action": "Remove wrappers that caught unservicableEventLink around readStream. Code that relied on the error to detect deleted sources must check the source stream itself."
    },
    {
      "id": "N1",
      "kind": "new",
      "mechanical": false,
      "scope": "handlers that must write several usecases' or aggregates' events together",
      "after": "try await withUnitOfWork { work in ... }   // EventSourcing: withUnitOfWork, UnitOfWork, UnitOfWorkBackend, UnitOfWorkParticipant",
      "action": "Optional. Wrap the usecase calls of one operation in withUnitOfWork; KurrentStorageCoordinator takes part, InMemoryEventStore and PersistentEventStore do not."
    },
    {
      "id": "N2",
      "kind": "new",
      "mechanical": false,
      "scope": "catch clauses for DDDError.commitConflict",
      "after": "DDDError.commitConflict(conflicts:) and error.commitConflicts (one entry per conflicting stream, batch order; code still 501)",
      "action": "Optional. error.commitConflict still returns the first conflict."
    },
    {
      "id": "N3",
      "kind": "new",
      "mechanical": false,
      "scope": "KurrentSupport seam",
      "after": "EventStoreClient.appendAtomically(_:), StreamBatch, StreamBatchResult, StreamConflict; InMemoryEventStoreClient implements it",
      "action": "Optional; see BC1 for wrappers."
    },
    {
      "id": "N4",
      "kind": "new",
      "mechanical": false,
      "scope": "EventSourcingProjector.execute(input:)",
      "after": "when buildReadModel or apply throws, execute still returns nil and now logs a warning with the id and the error (logger label )",
      "action": "None. Watch for the warning to find projectors that returned nil because of an error."
    },
    {
      "id": "R1",
      "kind": "scope-rule",
      "mechanical": false,
      "scope": "calls of withUnitOfWork",
      "before": "a usecase's execute(input:) calls withUnitOfWork, or a block calls code that opens another scope",
      "after": "only the handler calls withUnitOfWork; shared logic is a function that opens no scope",
      "action": "No nesting: withUnitOfWork inside a unit of work throws operationNotAllow. Usecases never call it; handlers do. Shared logic goes in a function that does not open a scope."
    },
    {
      "id": "R2",
      "kind": "scope-rule",
      "mechanical": false,
      "scope": "do/catch inside the block",
      "before": "do { try await usecase.execute(input: i) } catch { return .failed(error) }   // inside the block",
      "after": "do { return .ok(try await withUnitOfWork { _ in try await usecase.execute(input: i) }) } catch { return .failed((error as? DDDError)?.userInfos[\"cause\"] as? any Error ?? error) }",
      "action": "Do not catch a usecase's error inside the block: let it leave the block, or call try work.fail(error) when the block must go on. Either way withUnitOfWork throws and drops the block's result, so map the error to a failure output outside withUnitOfWork; fail(_:) and failed repository calls put the original error in userInfos[\"cause\"]."
    },
    {
      "id": "R3",
      "kind": "scope-rule",
      "mechanical": false,
      "scope": "Task { } and Task.detached inside the block",
      "before": "Task { try await repository.save(aggregateRoot: x) }   // inside the block",
      "after": "try await repository.save(aggregateRoot: x)   // awaited before the block returns",
      "action": "Do not move a save into Task { }. A save that runs after the block ended throws operationNotAllow. Do not move one into Task.detached or into code that does not run in the block's task tree (a NIO future callback, a DispatchQueue block, a timer) either: it does not see the unit of work, so the save writes at once and stays written when the block throws or the commit fails. Await everything before returning; run usecases in parallel with async let or a TaskGroup."
    },
    {
      "id": "R4",
      "kind": "scope-rule",
      "mechanical": false,
      "scope": "side effects after save",
      "before": "try await repository.save(aggregateRoot: x); try await eventBus.publish(event: e)",
      "after": "if let work = UnitOfWork.current { try work.onCommitted { ... } } else { ... }",
      "action": "Publish through work.onCommitted (see BC2)."
    },
    {
      "id": "R5",
      "kind": "scope-rule",
      "mechanical": false,
      "scope": "async let / TaskGroup inside the block",
      "before": "async let a: Void = change(id: x); async let b: Void = change(id: x)   // the same aggregate",
      "after": "async let a: Void = change(id: x); async let b: Void = change(id: y)   // different aggregates",
      "action": "Concurrent usecases on different aggregates are fine. Concurrent changes to the same aggregate are not supported: when both tasks find it before either saves it, the second save throws commitConflict."
    }
  ],
  "downstreamProcedure": [
    "Bump swift-ddd-kit to from: \"1.5.0\"; raise any direct swift-kurrentdb requirement to 3.0.0 (SB3).",
    "In files that import KurrentDB, write EventSourcing.CustomMetadata for swift-ddd-kit's type (SB4).",
    "In custom EventStoreClient conformances, implement or forward identity and appendAtomically (SB1, BC1).",
    "Handle the new EventStoreClientError cases (SB2).",
    "Build; run the test suite.",
    "Before adopting withUnitOfWork: move post-save publishing to onCommitted (BC2), give the repositories that write together, or read what the block saved, one KurrentDBClient instance (BC3), check metadata types (BC6), and follow R1–R5."
  ]
}

Source-breaking changes

These stop existing code from compiling, and the compiler points at each place.

SB1  protocol  EventStoreClient.identity has no default

Custom EventStoreClient conformances (wrappers, decorators, hand-written fakes) must implement var identity: ObjectIdentifier { get }. Inside one unit of work only clients with the same identity commit together. There is no default on purpose: two clusters taken for one would send events to the wrong cluster. LiveEventStoreClient reports the identity of the KurrentDBClient it wraps; every InMemoryEventStoreClient instance is an identity of its own. A wrapper forwards the identity of the client it wraps, and forwards appendAtomically(_:) too (BC1):

struct LoggingClient: EventStoreClient {
    let base: any EventStoreClient
    // ...other requirements...
+   var identity: ObjectIdentifier { base.identity }
+   func appendAtomically(_ batches: [StreamBatch]) async throws -> [StreamBatchResult] {
+       try await base.appendAtomically(batches)
+   }
}

SB2  enum case  New EventStoreClientError cases

CaseThrown when
consistencyViolations([StreamConflict])appendAtomically found streams whose expected revision did not hold; nothing was written. Never empty. KurrentStorageCoordinator turns it into DDDError.commitConflict(conflicts:).
atomicAppendUnsupportedthe conformance relies on the deprecated default of appendAtomically(_:).

An exhaustive switch over EventStoreClientError without a default must handle both.

SB3  dependency  swift-kurrentdb ≥ 3.0.0

swift-ddd-kit 1.5 requires swift-kurrentdb 3.0.0. If your Package.swift depends on swift-kurrentdb directly, raise the requirement too: a 2.x requirement no longer resolves next to swift-ddd-kit. Code of yours that calls swift-kurrentdb itself (reads, EventData, KurrentDBClient) follows swift-kurrentdb's Migrating from 2.x to 3.0.

- .package(url: "https://github.com/gradyzhuo/swift-kurrentdb.git", from: "2.6.0")
+ .package(url: "https://github.com/gradyzhuo/swift-kurrentdb.git", from: "3.0.0")

SB4  type name  CustomMetadata is ambiguous next to import KurrentDB

swift-kurrentdb 3.0 adds a type named CustomMetadata. In a file that imports KurrentDB and EventSourcing, KurrentSupport or DDDKit, a bare CustomMetadata no longer compiles: 'CustomMetadata' is ambiguous for type lookup in this context. Name swift-ddd-kit's type with its module. Files that do not import KurrentDB, generated events and mappers included, are not affected.

- KurrentStorageCoordinator<OrderProjector, CustomMetadata>(client: client, eventMapper: mapper)
+ KurrentStorageCoordinator<OrderProjector, EventSourcing.CustomMetadata>(client: client, eventMapper: mapper)

SB5  generator  An unknown key in projection-model.yaml fails the build

The generator ignored a key it did not know, and a file that did not decode produced no models. Both now fail the build. The error names the model, the key and the known keys (category, createdEvents, deletedEvent, events, idField, idType, model):

Unknown key "createdEvent" (did you mean "createdEvents"?) in projection model "OrderList".

A misspelt key was ignored before, so its events were missing from the generated code. After fixing the key, check that the read model now handles those events as intended. A file with no YAML document (empty, or comments only) still yields no models.

-   createdEvent: OrderCreated
+   createdEvents: OrderCreated

Behaviour changes

The compiler will not point these out They compile unchanged but behave differently, mostly once code runs inside withUnitOfWork. Check each one against your code and tests.

BC1  runtime  Wrappers must forward appendAtomically(_:)

EventStoreClient gains appendAtomically(_:). The protocol extension provides a deprecated default, so an existing conformance compiles, with a deprecation warning; but a unit of work that writes two or more streams through it throws EventStoreClientError.atomicAppendUnsupported at commit. Forward it as in SB1.

BC2  usecase  Publishing right after save

A usecase that calls EventBus.publish right after repository.save publishes before the commit when it runs inside withUnitOfWork, so subscribers can see events that are never written. To be right inside and outside a unit of work:

if let work = UnitOfWork.current {
    try work.onCommitted { try await notifier.send(.quotingCreated(id)) }
} else {
    try await notifier.send(.quotingCreated(id))
}

BC3  client  One KurrentDBClient instance per unit of work

Writes in one unit of work commit together only through clients with the same identity, and the identity is the KurrentDBClient instance, not the cluster. Coordinators built with init(client: KurrentDBClient, eventMapper:) over one instance share the unit of work, so a composition root that passes one client everywhere needs no change. Two instances connected to the same cluster (two KurrentDBPool.borrow() results, say) count as two: the first write through the second one throws DDDError.operationNotAllow. A read through another instance neither binds the unit of work nor sees its staged events, only what the server has: only coordinators whose client has the unit of work's identity see them. A read error through it still fails the unit of work like any store error. A usecase that reads what an earlier usecase in the same block saved needs a repository over the same KurrentDBClient instance.

BC4  repository  The check lives in EventSourcingRepository's default implementations

Inside a unit of work, the default save and purge refuse a store that cannot take part, and errors from store calls in the default find, save, delete and purge fail the unit of work even when the caller catches them. Code that calls store.append or store.purge directly on a non-participating store still writes or purges at once inside a unit of work (a purge is permanent, even when the block then throws), and a repository that overrides those methods gets neither the refusal nor the automatic failure.

BC5  aggregate  Do not reuse aggregate instances after a unit of work

Inside a unit of work, an aggregate's version after save is the revision the commit is predicted to give it. When the server returns another one, the commit logs a warning and succeeds: the server's revision is the true one. That happens, for example, when a soft-deleted stream is recreated: it continues from the old tail + 1 instead of 0. After a block that threw, the instance still reflects the discarded save. Find aggregates again after the block.

BC6  metadata  Metadata inside a unit of work

A unit of work that writes two or more streams sends metadata as protobuf Value (AppendRecords properties) instead of raw JSON bytes, so every save inside a unit of work checks that the metadata encodes to a JSON object. A type that encodes to a scalar (a String-backed enum, say) throws DDDError.operationNotAllow(operation: "save", …) at save, not at commit; nil metadata is not checked, and outside a unit of work such metadata is still written as before.

  • NaN and ±infinity throw EncodingError from the coordinator's JSONEncoder at save, not operationNotAllow, inside a unit of work and outside it, as before 1.5. Inside a unit of work the error also fails it.
  • Numbers are not checked further: inside a unit of work that writes two or more streams each one travels as the nearest Double, so an integer beyond ±2^53, including one beyond 64 bits such as a large Decimal, is stored rounded without an error. Store values whose every digit matters as strings.

Read back, the custom metadata of an event that a unit of work wrote to two or more streams also holds the server's $schema.name and $schema.format keys; a struct decodes as before, so compare decoded values, not raw bytes or dictionaries. Keys of your own that start with $ are kept.

An event saved with nil metadata (no EventMetadataContext) is stored with only those two keys. LiveEventStoreClient reads metadata whose keys are exactly $schema.name and $schema.format back as empty, so through KurrentStorageCoordinator and the projection runners the event reads as having no metadata, as before 1.5.

  • Metadata that encodes to {} (all fields optional and nil) reads back as nil after such a commit, and as a value with every field nil otherwise: treat both as no metadata.
  • Code that reads the stream with KurrentDBClient directly, and MigrationUtility, still see the two keys.
  • ContextForwarder treats metadata that holds only $schema.* keys as absent (decodeMetadata returns nil).

BC7  reads  A cancelled read throws

swift-kurrentdb 3.0 reads a stream as it is iterated. A find or fetchEvents through KurrentStorageCoordinator whose task is cancelled midway throws CancellationError; with 2.x the read had already fetched every event and returned normally. Catch CancellationError where a cancelled task must not count as a failed read.

BC8  reads  A link whose event is gone is skipped

A stream of links (a linkTo projection, $ce-, $et-) can hold a link whose event no longer exists, because the source stream was deleted, tombstoned, truncated or scavenged. LiveEventStoreClient.readStream threw KurrentError.unservicableEventLink at the first one, or reported the stream as missing, so KurrentStorageCoordinator.fetchEvents and a projector over such a stream failed. The read now skips these links, logs a warning for each (logger label LiveEventStoreClient, metadata stream and link) and returns the remaining events.

Remove wrappers that caught unservicableEventLink around readStream. Code that relied on the error to notice a deleted source must check the source stream itself.

Behaviour inside a scope

Everything here is new in 1.5 and applies only while withUnitOfWork runs. Outside a scope nothing changed.

How the scope ends

  1. The block returns or throws, and the scope closes at once. From then on work.fail(_:), work.onCommitted(_:) and work.withBackend(_:identity:make:_:) throw operationNotAllow, also from a Task started in the block, which still sees the scope as UnitOfWork.current. So a save that runs after the block throws instead of writing.
  2. The block threw (CancellationError included): nothing is committed, no hook runs, the error is rethrown.
  3. The scope was failed (by work.fail(_:) or by a repository error): nothing is committed, no hook runs, and withUnitOfWork throws DDDError.operationNotAllow(operation: "commit", reason: "unit of work failed") with the first cause in userInfos["cause"].
  4. Otherwise the staged writes commit. One stream goes through the same single-stream append as a plain save; two or more go through one AppendRecords call (KurrentDB 26.1+; an older server gives operationNotAllow(operation: "commit", reason: "server does not support AppendRecords (KurrentDB 26.1+)")). A conflict on any stream rejects everything with commitConflict and error.commitConflicts lists every conflicting stream; a purged stream gives streamPurged, also when other streams conflict.
  5. The onCommitted hooks run in registration order, outside the scope (UnitOfWork.current == nil): a save inside a hook writes directly and is not part of the commit. A throwing hook stops the later ones and its error is rethrown, but the commit stands.
Commit errors After commitConflict or streamPurged nothing was written. After any other commit error (transport, atomicAppendUnsupported, a server without AppendRecords) the writes may have landed, for example when the response was lost after the server committed: read the streams before running the block again.

Stores, reads and purge

  • Only KurrentStorageCoordinator takes part. save and purge through a repository over InMemoryEventStore or PersistentEventStore throw operationNotAllow; save does so even when the aggregate has no new events (outside a scope such a save still returns without calling the store). find is never refused. Tests use KurrentStorageCoordinator over InMemoryEventStoreClient: no server needed.
  • KurrentStorageCoordinator.purge throws operationNotAllow(operation: "purge", reason: "not allowed inside a unit of work"), also when called directly. A direct store.purge on InMemoryEventStore or PersistentEventStore is not refused: it purges at once and permanently, even when the block then throws.
  • Reads through a coordinator whose client has the scope's identity see the events the scope has staged, after the server's (read-your-writes). When another writer moved the stream past the revision a save in the scope expected, such a read throws commitConflict and fails the scope, instead of replaying overlapping revisions. Otherwise a read never creates, binds or fails on the scope's backend, so a usecase may read through a repository over another KurrentDBClient, but that read sees only what the server has (a read error through it still fails the unit of work, BC3). A usecase that reads what an earlier usecase in the same block saved needs a repository over the same KurrentDBClient instance.
  • A second save of the same stream must expect the revision the first one predicted, or it throws commitConflict at once; so do two aggregate types whose stream names collide.
  • Each usecase's EventMetadataContext<M>.withValue value travels with that usecase's events; repositories with different Metadata types can save in one scope.

Rules inside the block

  1. No nesting. withUnitOfWork inside a scope throws operationNotAllow and leaves the outer scope alone. A usecase does not call withUnitOfWork; it belongs to the handler. When two handlers share logic, extract a function that does not open a scope and let each handler wrap it.
  2. Do not do/catch a usecase's error inside the block. Let it leave the block, or call try work.fail(error) when the block must go on. Either way withUnitOfWork throws and drops what the block returned, so turn the error into a failure output outside it, taking the original error from userInfos["cause"]. What goes wrong otherwise is a usecase that saves, then throws, and is caught: store errors in the default repository methods fail the scope automatically (BC4), and this rule covers the rest.
  3. Do not move a save into Task { … }. A task that is not detached inherits the scope; a save it reaches after the block ended throws operationNotAllow, never writes directly and never joins a batch that was already committed, and a withUnitOfWork in it throws too. Await everything before returning.
  4. Do not move a save out of the task tree either. Task.detached, and code that does not run in the block's task tree (a NIO future callback, a DispatchQueue block, a timer), do not see the scope at all (UnitOfWork.current is nil): a save there writes to the store at once, is not part of the commit, and stays written when the block throws or the commit fails. Use async let or a TaskGroup to run usecases in parallel inside the block.
  5. Publish after the commit. A usecase that calls EventBus.publish right after save publishes before the commit inside a scope; use if let work = UnitOfWork.current { try work.onCommitted { … } } else { … } (BC2).
  6. Different aggregates may run concurrently, the same one may not. async let and TaskGroup over different aggregates are fine; when two tasks both find the same aggregate before either saves it, the second save throws commitConflict.
let quoting = try await withUnitOfWork { work in
    let quoting = try await createQuotingCaseService.execute(
        input: .init(operatorId: input.operatorId, name: input.name))
    try await openBillingAccountService.execute(input: .init(for: quoting.id))
    try work.onCommitted { try await notifier.send(.quotingCreated(quoting.id)) }   // after the commit
    return quoting
}

Projections run on subscription runners, not inside a scope

Do not run a projector synchronously inside withUnitOfWork Every read inside a scope through a KurrentStorageCoordinator over the same client instance as the scope's writes sees the staged events, including an EventSourcingProjector called from the block. Read model snapshots go to another store and are not part of the unit of work, so such a projector folds events that a failed commit never writes, and its snapshot runs ahead of the event store. Run projections on the KurrentProjection subscription runners: they run in their own task, outside any scope, and see only committed events.

Additions

None of these requires changes to existing code.

IDAdditionNotes
N1withUnitOfWork, UnitOfWork, UnitOfWorkBackend, UnitOfWorkParticipant (EventSourcing)The scope and the hooks for store authors. work offers id, isFailed, try work.fail(_:) and try work.onCommitted(_:). See the README section Compose Usecases with withUnitOfWork.
N2DDDError.commitConflict(conflicts:), error.commitConflicts (DDDCore)One entry per conflicting stream, in batch order; still code 501. error.commitConflict returns the first.
N3EventStoreClient.appendAtomically(_:), StreamBatch, StreamBatchResult, StreamConflict (KurrentSupport)Atomic multi-stream append through KurrentDB's AppendRecords; InMemoryEventStoreClient implements it too. KurrentStorageCoordinator is a UnitOfWorkParticipant.
N4Warning from EventSourcingProjector.execute(input:) (EventSourcing)When buildReadModel or apply throws, execute still returns nil and now logs a warning with the id and the error (logger label <ProjectorType>).

Upgrade checklist

Fix what breaks the build first, then check the behaviour changes.

  1. Bump dependencies — swift-ddd-kit to from: "1.5.0"; a direct swift-kurrentdb requirement to 3.0.0 (SB3).
  2. CustomMetadata next to import KurrentDB — write EventSourcing.CustomMetadata (SB4).
  3. Custom EventStoreClient — implement or forward identity and appendAtomically(_:); check that no appendAtomically deprecation warning is left (SB1, BC1).
  4. projection-model.yaml — fix each key the build error names, then check the read models that gain events (SB5).
  5. Exhaustive switch — handle consistencyViolations and atomicAppendUnsupported (SB2).
  6. Build + test — swift build, then run the test suite.
  7. Link streams — remove wrappers that caught unservicableEventLink around readStream (BC8).
  8. Before adopting withUnitOfWork — move post-save publishing to onCommitted (BC2), give the repositories that write together, or read what the block saved, one KurrentDBClient instance (BC3), check metadata types (BC6), keep projections on the subscription runners, and follow the rules inside the block.

Reference KurrentDB version

KurrentDB 26.1 or later; CI runs kurrentplatform/kurrentdb:26.1.3 A unit of work that writes two or more streams needs AppendRecords, which KurrentDB 26.1 introduced; one stream works on older servers too. CI's kurrent-live-contract job runs KurrentLiveContractTests, including the unit-of-work suites, against kurrentplatform/kurrentdb:26.1.3 started with standard projections (KURRENTDB_RUN_PROJECTIONS=All, KURRENTDB_START_STANDARD_PROJECTIONS=true). Re-run those tests when you upgrade KurrentDB.