Changelog

Releases

Pre-releaseOn GitHub →

0.4.1

Stoic 0.4.1 lets a typed schema describe a settings file people edit by hand, with nothing lost on the next write. Lodestar's config now runs on it.

Everything here is additive. 0.4.0 code builds unchanged.

Schema (design/06, "As built: files people edit")

  • Clamping. clampingToRange() on a double or integer schema with an inclusive .range brings an out-of-range number to the nearest bound and reports it as a warning ("99999 is out of range, expected a number between 200 and 4000; clamped to 4000").

  • Lossy dictionaries. Schema.lossyDictionary(of:valueDoc:) drops each bad entry on its own, with a dropped_entry warning at that entry's path, and keeps the good ones. A settings store writes the dropped entries back on every write, so a typo in one entry is never erased by an unrelated change.

  • Documentation. documented(_:) and valueDoc: describe any schema or a dictionary's values in the JSON Schema export.

  • Null sections. readingNullAsEmpty() reads a null object as all its defaults, silently, and the null is not written back.

  • Normalization. normalizing(_:retired:) is an unversioned, idempotent rewrite of the raw document, applied on every read before decoding:

    • a rename where the new key wins, move, delete and setIfAbsent;
    • an enum remap;
    • custom operations;
    • retired keys, which are skipped on read and never carried on write.

    Nodes it does not touch keep their exact positions.

  • JSON Schema export. JSONSchemaOptions adds Draft-07 output and closed objects (additionalProperties: false) whatever the unknown-key policy, plus extra root properties for a file's header keys (SettingsFileHeader.jsonSchemaProperties). Schema.json(jsonSchema:) lets a free-form field carry a fragment of its own into the export. The default options write exactly the 0.4.0 document.

  • Messages.

    • .string(.oneOf(...)) suggests the closest choices, as .enumeration does.
    • A repair no longer spells out a composite default.
    • Issue.message includes the repair on warnings too.
Pre-releaseOn GitHub →

0.4.0

Stoic 0.4.0 adds downloads, sealed storage, and settings files people edit by hand, each driven by what Lodestar needed.

New libraries

  • StoicDownloads (design/23). Resumable, verified, durable file downloads. Bodies stream with backpressure on Apple platforms. Digests (SHA-256 or git-blob SHA-1) are checked while the bytes arrive, not in a second pass. A resume carries an If-Range validator, and the retry schedule resets whenever bytes arrive. The finished file is placed with fsync, rename and a directory sync. A DownloadBundle fetches several files and swaps the whole directory in at once, for models. It can adopt a partial file it did not write. Behind the Crypto trait.

  • StoicSealed (design/24). Encryption at rest with AES-256-GCM through swift-crypto:

    • A Keyring held in a KeyCustody.
    • Sealed files, SealedObjectFile for per-object keys, and SealedJournal, whose compaction can rotate the key so deleted records are gone for good.
    • Failures are told apart: tampered, torn, unknown key, not sealed.
    • The contract states the threat model plainly.

    Behind the Crypto trait, so adopters who do not enable it fetch nothing new.

  • StoicSealedKeychain. SecretStoreCustody, which turns any SecretStore (such as the Keychain) into a keyring's custody. A locked or refusing keychain is never read as an absent key.

Settings people edit by hand (design/18)

A .handEdited settings file is never moved or overwritten when it doesn't parse. The last good value is kept, and the problem carries a line and column. An update first reads the file again under a lock, so an edit made a moment ago is not lost.

New in this release:

  • Writing the file:
    • A canonical sparse layout, with caller-supplied key order and a file header.
    • materialize(), and replaceUnusableFile(...), which copies the broken file aside first.
  • Locking: blockingUpdate(waitingUpTo:) for synchronous callers that wait for the lock.
  • Watching the file: watch(debounce:) follows rename-saves.
  • Streams: changes(), with cause and source; problems().
  • Dialect:
    • Comments can be refused.
    • A repeated key is read last-wins with a warning, never as a reason to fall back to defaults.
  • JSON: JSONChange diffs and applies documents for undo history, plus path operations on JSONValue.

Store, Outbox and HTTP

  • PosixFileSystem(newFileMode:newDirectoryMode:) creates private files with no chmod window.
  • FileSystem.watchFile watches a file for changes.
  • Journals:
    • Journal.readOnlyReplay lets a second process read a journal without repairing it.
    • Journal.remove deletes a journal with its sidecars.
  • Outbox:
    • Breaking: a delivery closure now returns a DeliveryResult (.delivered, .discard(reason:), .keep).
    • Outbox.deliver(_:using:) awaits the outcome for one entry.
    • Undecodable entries and expiry each get a policy.
  • HTTP:
    • HTTPClient.stream streams a response body.
    • HTTPPolicy.singleAttempt makes one attempt and leaves retrying to the caller.
    • keyedConflictIsInProgress controls whether a 409 on a keyed request means "in progress".
  • KeychainSecretStore(loginKeychainService:) uses the macOS login keychain, for Developer ID apps without an application identifier.

Fixes

  • StoicTesting: a use-after-free in the simulation executor. An enqueue from another thread could signal an executor its simulation had already freed. Found under AddressSanitizer, with a deterministic regression test.
  • StoicTesting: TestClock.waitForSleepers works from XCTest without importing Testing.

Breaking changes

These are listed in api-breakage-allowlist.txt:

  • The Outbox delivery closure's result.
  • AtomicFile.Options.newFileMode is now optional (nil means the file system's mode).
  • New SettingsStore.UpdateError cases.
Pre-releaseOn GitHub →

0.3.0

Stoic 0.3.0: operations, where a call site states facts and Stoic derives the resilience policy from them; a package graph that is checked, with a portable StoicFoundation and StoicHTTP; and the faults a review of 0.2.0's primitives found, closed. Pre-1.0 — the API still changes; the changes that can break code are listed last. Requires Swift 6.4 and the 27 releases of Apple's platforms; the libraries that need no Apple framework also build and pass their tests on Linux.

Operations — declare a Backend once (remote, system, local or compute, with the capacity its owner knows) and each operation on it by whether repeating it is harmless: readOnly, idempotent, keyed (repeatable because the backend deduplicates by key) or notRepeatable, .brief or .long, with a ceiling urgency. perform derives the rest: the deadline when the caller set none, the schedule and its classifier, the attempt timeout, the breaker and what it counts, a bulkhead partitioned by Urgency so capacity is kept for people, a writer lane for local backends, the retry budget, and the idempotency key. No number is written at a call site; policy(at:) is the derivation as a pure, printable function. withUrgency says who is waiting (inferred from the task's base priority when unset; .interactive is never inferred). The error is OperationError: why the call stopped, the last attempt's own failure, and an outcome of .notExecuted, .executed or .unknown, which for a keyed or non-repeatable operation never reads as cancellation. Retryable.neverReachedBackend is the proof that lets an unsafe operation be repeated; StoicFoundation claims it for the URLError and POSIXError codes that fail before a connection exists. One layer retries: a perform that gives up settles the enclosing attempt, and retry, Retrying, hedge and the outbox never repeat it. State lives in Ambient.backends. On Apple platforms a Foundation error reaches any Error as its NSError, which a protocol cast cannot see through; classification now reads URLError, POSIXError and CocoaError as the Swift values they are wherever they came from, so their table (and neverReachedBackend) applies to a real URLSession failure, not only on Linux.

Idempotency keys — every attempt of one retry gets the same attempt.idempotencyKey (hedged copies too), drawn on first read. An operation started inside another's attempt derives its key from the enclosing key, so it is the same on every outer attempt; the derivation is a frozen, versioned name-based UUID that survives a relaunch. An outbox entry's attempts run under the entry's key.

Package graph and platforms — Foundation's error table (URLError, POSIXError, CocoaError) is the new portable StoicFoundation; HTTP's semantics (HTTPRetry, HTTPStatusError) moved to StoicHTTP; StoicApple links StoicFoundation, so retry classifies the same errors as before. StoicHTTP no longer depends on StoicApple and builds on Linux over FoundationNetworking. scripts/package-graph.swift holds the layering as a table: a dependency it does not allow fails, every import must be a declared direct dependency, and every declared dependency must be imported. scripts/adoption.sh adopts every library from a fresh package with no traits and requires that nothing is fetched and everything builds; scripts/linux.sh builds and tests the portable libraries on Linux in CI.

Persistence — a write that lands but cannot be made durable says so: AtomicFile.write and replaceItem throw StoreError.Kind.durabilityUnknown after the new bytes are in place, and SettingsStore.update publishes the value the file now holds and throws UpdateError.durabilityUnknown. Journal.append(batch:) is all or nothing after a crash, including pages a torn write kept out of order; a snapshot that failed its checksum stays refused on every open until lostSnapshot: .acceptLoss; Outbox.open takes journalOptions (the cross-process lock, accepting a lost snapshot) and exposes the journal's open report. New directories are created durably, and the simulated disk models failed syncs, lost directories and torn pages. LaunchGuard is serialised, never the reason an app cannot start, and markStable(after:) counts time on the liveness clock. Adopting SettingsStore over plain JSON keeps the settings (the old bytes go to <path>.legacy); a repaired value stays in the file until the app changes it; observers are told after the update lock is released. AtomicFile.Options.newFileMode is documented as exact: set with fchmod, so the umask does not narrow it.

HTTP — the client follows redirects itself, the same on every platform: an https request never follows to http, once a redirect leaves the request's origin the client's headers, credentials and idempotency key stay behind, POST follows 301, 302 and 303 as a GET, and HTTPPolicy.maxRedirects (10) bounds the chain; a refusal is HTTPError.redirectRefused. URLSessionTransport answers on Linux, through the session's own delegate. A call inside a perform attempt is one attempt of it, through no breaker or bulkhead of its own; a keyed request answered 409 or 425 is "in progress" and retried after at least a second. A rate limit's queue always has a bound, a host with a request in flight is never forgotten, a coalesced flight compares its overrides by value, and a decode that succeeded with warnings says so (http.decoded_with_warnings).

Schemas — no entry point hands over a value without its warnings; wire models read keys exactly (KeySpellings, ASCII folding only); constraints hold for the value the caller receives, not the digits sent; Refined(clamping:) snaps to steps and exists only where it cannot fail (ClampableRefinement); the Codable bridge walks iteratively under the parse limits; numbers are ranged by their exponent and ordered exactly at any precision; the JSON Schema export says an integer refuses 5.0; the version key is read strictly. Did-you-mean suggestions and issue positions no longer cost time in proportion to the document squared (8,000 near-miss keys: 160 s to 0.2 s in debug). @Schema refuses lazy and wrapped properties; a constraint that admits nothing, and a migration that moves a value into itself, trap where they are written.

Ambient context — withAmbient has a synchronous form, for an entry point that runs a run loop: withAmbient({ $0.instrumentation = … }) { NSApplication.shared.run() } gives every main-thread callback, and the tasks they start, the context; detached tasks and other threads do not inherit it.

State machines and services — a visit's work stops before the next visit's begins (shutdownTimeout, abandoned after it), shutdown() ends a machine, the machine's own send drops an ended visit's events, registering the same work twice is reported and ignored, and send is under a microsecond with no allocations. StateGraph tells events apart by value and says whether it finished (isComplete). Supervisor.events() gives every subscriber every event, a backoff bounded by time ends and escalates, and a hung child is cancelled with childHung. ServiceGraph abandons a start that ignores cancellation after startGrace, and reports failed starts and every stop.

Fixes — a breaker times a call from when it left the local queue, records a call a deadline cut short as a slow failure, and a probe cut off that way re-opens it; Pipeline checks its stage order when built; Retrying reports cancellation, the deadline and an empty budget as rejections; one rule for an open breaker under retry; a retry inside a hedge collapses to one attempt, and a hedge that cannot finish before the deadline is skipped; every classifier sees through PolicyError, Report and ConcurrentFailure the same way; the schedule's cap holds on a hot device, upTo(elapsed:) stops rather than take a delay past its limit, and decorrelated backs off; mapConcurrent throws cancellation, never a shorter array; race does not report a cancelled caller as every racer failing; TaskSlot holds its owner weakly; Debouncer and Throttler do not replace a call that is due because its timer is late; AsyncSemaphore's FIFO counts a waiter on its way to the queue, and tasks Stoic starts do not inherit held permits; Broadcast.publish cut short by finish() throws closed; ExpiringCache stores nothing from an abandoned load and stops refreshing after its scope; a scope's cleanup runs under its own deadline, a nested deadline that cannot narrow is a no-op, and a scope cancelled from outside passes on its enclosing cause; a stream whose consumer stops listening can no longer deadlock the machine or monitor feeding it.

Testing — the public API is compared with the last release on every change, an escape budget makes a new stoic:allow a reviewed change, Address Sanitizer runs every suite, hot paths are held to their recorded allocations (the median call, which a scheduler's bursts do not move), and the tour is lint-clean, kept so by check.sh. StoicLint adds nine rules (preconcurrency, swallowed-cancellation, swallowed-error, bare-task-sleep, key-inside-retry, hand-rolled-retry, keep-alive-loop, unbounded-task-group, unsafe-continuation).

Can break code — HTTPRetry and HTTPStatusError moved from StoicApple to StoicHTTP (import it), and URLError, POSIXError and CocoaError's retryDecision is StoicFoundation's (import it to call it by name; retry still classifies them with StoicApple alone). URLSessionTransport.init(session:) is gone (init(configuration:) carries a session's settings; the transport owns its delegate). mapConcurrent throws PolicyError<Failure> (.failed is the first failure, .rejected a cancelled caller) and mapConcurrentResults throws Rejection. TaskSlot.run and runExclusively are run(for: owner), must be called on an actor, and deliver receives the owner: { @MainActor model, result in … }. Value-only decoding takes a warnings: handler (Schema.decode(_:options:warnings:), decode(from:options:warnings:), Decoded.get(warnings:), decodeSchema and decodeSchemaIfPresent; spell dropping them { _ in }). Schema.object(declare:) reads keys exactly by default (spellings: .forgiving restores the old reading); the configuration form is unchanged. Refined(clamping:) is available only for a ClampableRefinement. Mutation.Kind.notFinite is gone and integralFraction is new. HTTPRateLimit.queueLimit is an Int (no nil). HTTPError.status carries keyed: (patterns and constructions take five values) and HTTPError.redirectRefused is a new case; HTTPTransport conformers must not follow redirects. StateGraph.explore needs Event: Hashable, and truncated is isComplete (the opposite sense). Supervisor.events is events(). Exhaustive switches over StoreError.Kind, SettingsStore.UpdateError and SimulatedFileSystem.Operation need durabilityUnknown and createDirectory. Parameters added with defaults (Ambient.init backends:, HTTPPolicy.init maxRedirects:, Journal.Options.init lostSnapshot:, Outbox.open journalOptions:, ServiceGraph.run startGrace:, whileIn shutdownTimeout:, mapConcurrent label:, JSONValue.init(reading:) limits:) need no edit unless the initializer or function is used as a value. The API check does not see these: LaunchGuard.beginLaunch() no longer throws (drop the try; a record that cannot be written is launch.record_failed); AtomicFile.write and replaceItem can throw .durabilityUnknown when the change is made, so treat it as made and do not retry the write; a multi-record Journal batch is unreadable by 0.2.0 (a single record is unchanged), and a lost snapshot refuses every open until lostSnapshot: .acceptLoss; TestClock.waitForSleepers that times out records its issue and then ends every sleep on the clock with CancellationError; withTestAmbient installs fresh backend state and records a test issue for operation.key_unread, operation.key_ambiguous and operation.backend_conflict (withKnownIssue for a test that provokes one); a Pipeline in the wrong stage order, a constraint that admits nothing, @Schema over a lazy or wrapped property, and a move into itself fail where they are written; Retrying throws .rejected(.cancelled), .rejected(.deadlineExceeded) or .rejected(.budgetExhausted) where it threw the last failure, and a breaker counts a call cut short by a deadline as a failure; each of StoicLint's new rules is a build error where it matches.

Pre-releaseOn GitHub →

0.2.0

Stoic 0.2.0: the gaps an audit and a first real adopter (Lodestar, a macOS app) found, closed. Pre-1.0 — the API still changes; the changes that can break code are listed last. Requires Swift 6.4 and the 27 releases of Apple's platforms.

New primitives — Debouncer and Throttler (a dropped call is a defined rejection, never a hang); ExpiringCache with TTL, stale-while-revalidate, LRU and single-flighted loads; Broadcast with a bounded buffer per subscriber; tracing spans (withSpan, task-local Span.current, adapters to swift-log and swift-metrics); abandoningAsyncAfter for async work that never checks cancellation.

Persistence — FileLock (cross-process, cancellation and deadline aware) and an opt-in crossProcessLock for Journal and SettingsStore; AtomicFile.replaceItem for a crash-safe swap of a file or directory; the journal resyncs past mid-file damage by checksum and reports it; settings keep fields their schema does not declare and are created 0600; atomic writes keep permissions and write through symlinks; LaunchGuard no longer counts a backgrounded launch, a restart or a new build as a crash.

Schemas for API models — required fields in @Schema, built-in Date/URL/UUID/Data/Decimal, @UnknownCase for enums and tagged unions a server may extend, @Lossy arrays, @Codable for an existing Codable leaf.

HTTP — coalescing keyed on every header; per-call HTTPOverrides; one replay after a 401 through a single-flighted reauthenticate; retry decided on a response; a per-host rate limit; responses up to maxResponseBytes decode without parser limits in the way.

Apple — settled reachability (PathMonitor), BGTask work bounded by the system's expiration (BackgroundJob), Keychain secrets (SecretStore).

Fixes — supervisor heartbeats no longer report a hang after sleep; Pipeline retries timed-out attempts; TaskScope forgets finished forks and bounds forks that ignore cancellation (forkTimeout); SingleFlight escalates priority; TaskSlot clears a stale deadline; abandonment slots are reclaimed; graceful termination's deadline holds against a blocking step; cancellation through a policy is cancellation, not failure, to scopes and services.

Testing — failure-mode coverage gate (one documented row left), Thread Sanitizer in CI, simulations report escaped work, compile-fail tests.

Can break code — HTTPPolicy.varyHeaders is gone (ignoreHeadersForCoalescing replaces it); GracefulTermination's shutdown closure runs off the main actor (hop with MainActor.run); Report.description redacts the root error (debugDescription keeps it); a SchemaSuite that skipped every case now fails; LaunchGuard's state file is v2 (v1 is still read).

Pre-releaseOn GitHub →

0.1.0

The first public release of Stoic: robustness primitives for Swift apps. Pre-1.0 — the API will change. Requires Swift 6.4 and the 27 releases of Apple's platforms.

Core (Stoic) — deadlines and timeouts that cancel with a cause, abandoningAfter for calls that ignore cancellation; schedules and budgeted retry; TaskSlot, race, mapConcurrent, semaphores, SingleFlight, Channel; scopes, resources and sagas with bounded, shielded cleanup and quarantined releases; StateMachine and StateGraph; ServiceGraph; Erlang-style Supervisor; circuit breaker, rate limiter, bulkhead, hedging and pipelines; Report and Defect; an event catalog; system conditions; diagnostics and a task ledger.

Validation (StoicJSON, StoicSchema, StoicMacros) — a strict JSON parser with positions; one schema per type for decode, encode, every issue with its line, JSON Schema export, unions, migrations, generators and a self-testing suite; @Schema behind the Macros trait.

Persistence (StoicStore, StoicSettings) — atomic files done right, a crash-consistent journal, an outbox, a launch guard, a flight recorder the next launch can read, and settings that a crash, a bad value, an old format or a newer app version cannot ruin — all checked at every crash point of a simulated disk.

Network (StoicHTTP) — per-host policies, only idempotent requests repeated, Retry-After within the deadline, bounded responses, schema decoding, coalesced GETs, and a scripted transport for tests.

Testing (StoicTesting) — virtual clocks, seeds, fault injection, golden traces, and deterministic simulation: a seed picks every interleaving, fault timing and schedule, and a failing seed replays exactly.

Enforcement and integration — the StoicLint build plugin (Lint trait); swift-log and swift-metrics adapters; AppKit and UIKit lifecycle bridges.