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:
- Observable actors.
@Observablecan be applied to anactorand to adistributed actor. Its properties are tracked and notified as a class's are, for observers running on the actor. SnapshotSource. An actor that declares conformance to this protocol, and is@Observable, gets a synthesizedSnapshotstructure mirroring its observed properties and the means to read it without awaiting:latestSnapshot.- 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.
- 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'sbodyis 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 showingcompletedfrom one moment andtotalfrom 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
latestSnapshotmay straddle a refresh; reading onelatestSnapshotinto 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 = countcalls the setter). Anasyncinitializer 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 withaccess(keyPath:)orwithMutation(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
Snapshotstructure has the access level of the actor (publicorpackage, 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, andprivatebecomesfileprivate: the snapshot is a nested type, so aprivateproperty 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 apublicactor. @ObservationTrackedon a property of theSnapshotstructure expands to a getter that registers an access with the snapshot's registrar before returning the value, and afileprivatepeer holding it. There is no setter: a snapshot is only read. The structure is recognized as aSendablestruct namedSnapshot; 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
latestSnapshotafresh 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:): inset, 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:)isinternaland isn't part of the protocol. - The property indices are the ones the actor's accessors use, including under
@Observable(resolution: .object)andgroup:, 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.
latestcopies 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 onsource, which callsmakethere. 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 sendswillSetfor each property in the set, takes the lock to replace the published snapshot with the valuemakereturns, releases it, and sendsdidSetfor each. Notifications are sent outside the lock, so an observer that reads the snapshot when notified doesn't deadlock and finds the new values.makeis 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
@Observableon aSnapshotSourceactor 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.SnapshotSourceon adistributed actoris diagnosed:latestSnapshotisnonisolated, 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
SnapshotSourcegets the same expansion as without. The protocol inherits fromActor, 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
@Observableto an actor was an error and is not now. Nothing that compiled changes meaning. SnapshotSourceandObservableSnapshotRegistrarare new top-level names in a module SwiftUI re-exports. See Alternatives considered for their naming.@Observable's declared member names gainSnapshot,invalidateSnapshot,snapshotandlatestSnapshot. The macro generates them only for an actor that declaresSnapshotSource, 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@Observabletype with a member of the same name is unaffected.- An actor that declares its own
snapshot,latestSnapshotorinvalidateSnapshot(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.
SnapshotSourceandObservableSnapshotRegistrar, with its initializer and methods, are new symbols withSwiftStdlib 6.5availability.- Observable actors add none: they use the property index-only entry points of the previous proposal.
ObservableSnapshotRegistrarstores aMutexand anAtomicin private properties of a non-frozen final class, so neither type is part of its ABI. No declaration is@frozenor@inlinable.- Macros have no ABI.
Implications on adoption
- An actor adopts by writing
@Observable, and a source of snapshots by also writingSnapshotSource. Neither changes the actor's ABI beyond the conformance, since the synthesized members other than the protocol's areinternalorprivate. - 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
awaitfor staleness: the snapshot it reads is the last one published. A view that must not show a stale value readsawait snapshotin 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.