Skip to content

Stoic 0.3.0

Pre-release
Pre-release

Choose a tag to compare

@rvaccone rvaccone released this 17 Oct 09:53
· 185 commits to main since this release
Immutable release. Only release title and notes can be modified.

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.