[Pitch] Observable actors and actor snapshots

This is a back-to-back follow-on from the [Pitch] Observation performance and modeling improvements post. I am putting this up so firstly folks can have context for where that other pitch is going (and perhaps some additional motivation of why it is useful as an evolutionary step).

Introduction

Work that must not block the main thread lives in actors: downloads, databases, sync engines, device connections. The views that present that work live on the main actor, are written synchronously, and are driven by Observation. Today an actor can't be @Observable, and even if it could, a view can't read an actor's state, because reading it takes an await and a view's body can't suspend.

This proposal makes actors observable, and gives an actor a way to emit its state to synchronous readers, such as views, in a form that Observation can track.

For the readers who need a quick overview, here are the key highlights:

  1. Observable actors. @Observable can be applied to an actor and to a distributed actor. Its properties are tracked and notified as a class's are, for observers running on the actor.
  2. SnapshotSource. An actor that declares conformance to this protocol, and is @Observable, gets a synthesized Snapshot structure mirroring its observed properties and the means to read it without awaiting: latestSnapshot.
  3. Observable snapshots. Reading a property of a snapshot under observation tracking registers an access to it, as a view's body does. The observer is notified when the snapshot with the new value is published, never before, so reading the snapshot when told of a change always gives it.
  4. An explicit consistency model. The snapshot is eventually consistent with its actor: writes are coalesced into one refresh, readers see snapshots only move forward, and `await snapshot gives a value that is current as of the call.

Most developers will interact with this feature through the macro: the conformance is opt-in.The type ObservableSnapshotRegistrar is for the macro's expansion and for library authors who hand-write the protocol.

@Observable
actor Downloader: SnapshotSource {
  var status = "idle"
  var completed = 0
  var total = 1_000

  func run() async { /* ... writes `completed` as it goes ... */ }
}

struct DownloadView: View {
  let downloader: Downloader

  var body: some View {
    // Synchronous, on the main actor, and tracked.
    let snapshot = downloader.latestSnapshot
    ProgressView(value: Double(snapshot.completed), total: Double(snapshot.total))
    Text(snapshot.status)
  }
}

Motivation

Actors can't be observed

@Observable diagnoses an actor:

error: '@Observable' cannot be applied to actor type 'Downloader'

The reason given in the implementation is isolation: a class's properties are named by key paths, and a key path can't name an actor-isolated property, so the expansion for a class doesn't apply to an actor. The consequence is that the state with the most to say, that of long-running work off the main thread, is the state Observation can't describe. An actor that wants to be observed has nothing to adopt, so this leaves developers to invent their own notification mechanism, or they don't have one.

A view can't read an actor

Suppose the actor were observable. A view would still be unable to use it:

  • Reading an actor's property from outside it takes an await. A view's body is synchronous and can't suspend.
  • Observation tracking is built on synchronous reads. A tracked closure records the properties it reads as it runs; there is no way to record a read that suspends.
  • The values of several properties read across separate awaits can each come from a different moment. A progress bar showing completed from one moment and total from another is wrong in a way no individual read reveals.

The status quo is a hand-written mirror

What code does today is often mirror the actor's state into a main-actor class, and have the views observe that:

actor Downloader {
  private(set) var completed = 0
  private(set) var total = 1_000
  // ...
}

@MainActor @Observable
final class DownloaderModel {
  var completed = 0
  var total = 1_000

  init(_ downloader: Downloader) {
    Task {
      // Poll, or have the actor call back for every change, and copy:
      for await (completed, total) in downloader.progressStream {
        self.completed = completed
        self.total = total
      }
    }
  }
}

Every part of this is a place to go wrong. The stream, and the copy of each property into the model, are written by hand for each actor and drift from it as the actor grows. Each change costs a hop to the main actor, so a burst of a thousand writes is a thousand hops, rather than the one update the screen has time to show. Updating two properties that belong together, such as completed and total, takes two assignments, between which a view can render a state that never existed. And the model is a second source of truth: the one a view shows can be behind the actor's with no way for the view to know.

What's wanted

A view wants to read a value of the actor's state, synchronously, as it reads a model's properties; to be told when what it read has changed; and to find, when told, that the new state is what it reads. The cost of providing that should be paid by the actor, at its own pace, and not by the main actor on each write.

Proposed solution

Observable actors

In short a simple chang: @Observable is accepted on an actor and on a distributed actor:

@Observable
actor Counter {
  var count = 0
}

An actor's properties are tracked and notified as a class's are. Observation works for code running on the actor, such as a withObservationTracking called from a method of the actor. No key path can name an actor-isolated property, so, as for a noncopyable struct, the expansion identifies each property by its property index alone, through the property index-only registrar entry points, and an Event can't say which property changed.

SnapshotSource

An actor that also declares SnapshotSource is a source of snapshots:

@Observable
actor Counter: SnapshotSource {
  var name = "test"
  var index = 0
}

@Observable then synthesizes a Snapshot structure holding a copy of each observed property, and the members of the protocol that read it:

let counter = Counter()

// Synchronous, from anywhere, without awaiting:
let name = counter.latestSnapshot.name

// Current as of the access:
let now = await counter.snapshot

latestSnapshot is nonisolated, so it can be read from the main actor or any other context. It is the most recent snapshot the actor has published. A write to the actor doesn't change it; it invalidates it, and a refresh, scheduled on the actor, publishes the actor's state as a new snapshot. The snapshot is an ordinary Sendable value: reading latestSnapshot copies it out, which is a retain for each property that holds a reference.

Observing a snapshot

A property of a snapshot is tracked: reading it under withObservationTracking, as a view's body does, registers an access. The notification of a change to it is sent when the refresh publishes the snapshot, after the snapshot is readable, so an observer that reads the snapshot in response reads the new values:

withObservationTracking(options: [.willSet]) {
  render(counter.latestSnapshot.name)
} onChange: { _ in
  // Here `counter.latestSnapshot.name` is the existing name and is ready to claim an invalidation on the next suspension point.
}

These notifications are separate from the actor's own, which are sent at the write and are for observers on the actor. A view observes the snapshot and never sees the actor's.

The consistency model

The snapshot is eventually consistent with the actor:

  • Convergence. After a write, the published snapshot reaches the actor's state once the refresh runs, which is no earlier than the writing job's next suspension point.
  • Read your notifications. An observer is never notified of a change before the snapshot that has it is published.
  • Monotonic reads. A reader sees the previous snapshot or a newer one, never an older one.
  • Coalescing. A burst of writes is one refresh and one notification per changed property, with the final values. Intermediate values might never be visible through the snapshot.
  • Consistent contents. All the values of one snapshot come from a single job on the actor. Two separate reads of latestSnapshot may straddle a refresh; reading one latestSnapshot into a local and then its properties doesn't.

For a read that must be current as of now, await snapshot refreshes first and returns a snapshot taken at that point.

As an illustration, a download that writes completed a thousand times, suspending every hundred, is observed by a progress bar through eleven renders, each a published and consistent state, while a label reading only status re-renders only when status changes.

Choosing what is in the snapshot

The snapshot has what @Observable observes. @ObservationIgnored leaves a property out of both:

@Observable
actor Importer: SnapshotSource {
  var progress = 0.0
  @ObservationIgnored var session: URLSession   // not `Sendable`: not observed, not in the snapshot
}

A property of a SnapshotSource needs a default value, or an optional type, since the snapshot starts out holding the initial values.

Detailed design

Observable actors

Macro changes

@Observable no longer diagnoses an actor. For an actor or a distributed actor the accessors make only property index-only calls, in every build, as for a noncopyable struct:

// Counter's `count` accessors expand (in part) to:
get { access(propertyIndex: 0); return _count }
set {
  guard shouldNotifyObservers(_count, newValue) else { _count = newValue; return }
  withMutation(propertyIndex: 0) { _count = newValue }
}
_modify {
  access(propertyIndex: 0)
  _$observationRegistrar.willSet(propertyIndex: 0)
  defer { _$observationRegistrar.didSet(propertyIndex: 0) }
  yield &_count
}

Unlike a noncopyable struct's, an actor's withMutation(propertyIndex:_:) is not mutating and passes nothing to its closure. The closure is formed in the setter, which is isolated to the actor, and runs there, so it mutates the actor directly:

internal func withMutation<MutationResult, Failure: Error>(
  propertyIndex: Int,
  _ mutation: () throws(Failure) -> MutationResult
) throws(Failure) -> MutationResult {
  try _$observationRegistrar.withMutation(propertyIndex: propertyIndex, mutation)
}

The synthesized access(propertyIndex:) and withMutation(propertyIndex:_:), and the registrar itself, are isolated to the actor rather than nonisolated, because a distributed actor can't have a nonisolated stored property. (The registrar of a SnapshotSource actor, which can't be distributed, is nonisolated: latestSnapshot reads it from outside the actor.) The accessors are isolated in any case, and nothing outside the actor calls them. shouldNotifyObservers is nonisolated as elsewhere, and the Observable conformance is nonisolated.

Limitations

  • An actor's synchronous initializer is not isolated, so it can't assign a property that has a default value through its accessors (self.count = count calls the setter). An async initializer is isolated and can.
  • As for a noncopyable struct, a property with no property index (one declared in an #if) is an error rather than silently untracked, and a type can't customize observation with access(keyPath:) or withMutation(keyPath:_:).
  • The expansion calls the property index-only entry points unconditionally, so an observable actor deploying to older runtimes must be marked @available.

SnapshotSource

@available(SwiftStdlib 6.5, *)
public protocol SnapshotSource: Actor {
  associatedtype Snapshot: Sendable

  /// A snapshot of the actor's current state, which is also published as the
  /// latest snapshot.
  var snapshot: Snapshot { get async }

  /// The most recent snapshot the actor has published, readable without
  /// awaiting it.
  nonisolated var latestSnapshot: Snapshot { get }
}

The synthesized Snapshot is an ordinary copyable structure.

The names say what each read gives. latestSnapshot is the most recent published snapshot, which lags a write until the refresh runs; snapshot is current as of the access. The name published… is avoided for the property, as it recalls Combine's @Published.

The conformance is recognized from the actor's inheritance clause (SnapshotSource or Observation.SnapshotSource); one declared in an extension isn't seen by the macro.

The synthesized members

@Observable
actor Downloader: SnapshotSource {
  var status = "idle"
  var completed = 0
}

This expands to the following:

struct Snapshot: Sendable {
  var _$registrar: Observation.ObservationRegistrar
  @ObservationTracked(propertyIndex: 0) var status = "idle"
  @ObservationTracked(propertyIndex: 1) var completed = 0
}

private nonisolated let _$observationRegistrar: ObservableSnapshotRegistrar<Snapshot> =
  .init(propertyCount: 2) { Snapshot(_$registrar: $0) }

private func makeSnapshot() -> Snapshot {
  var snapshot = Snapshot(_$registrar: _$observationRegistrar.registrar)
  snapshot._status = _status
  snapshot._completed = _completed
  return snapshot
}

internal func invalidateSnapshot(propertyIndex: Int) {
  _$observationRegistrar.invalidate(propertyIndex: propertyIndex, in: self) { $0.makeSnapshot() }
}

var snapshot: Snapshot {
  get async {
    _$observationRegistrar.refresh { makeSnapshot() }
    return makeSnapshot()
  }
}

nonisolated var latestSnapshot: Snapshot {
  _$observationRegistrar.latest
}

(makeSnapshot has a macro-unique name in the expansion; the members the protocol requires have the access level of the actor.) The actor's registrar, _$observationRegistrar, is the ObservableSnapshotRegistrar in place of the plain ObservationRegistrar of an actor that isn't a source of snapshots; the actor's access(propertyIndex:) and withMutation(propertyIndex:_:) call it as they would that one.

  • The property declarations repeat each property's own type annotation and initializer, so a property with only an initializer (var name = "test") has the type the initializer infers.
  • The Snapshot structure has the access level of the actor (public or package, else internal), and each of its properties that of the actor's property it mirrors, so a snapshot exposes no more than the actor does. The structure's level caps a property declared with a greater one, as for any member of a less visible type. A setter's level (public private(set) var) is left out, since a snapshot has no setter, and private becomes fileprivate: the snapshot is a nested type, so a private property would be out of sight of the code in the actor's file that sees the actor's own. A property without a modifier is internal, even on a public actor.
  • @ObservationTracked on a property of the Snapshot structure expands to a getter that registers an access with the snapshot's registrar before returning the value, and a fileprivate peer holding it. There is no setter: a snapshot is only read. The structure is recognized as a Sendable struct named Snapshot; the macro cannot see the actor that declares it.
  • A copy of a snapshot registers its accesses with the same registrar as the original. Reading a retained, stale copy under tracking is notified of the actor's later publications, though the copy's values don't change. A view that reads latestSnapshot afresh each time it is evaluated is unaffected; holding a copy across evaluations is a misuse that costs an extra evaluation.
  • The actor's own accessors call invalidateSnapshot(propertyIndex:): in set, after the equality guard, since a write observers aren't told of doesn't change the snapshot either, and at the start of _modify, which always notifies. invalidateSnapshot(propertyIndex:) is internal and isn't part of the protocol.
  • The property indices are the ones the actor's accessors use, including under @Observable(resolution: .object) and group:, so those choices apply to a snapshot's notifications too.
  • The Task that runs the refresh is created by the first write after a refresh, by invalidate(propertyIndex:in:make:). Later writes find the snapshot already invalid and do nothing more. It runs on the actor, and so can't start until the writing job reaches a suspension point.

ObservableSnapshotRegistrar

@available(SwiftStdlib 6.5, *)
public final class ObservableSnapshotRegistrar<Snapshot: Sendable>: Sendable {
  /// The registrar that a snapshot's properties register their accesses with.
  public let registrar: ObservationRegistrar

  public init(propertyCount: Int, initial: (ObservationRegistrar) -> Snapshot)

  // The actor's own observation: the property index entry points of ObservationRegistrar.
  public func access(propertyIndex: Int)
  public func willSet(propertyIndex: Int)
  public func didSet(propertyIndex: Int)
  public func withMutation<T, Failure: Error>(
    propertyIndex: Int,
    _ mutation: () throws(Failure) -> T
  ) throws(Failure) -> T

  /// A copy of the published snapshot.
  public var latest: Snapshot { get }

  public func invalidate<Source: Actor>(
    propertyIndex: Int,
    in source: Source,
    make: @escaping @Sendable (isolated Source) -> Snapshot
  )
  public func refresh(_ make: () -> Snapshot)
}

It owns the published snapshot and two registrars that are kept apart: the actor's own, which the actor's accessors notify at the write through the forwarding entry points, and the snapshot's, which is notified only at publication. It also owns the set of properties written since the last refresh. It is a class so that the task that runs the refresh can hold it; the actor holds the only other reference.

  • latest copies the published snapshot out with the lock held only for the copy.
  • invalidate(propertyIndex:in:make:) marks a property as written. If the snapshot was up to date before, it schedules a refresh on source, which calls make there. The set is a bitmask, one bit each for the first 63 property indices and one standing for all those after; it is touched only from the actor, so it needs no ordering.
  • refresh(_:) takes the set of written properties. If it's empty it returns. Otherwise it sends willSet for each property in the set, takes the lock to replace the published snapshot with the value make returns, releases it, and sends didSet for each. Notifications are sent outside the lock, so an observer that reads the snapshot when notified doesn't deadlock and finds the new values. make is called with the lock held and reads the actor, which the refresh runs on.
  • A property after the 63rd shares a bit, and so a refresh notifies all of them: observers of those may be told of a change that wasn't theirs, never missed one.

A snapshot reaches the registrar it registers with through its _$registrar field, so a snapshot held by a view keeps the registrar's shared state alive. Notifications of the actor's destruction (.deinit events) for observers of the snapshot may be delayed until those snapshots are released.

Diagnostics

  • @Observable on a SnapshotSource actor diagnoses a property that can't be in the snapshot: a declaration of several variables, which must be split, and a property with neither a default value nor an optional type. Both fixes are offered as marking the property @ObservationIgnored.
  • SnapshotSource on a distributed actor is diagnosed: latestSnapshot is nonisolated, and a distributed actor can't have nonisolated stored state for it to read. A distributed actor is otherwise observable as above.
  • A class or struct that names SnapshotSource gets the same expansion as without. The protocol inherits from Actor, so the conformance is the compiler's to reject.

@ObservationIgnored

@ObservationIgnored is documented to additionally leave a property out of the snapshot of a SnapshotSource. No separate macro was added: a property that isn't observed has no accessor to invalidate the snapshot, so it would be stale in it, and the macro has no other use there.

Source compatibility

All of the changes are additive.

  • Code that applied @Observable to an actor was an error and is not now. Nothing that compiled changes meaning.
  • SnapshotSource and ObservableSnapshotRegistrar are new top-level names in a module SwiftUI re-exports. See Alternatives considered for their naming.
  • @Observable's declared member names gain Snapshot, invalidateSnapshot, snapshot andlatestSnapshot. The macro generates them only for an actor that declares SnapshotSource, and declares each member's name only to say it may; no existing type's members change. Unlike the other names in the list, they are common ones, and it is worth confirming in review that an @Observable type with a member of the same name is unaffected.
  • An actor that declares its own snapshot, latestSnapshot or invalidateSnapshot(propertyIndex:) keeps it just like the other features of Observation: the macro skips a member the type already declares, as it does for the other members it synthesizes.

ABI compatibility

This proposal is purely additive: no existing symbol is removed or changes meaning, and the exported symbols are a strict superset of the current SDK's.

  • SnapshotSource and ObservableSnapshotRegistrar, with its initializer and methods, are new symbols with SwiftStdlib 6.5 availability.
  • Observable actors add none: they use the property index-only entry points of the previous proposal.
  • ObservableSnapshotRegistrar stores a Mutex and an Atomic in private properties of a non-frozen final class, so neither type is part of its ABI. No declaration is @frozen or @inlinable.
  • Macros have no ABI.

Implications on adoption

  • An actor adopts by writing @Observable, and a source of snapshots by also writing SnapshotSource. Neither changes the actor's ABI beyond the conformance, since the synthesized members other than the protocol's are internal or private.
  • Both require the new runtime. An observable actor's expansion calls the property index-only entry points unconditionally, so an actor deploying to older runtimes must be marked @available.
  • A view adopting a snapshot trades await for staleness: the snapshot it reads is the last one published. A view that must not show a stale value reads await snapshot in a task instead.

Alternatives considered

Key-path-based observation. This would need extensive compiler modifications around KeyPath types and may not actually provide any real benefit over index based solutions.
Leaving actors unobservable, and mirroring by hand. This is the status quo, and its costs are the motivation.
Notifying snapshot observers with the actor's registrar. A single set of notifications would be simpler, but they are sent at the write, before the refresh, so an observer would be told to read a snapshot that doesn't yet have the change. A view would render the stale value, re-register, and be notified again when the refresh published: a wasted render and a visible flicker for every change. A separate registrar, notified at publication, makes the order a guarantee.
Publishing on every write. Building and swapping the snapshot at each write costs a copy of every property per write, and a lock acquisition, on the actor's hot path. Deferring to a refresh coalesces a burst into one of each.
Refreshing synchronously when a job ends. There is no hook for the end of an actor's job; a task enqueued on the actor runs at the first opportunity after it, which is the same point.
A hand-written Snapshot. The author would repeat each property in a structure and write the copying; the two would drift. Synthesizing from the observed properties makes "observed" and "snapshotted" one set.
A separate @Snapshotted macro. Two macros on one actor, each with its own idea of which properties are included, would have to agree. A single expansion shares the property indices, the backing storage and the accessors.
A separate ignore macro. @ObservationSnapshotIgnored would allow a property that is observed on the actor but not in the snapshot. It is the more precise tool, at the price of a second way to exclude a property, and a non-Sendable property that is observed by code on the actor is rare enough. @ObservationIgnored meaning "not observed, and so not published" is one rule.
Reading the actor directly from a view. Making an actor's properties readable with a nonisolated accessor isn't memory-safe.
A noncopyable snapshot read by borrowing. An earlier design made Snapshot noncopyable and read it through a closure, withCurrentSnapshot(_:), taking it borrowing, so that only the properties the closure used were copied. In a view's body the closure copies the values out anyway, so the borrow saved nothing, and reading several properties meant one closure, or several locks and snapshots that might straddle a refresh. The closure was the cost of every read; a copyable value read through latestSnapshot is cheaper to write and keeps one snapshot's values together. A borrowing read could be added later for a snapshot too large to copy.
A non-escapable snapshot. snapshot returns across an await and the value is Sendable, neither of which a lifetime-bound value allows, and a closure's borrowing parameter already keeps a borrow from escaping it.

20 Likes

This is very interesting, thanks for digging into this direction!

Since you've mentioned support for distributed I feel invited to discuss if this is actually compatible/usable and what it would take to make it so. I think we're not far off from being able to pull this off for distributed, though it needs more thought than the proposal implies by saying you can put @Observable on distributed actor :thinking:

Distributed + SnapshotSource

  • SnapshotSource on a distributed actor is diagnosed: latestSnapshot is nonisolated, and a distributed actor can't have nonisolated stored state for it to read. A distributed actor is otherwise observable as above.

I worry about not having snapshots, as I think would imply we'd have to send all the updates over the wire which isn't something we'd want to do, since wire boundaries are expensive. Offering snapshots which we nicely coalesce (as you explained even for local ones) are more tangible though, so I'd like to discuss how that can work in distributed.

I don't think SnapshotSource is inherently incompatible with distributed actor because of the property there - as the proposal claims, there's other issues which make it tricky.

We would need the Snapshot to be compatible with a actor's ActorSystem.SerializationRequirement, but I'm thinking you may be able to just entirely side step having an opinion about this, and leave it to actor system implementations.

The protocol does require the var latestSnapshot to be implemented, but that just means we need to be able to get "latest snapshot for the actor". Indeed a remote actor reference cannot have stored nonisolated properties, but it can have computed ones, so this would be implemented as:

  extension MyCoolSystemDistributedSnapshotSource {
    nonisolated var latestSnapshot: Snapshot {
      actorSystem.snapshots.slot(for: self).latest   // works on a remote reference
    }
  }

It does mean that your macro a) can't implement this method, since it doesn't know how the actor system can get the snapshot for an actor/id, or b) that we'd have to provide a protocol ObservableActorDistributedActorSystem { func snapshots ... etc }.

The latter (b) is quite a lift, and I don't think we need to do it actually. We could just say that the macro doesn't implement that property on distributed actors so if you want to support that, you need to implement it "yourself". Where the yourself could just mean "your favorite actor system impl, maybe provides support for this, and therefore you just add: @Observable distributed actor Downloaded: MyCoolSystemObservableActor { ... } so we don't have to tie the language and stdlib to how these systems implement this, as long as they do it somehow.

I think this might work fine, and we don't have to commit any of these protocols to the stdlib, the implementations can offer this one by one, if they support observation.

The more problematic requirement is actually:

  var snapshot: Snapshot { get async }

so this can't be implemented with a distributed func call... unless we ignore errors which likely is not a good idea here? We'd rather not serve an outdated snapshot here after all...

So, in the end I suspect that we'd have to just keep SnapshotSource not compatible with distributed actor, however a system willing to implement it could do so easily if they provided:

// Does not have to be in stdlib! 
// Any specific ActorSystem can provide this if they choose to support observation.
protocol MyCoolSystemDistributedSnapshotSource: DistributedActor 
  where ActorSystem == MyCoolSystem { 
  associatedtype Snapshot: Sendable & Codable
  // can we make the Snapshot Codable...? Do we need @Observable(snapshot: .codable)?

  var snapshot: Snapshot { get async throws }
  nonisolated var latestSnapshot: Snapshot { get }
}

And I think this would be possible to implement... as long as the @Observable generated pieces remain functional if we'd apply them to such unknown to the macro type? :think:

This is quite interesting for some IPC but also for Wasm I think -- Like, it could be used with @sliemeobn's recent work CovalentRPC (was ActorRPC): distributed actors over HTTP, now playing in a browser near you. As long as we don't error out aggressively and let Simon implement such support protocol/extension :eyes:

Short version: Can @Observable work with distributed actor, and keep the Snapshot and "make snapshot" synthesis, but assume someone has to fill in the "matching blank" impls for the SnapshotSource protocol?

Actor lifetime

If I look at this correctly, an active subscription from someone observing keeps the actor alive right? I assume this is the same as with classes, just wanted to make sure I understood the implication here. This is very system dependent, so kinda hard to discuss in the abstract... but I think this is probably fine enough.

Wire compatibility

If we claim to support distributed actors, we should discuss the wire compatibility story. I think such system ties the remote and client very tightly, but it probably primarily means that evolving the state must be done in a compatible way, e.g. if you add more fields, make them optional if you may be talking to an "old" server etc.

There's some other inherent tying systems here, like renaming a field would break wire-compat, so we should call this out probably. It may be an acceptable tradeoff for quickly getting together a client/server though, and "freezing" the wire api at some point when one shipped it...

Could that work? Can we update a SnapshotSource with partial information we received on the wire, and this way mark that well "didn't have any state for var newField"? This may be acceptable for such inherently very coupled system.

Version negotiation etc fall onto the actual system making the connection, so if an user never wants to support drifting versions they'd know much earlier -- this isn't something Observable should worry about IMHO. If we did connect, there is clearly intent for this host to be "compatible enough" with the other side.


This is looking very promising, but if we're to promise distributed compatibility I'd like to see more discussion how that'll actually work in practice in this proposal.

6 Likes

I'm definitely not super familiar with distributed actors, but any reason we couldn't just make var snapshot: Snapshot { get async } potentially throwing from the start? That would let us model the normal actor and distributed actor SnapshotSources together:

protocol SnapshotSource {
    associatedtype Snapshot: Sendable
    associatedtype Failure: Error = Never
    
    var snapshot: Snapshot { get async throws(Failure) }
    
    nonisolated var latestSnapshot: Snapshot { get }
}

protocol ActorSnapshotSource: SnapshotSource, Actor where Failure == Never {}
protocol DistributedActorSnapshotSource: SnapshotSource, DistributedActor {}

protocol MyCoolSystemDistributedSnapshotSource: DistributedActorSnapshotSource
where Failure == any Error, ActorSystem == MyCoolSystem, Snapshot: Codable {}

extension MyCoolSystemDistributedSnapshotSource {
    nonisolated var latestSnapshot: Snapshot {
        actorSystem.snapshots.slot(for: self).latest
    }
}
1 Like

This is a very interesting idea, because I actually have quite a few cases where I use the pattern of having an actor that owns state (SSOT) and use snapshots to communicate this state to the user.

The pattern works very well, but (manually) keeping the actor definition and the snapshot in sync (for instance: adding a new field to the actor, making sure its also added to the snapshot) is error prone and has bitten me several times already.