Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,28 @@ jobs:

- name: Test (${{ matrix.platform }})
run: ${{ matrix.command }}

docs:
name: Docs (warning-free)
runs-on: macos-26

steps:
- name: Checkout Code
uses: actions/checkout@v4

- name: Select Xcode
uses: maxim-lobanov/setup-xcode@v1
with:
xcode-version: latest-stable

- name: Docs build (warning-free)
run: |
set -o pipefail
xcodebuild docbuild \
-scheme StateManagement-Package \
-destination 'platform=macOS' \
2>&1 | tee docbuild.log
if grep -q "warning:" docbuild.log; then
echo "::error::docbuild emitted warnings — see log above"
exit 1
fi
6 changes: 3 additions & 3 deletions CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ The name of a Value. Always into one Container. For an Atomic value, a key path.
_Avoid_: ValueID, and calling the key path alone the Address of a Keyed value

**`$` Address**:
The name of the AsyncStrategy seam for a Value declared with `@AsyncState`: the path to the `AsyncState` wrapper rather than to the Value, plus a key when Keyed. Kicks, inbound verbs, and the awaitable read take it. Watch and Operations take the Address.
_Avoid_: calling it a Value or a fourth shape, and using the Address on the strategy seam
An Address spelled with `$`, naming the wrapper rather than the Value it wraps, plus a key when Keyed. A `Computed` has only this Address; an `@AsyncState` has it as the AsyncStrategy seam, with its Value at the plain path.
_Avoid_: reading `$` as one wrapper kind, and using the plain Address on the strategy seam

**Atomic value**:
A Value that is the whole fact at one name in a Container.
Expand All @@ -63,7 +63,7 @@ _Avoid_: derived state, selector, reducer
### AsyncStrategy

**AsyncStrategy**:
Owns read, write, and external side effects for Addresses declared with `@AsyncState`. The Environment owns one instance per type and always holds the Value. `onRead`, `onWrite`, and `onDrop` take the `$` Address and a Policy value.
Owns read, write, and external side effects for Addresses declared with `@AsyncState`. The Environment owns one instance per type and always holds the Value. `onRead`, `onWrite`, and `onDrop` take the `$` Address and a Policy value, as do the inbound verbs and the awaitable read; Watch and Operations take the Value's plain Address.
_Avoid_: Source, ExternalSource, Bridge, inbound Service, using Service for this, one instance per Address, persist Service as the write path

**Policy**:
Expand Down
2 changes: 2 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ Swift Package Index only *builds* the package (for the compatibility matrix) and
//===----------------------------------------------------------------------===//
```

- When linking an overloaded symbol, carry the full signature (``onRead(_:policy:current:)``). When two overloads differ only by type — DocC gives a readable disambiguator (``write(_:value:)-(_,Value)``) — use it. When overloads differ only by an `async`/`throws` effect (same erased parameter types), DocC's only disambiguator is an opaque hash (`-710qe`) — don't embed one; drop to a plain unlinked ``name`` instead. A hash breaks silently the next time the declaration changes and DocC recomputes it.

## Pull requests

- Branch off `main`.
Expand Down
4 changes: 2 additions & 2 deletions Sources/AsyncState/AsyncState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public final class AsyncState<S: AsyncStrategy, Key: Hashable, Entry, Value> {
self.init(wrappedValue: wrappedValue, policy: policy)
}

/// Designated init. App call site is unlabeled ``init(wrappedValue:_:)``.
/// Designated init. App call site is unlabeled ``init(wrappedValue:_:)-(Value,S.Policy)``.
/// A Satellite pins `S` by forwarding here; `S.Policy` does not reverse-infer `S`.
@_disfavoredOverload
public init(wrappedValue: Value, policy: S.Policy)
Expand All @@ -138,7 +138,7 @@ public final class AsyncState<S: AsyncStrategy, Key: Hashable, Entry, Value> {
self.init(wrappedValue: wrappedValue, policy: policy)
}

/// Designated keyed init. App call site is unlabeled ``init(wrappedValue:_:)``.
/// Designated keyed init. App call site is unlabeled ``init(wrappedValue:_:)-([Key:Entry],S.Policy)``.
/// A Satellite pins `S` by forwarding here; `S.Policy` does not reverse-infer `S`.
@_disfavoredOverload
public init(wrappedValue: [Key: Entry], policy: S.Policy)
Expand Down
5 changes: 3 additions & 2 deletions Sources/AsyncState/AsyncStrategy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ import Foundation
public protocol AsyncStrategy: AnyObject {
/// Failure type for `$property.status`. Use `Never` if this strategy cannot fail.
associatedtype Failure: Error
/// Per-Address value stored on ``AsyncState`` and passed to ``onRead``, ``onWrite``, and ``onDrop``.
/// Per-Address value stored on ``AsyncState`` and passed to ``onRead(_:policy:current:)``,
/// ``onWrite(_:policy:value:)``, and ``onDrop(_:policy:)``.
///
/// Default `Void` keeps type-only `@AsyncState(SomeStrategy.self)` for mocks. A non-Void Policy
/// requires a Policy value at the property wrapper.
Expand Down Expand Up @@ -72,7 +73,7 @@ public protocol AsyncStrategy: AnyObject {
)

/// The sourced Address died because this Address's Container dropped. Default is empty.
/// `policy` is the same value ``onRead`` received.
/// `policy` is the same value ``onRead(_:policy:current:)`` received.
func onDrop<Storage: StateContainer, Value>(
_ address: KeyPath<Storage, AsyncState<Self, NoKey, Value, Value>>,
policy: Policy
Expand Down
2 changes: 1 addition & 1 deletion Sources/AsyncState/AsyncStrategyEnvironment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ private let strategyLogger = Logger(
/// Restricted Environment for an AsyncStrategy. Standing for the Environment's lifetime.
///
/// Inbound verbs are hidden Sync operations. No `write`. No `read`. No `spawnService`.
/// Nested ``perform`` has no `write`. Dead Environment: inbound verbs no-op.
/// Nested `perform` has no `write`. Dead Environment: inbound verbs no-op.
///
/// > Important: A strategy retains this, never the ``SharedEnvironment``. The Environment owns the
/// strategy, so holding it back is a cycle; this type holds the Environment weakly and answers
Expand Down
2 changes: 1 addition & 1 deletion Sources/Combine/SMPublished.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import Foundation
/// It does not compose with ``AsyncState``: both are enclosing-instance wrappers over the same
/// stored Value, and a property carries one wrapper. Publish a sourced Value by watching it.
///
/// The class must use the default ``ObservableObjectPublisher``.
/// The class must use the default `ObservableObjectPublisher`.
///
/// - SeeAlso: <doc:Leftover-Combine>
@propertyWrapper
Expand Down
8 changes: 7 additions & 1 deletion Sources/Computation/Computed.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ A Computed is derived, not stored. Declare it with @Computed and reach it throug
/// (`fatalError`). The cycle cannot be broken at runtime because the read is what would supply the
/// value it is waiting for.
///
/// A Computed always runs, so reading one is never Optional — at a key just as much as atomically.
/// `Optional` marks what the framework knows may be missing, which a stored keyed entry is
/// (``StateContainer``) and a derivation is not. A genuinely partial derivation declares that
/// itself as `Computed<Key, Output?>` and returns `nil` for a key it declines.
///
/// In the following example `count` recomputes when `items` change; `isDone`
/// recomputes when that id's `done` flag changes.
/// ```swift
Expand All @@ -62,7 +67,8 @@ A Computed is derived, not stored. Declare it with @Computed and reach it throug
/// env.read(\ListContainer.items).count
/// }
///
/// // Keyed computed: derived per item id.
/// // Keyed computed: derived per item id. `done` is stored, so its keyed read is Optional;
/// // picking `false` for an absent entry is the author's answer, not the framework's.
/// @Computed<UUID, Bool> var isDone = { env, id in
/// env.read(\ListContainer.done, key: id) ?? false
/// }
Expand Down
2 changes: 1 addition & 1 deletion Sources/Consumers/SwiftUI/Watch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public struct Watch<Storage: StateContainer, Value>: DynamicProperty {

/// Create a `SwiftUI.Binding<Value>` binding that mutates the value, by performing a generic sync operation - ``InlineValueMutation``.
///
/// - Parameter mutation: A closure like a ``SyncOperation/perform(in:)``
/// - Parameter mutation: A closure like a `perform(in:)`
/// - Returns: SwiftUI Binding (`SwiftUI.Binding<Value>`).
public func binding(
mutation: @escaping (Value, SyncOperationEnvironment) -> Void
Expand Down
2 changes: 1 addition & 1 deletion Sources/Operations/Write.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import Foundation
///
/// Prefer named operations in production code. Use ``Write`` in previews and tests with
/// ``SharedEnvironment/seeded(_:)``, ``SharedEnvironment/seed(_:)``, or
/// ``SwiftUI/View/seedEnvironment(_:)``.
/// `SwiftUI.View.seedEnvironment(_:)`.
@MainActor public struct Write<Storage: StateContainer, Value>: SyncOperation {
private let apply: (SyncOperationEnvironment) -> Void

Expand Down
2 changes: 1 addition & 1 deletion Sources/Seeding/SeedOperationsBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import Foundation

/// Collects ``SyncOperation``s for ``SharedEnvironment/seeded(_:)``,
/// ``SharedEnvironment/seed(_:)``, and ``SwiftUI/View/seedEnvironment(_:)``.
/// ``SharedEnvironment/seed(_:)``, and `SwiftUI.View.seedEnvironment(_:)`.
@resultBuilder
public enum SeedOperationsBuilder {
public static func buildExpression(_ operation: any SyncOperation) -> [any SyncOperation] {
Expand Down
4 changes: 2 additions & 2 deletions Sources/Seeding/SharedEnvironment+Seeding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import Foundation

extension SharedEnvironment {
/// Creates a fresh ``SharedEnvironment`` and applies the builder’s operations in one
/// ``perform(_:file:line:)`` (single notify). Empty builders skip `perform`.
/// `perform(_:file:line:)` (single notify). Empty builders skip `perform`.
///
/// DEBUG only. Use for previews and tests.
public static func seeded(
Expand All @@ -28,7 +28,7 @@ extension SharedEnvironment {
return env
}

/// Applies the builder’s operations to this Environment in one ``perform(_:file:line:)``
/// Applies the builder’s operations to this Environment in one `perform(_:file:line:)`
/// (single notify). Empty builders skip `perform`.
///
/// DEBUG only. Use for previews and tests. ``seeded(_:)`` is the factory that creates a
Expand Down
2 changes: 2 additions & 0 deletions Sources/Telemetry/TraceContext.swift
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ public struct TraceContext: Sendable {
/// - Parameters:
/// - name: The human-readable name identifying the span operation.
/// - kind: The categorization target of the span (e.g. user-facing or internal).
/// - valueDescription: A debug description of the value to attach to the span. Populated only when `TelemetryInternal` is enabled.
/// - file: The source code file location. Defaults to caller `#fileID`.
/// - line: The source code line number. Defaults to caller `#line`.
/// - Returns: A non-copyable `Span` lifetime handle.
Expand Down Expand Up @@ -250,6 +251,7 @@ extension TraceContext {
/// - Parameters:
/// - name: The human-readable name of the scope.
/// - kind: The classification of the operation.
/// - valueDescription: A debug description of the value to attach to the span. Populated only when `TelemetryInternal` is enabled.
/// - file: The source code file location.
/// - line: The source code line.
/// - operation: The execution block representing the span duration.
Expand Down
4 changes: 2 additions & 2 deletions TestingSupport/StateReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@
import Foundation
import StateManagement

/// The sanctioned read for a test or a preview: a concrete ``EnvironmentService``, and therefore a
/// The sanctioned read for a test or a preview: a concrete `StateManagement.EnvironmentService`, and therefore a
/// Restricted Environment, so its reads carry a known reader.
///
/// It adds nothing. `read` for atomic, keyed, and computed Values is inherited, which is the point:
/// out-of-package callers get the reads without the core exposing an identity-free one and without
/// a Satellite reaching for `@testable` (ADR 0023).
///
/// Its reads subscribe, like any Service. Overriding ``serve()`` is not required; a reader that
/// Its reads subscribe, like any Service. Overriding `StateManagement.EnvironmentService.serve()` is not required; a reader that
/// never reacts simply leaves the subscription unused.
@MainActor public final class StateReader: EnvironmentService {}
58 changes: 58 additions & 0 deletions Tests/Computation/ComputedTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ final class ComputedState: StateContainer {
let e0 = env.read(\ComputedState.e, key: "0") ?? ""
return "\(a)-\(b)-\(e0)"
}

// A partial derivation: nothing in the Container decides readiness for an untracked id, so the
// author declares `Output` Optional and answers `nil`. The framework never adds that Optional.
var trackedIDs: Set<UUID> = []
var readiness: [UUID: Bool] = [:]

@Computed<UUID, Bool?> var isReady = { env, id in
guard env.read(\ComputedState.trackedIDs).contains(id) else { return nil }
return env.read(\ComputedState.readiness, key: id) ?? false
}
}

/// Service that reads the computation value on `serve`
Expand Down Expand Up @@ -139,6 +149,26 @@ struct MutateUnrelated: SyncOperation {
}
}

/// Brings an id under the derivation's rule, so `isReady` stops declining it.
struct TrackID: SyncOperation {
let id: UUID

func perform(in env: SyncOperationEnvironment) {
var tracked = env.read(\ComputedState.trackedIDs)
tracked.insert(id)
env.write(\ComputedState.trackedIDs, value: tracked)
}
}

struct SetReadiness: SyncOperation {
let id: UUID
let isReady: Bool

func perform(in env: SyncOperationEnvironment) {
env.write(\ComputedState.readiness, key: id, value: isReady)
}
}

struct ComputedTests {

///
Expand Down Expand Up @@ -267,4 +297,32 @@ struct ComputedTests {
#expect(service.lastComputationValue == initial)
}

// MARK: - Optional Output

/// A keyed Computed read is never Optional, because a Computed always runs. Partiality is the
/// author's to declare, so `nil` here is the closure's own answer and behaves like any other
/// output: cached per key, invalidated by the input that decided it.
@Test("A keyed Computed with Optional Output answers nil for a key it declines")
@MainActor func optionalOutputKeyedComputedDeclinesAKey() {
let env = SharedEnvironment()
let tracked = UUID()
let untracked = UUID()
env.perform(TrackID(id: tracked))
env.perform(SetReadiness(id: tracked, isReady: true))

let declined = ValueObserverProbe<ComputedState, Bool?>
.watch(computedKeyed: \.$isReady, key: untracked, in: env)
let answered = ValueObserverProbe<ComputedState, Bool?>
.watch(computedKeyed: \.$isReady, key: tracked, in: env)

declined.expect(value: nil)
answered.expect(value: true)

// Tracking the declined id invalidates only its entry: the derivation reruns and now
// answers, which is what proves the earlier `nil` was a real output rather than a miss.
declined.perform(TrackID(id: untracked))
declined.expect(updates: 1)
declined.expect(value: false)
answered.expect(value: true)
}
}
44 changes: 44 additions & 0 deletions Tests/Consumers/WatchTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ final class TestWatchState: StateContainer {
@Computed var boxKeyedComputed = { (env: ComputationEnvironment, key: String) -> Box in
Box(n: env.read(\TestWatchState.counter) + key.count)
}

// Optional-Output keyed computed: nothing decides a state for an untracked row, so the author
// declares `Output` Optional and answers `nil`. A Watch binds that as `Bool?`, not `Bool??`.
var trackedRows: Set<UUID> = []
var rowFlags: [UUID: Bool] = [:]

@Computed<UUID, Bool?> var rowState = { env, id in
guard env.read(\TestWatchState.trackedRows).contains(id) else { return nil }
return env.read(\TestWatchState.rowFlags, key: id) ?? false
}
}

struct UpdateValue: SyncOperation {
Expand Down Expand Up @@ -99,6 +109,15 @@ struct SetBoxDict: SyncOperation {
}
}

struct TrackRow: SyncOperation {
let id: UUID
func perform(in env: SyncOperationEnvironment) {
var tracked = env.read(\TestWatchState.trackedRows)
tracked.insert(id)
env.write(\TestWatchState.trackedRows, value: tracked)
}
}

// MARK: - SwiftUI integration fixtures (host-only)

#if canImport(AppKit) || canImport(UIKit)
Expand Down Expand Up @@ -393,6 +412,31 @@ struct WatchTests {
#expect(row7.lastValue == true)
}

/// The consumer half of the keyed-optionality verdict. A Computed always runs, so the
/// framework adds no Optional of its own: an Optional `Output` reaches the watcher as
/// `Bool?` rather than `Bool??`, and `nil` diffs like any other output.
@Test("Watch binds an Optional Computed Output as-is and diffs nil like any value")
func keyedComputed_optionalOutputBindsAndDiffs() {
let env = SharedEnvironment()
let row = UUID()
let otherRow = UUID()
let probe = ValueObserverProbe<TestWatchState, Bool?>
.watch(computedKeyed: \.$rowState, key: row, in: env)

probe.expect(value: nil)

// Tracking another row invalidates this one's entry too, but the derivation still declines
// it: an unchanged `nil` suppresses exactly as an unchanged non-Optional output would.
probe.perform(TrackRow(id: otherRow))
probe.expect(updates: 0)

probe.perform(TrackRow(id: row))
probe.expect(updates: 1)

let bound: Bool? = probe.render()
#expect(bound == false)
}

/// A suppressed keyed-computed notification must not drop the subscription.
@Test func keyedComputed_suppressionDoesNotDropSubscription() {
let env = SharedEnvironment()
Expand Down
Loading