Home / Docs / Specification / 27. Tasks and time
27.5 within
-
Grammar (ADR 0117 rule 5). In edition
0.4, a statement's expression MAY take a deadline after itswithclause, andattemptMAY take one:ebnfhandled = line_expr [ with_clause ] [ "within" add_expr ] NEWLINE [ INDENT handling { handling } DEDENT ] ; attempt_expr = "attempt" postfix [ "within" add_expr ] ;- The word.
withinis the word of a deadline right afterfor ever(spec/26 §7) and right after a token that ends an expression: a name, a capability reference, a literal,)or]. Anywhere else it stays reserved (U0103), so it is never a name. Before edition0.4it is a name, and a name after an expression is U0101. - After
attempt. Inlet r = attempt f(x) within d, theattempttakes the deadline, so itsResultholds the time-out. Awithclause then follows the deadline:attempt f(x) within d with @h = @g. Ahandledwhose expression is anattemptwith its ownwithintakes no second one (U0101).
unaimport std.time (millisecond, second) let quote = fetch_quote() within 2 * second if error use cached_quote - The word.
-
The deadline.
dis anInt of Millisecond, withMillisecondofstd.time: a deadline in seconds, a unitlessIntor another unit is U2028, and a type that is not an integer is U2001. It MUST be at least 1, arefinementobligation atd(spec/12 §3):within 0 * millisecondis U5001. It is evaluated first, before thewithclause and the expression. -
The failure kinds.
std.timedeclarespub kind Timed[E] = TimedOut | Failed(error: E)andpub kind Deadline = | Expired, a sum of one variant (spec/02 §2). Whenecan fail withE,e within dfails withTimed[E]:TimedOutwhen the deadline passed,Failed(error: x)whenefailed withxin time. Whenecannot fail, it fails withDeadline.Expired.attempt e within dgivesResult[T, Timed[E]], orResult[T, Deadline]. A variant resolves by the kind its context gives (spec/10 §11 rule 3). -
Handling (spec/06 §3).
e within dcan always fail, so without anif errorclause, and outsideattempt, it is U3007.if error use vandif error fail V(...)take any failure.if error passis legal when the function's error kind declares a variantTimedOutwithout fields, andeeither cannot fail or fails with that same kind:TimedOutpasses as the function'sTimedOut, andFailed(error: x)asx. Otherwise it is U3008. Nofailsclause takes type arguments.unapub kind RouteError = NoPath | TimedOut plan(graph: Graph, start: Node, goal: Node) -> Route fails RouteError = let route = shortest(graph, start: start, goal: goal) within 50 * millisecond if error pass -- TimedOut passes as RouteError.TimedOut route -
Dynamics.
- The deadline is
dafter the run's clock reads at thewithin, real or virtual (spec/26 §8). It belongs to thiswithin. - In nanoseconds (ADR 0116 amendment, P13). On the real clock the deadline is armed on a reading of the monotonic clock in nanoseconds, and every reading compared with it is one too:
e within dhas exactlydfrom the moment it was armed, to the resolution of the system's clock and sleep. A reading in whole milliseconds would give it betweend - 1anddmilliseconds, by the phase within a millisecond that earlier code left, possibly code onsecretdata. The timer thread fires each deadline at its own nanosecond: its timing wheel counts nanoseconds, with slots of one nanosecond at its finest level, and the thread sleeps until the wheel's next expiration, never to the end of a millisecond. Virtual time moves in whole milliseconds, andClock.nowreads milliseconds, as before. - Past the deadline, every interruptible operation waiting inside
e, and every one that starts later, fails with its time-out failure,HttpError.TimedOutforHttp(§6);eis canceled at its next check point (spec/11 §7): each call, operation and loop iteration, as a canceled task is (spec/19 §6 rule 4). An operation in progress completes first, its handler's code included. Nothing inside it runs further: no handling clause, no innerwithin. Tasks started insidee, bytogetherortogether for, are canceled with it, andeends once they have stopped. Afor everinsideeends as after a failure: itson stopruns on the state from before the loop, shielded from the deadline, and the cancellation then goes on (ADR 0116 rule 15). The cancellation leaves every frame ofeas a failure does, releasing the values each one holds, so a program whose deadlines keep passing holds no more memory than one whose expressions fail. - The outcome.
e within dsucceeds only whenereturns before its deadline, checked once more whenereturns: an expression that returns at its deadline, or later, has missed it. Otherwise the result isTimedOutorExpired, even whenereturned a value or a failure, which is dropped. In every outcome but success,e'seditarguments keep their values from before the statement, as for any failure (spec/17 §7 rule 1), and effects already performed stay (rule 2). - Nesting. An inner
withinwhose own deadline has not passed never reports a time-out because an outer one passed: the outer cancellation goes through it, and only the outermostwithinwhose deadline passed reports its time-out. - Virtual time. Under virtual time only the run's own waits move the clock (spec/26 §8), so a deadline passes inside
eonly through such a wait, asstd.testing.elapsein a test's handler.
- The deadline is
-
Interruption (ADR 0117 rule 4). In this edition the interruptible operations are those of
Http. A request waits no longer than the earliest deadline that covers it, of awithinor of afor ever withiniteration, and fails withHttpError.TimedOutwhen it passes: its exchange ends at that deadline, at its next I/O step, on its helper or, parked on the reactor, on its task (§2 rules 3 and 4). What a request sent before its deadline passed stays sent, on either path, so an interrupted request is an effect in doubt.- Never before the deadline. An interruptible operation that a covering deadline ends, with its time-out failure (
RateLimitedforacquireofstd.limit, §10), returns only once the run's clock has reached that deadline, in both engines, whatever unit a wait inside it counts in: a wait at a limit that reads the deadline in whole milliseconds reads the first millisecond at or after it, never one before. So when awithin's deadline cut an operation insidee, thewithinalways finds its deadline passed whenereturns, and times out with itstimeoutevent (rule 7): a cut operation'sTimedOutis never the failure of awithinthat succeeded in time.
- Never before the deadline. An interruptible operation that a covering deadline ends, with its time-out failure (
-
Trace. A
withinthat times out appends one event{"seq": n, "outcome": {"kind": "timeout"}}, with thetaskof its task and no operation, after the outcomes of the operations it interrupted, whose own events show their time-out failures (spec/11 §5), unless quiet code that is notquiet timingperformed them (below). An operation in progress completes (spec/19 §6 rule 4): the code of a handler serving an operation insideeis not cut by a deadline that was running when the operation began, so its event keeps its outcome, andeis canceled at the next check point after it. The outcome{"kind": "interrupted"}of ADR 0117 rule 10 belongs to an interruptible operation whose task is canceled while it waits, whichfirst ofbrings (ADR 0117 amendment of 2026-10-19). Code inside aquietexpression appends notimeoutand nocancelledevent of its own, nor, unless the mark isquiet timing(spec/09 §2), the events of the operations it performs in a run's trace, and takes noseqfor them (S-42, spec/26 §6 rule 4).- Canceled tasks. When the cut stops a block of
togetherortogether for, or afirst of(§6), insidee, every task of that block that has not returned ends with its event{"seq": n, "task": "<path>", "outcome": {"kind": "cancelled"}}(spec/19 §7 rule 3), whether it had started or the cut kept it from starting, in the order of the tasks' paths, after the events the block's tasks wrote, and before thewithin'stimeoutevent. The start of each task is a check point for this rule, in both engines. So the events do not depend on the number of workers, nor on how many tasks had started: in both engines, a task that had not returned when the deadline passed gets exactly onecancelledevent. - Timing information (ADR 0116 rule 21, IF5). Whether a
withintimed out, so itstimeoutevent and thecancelledevents of its tasks, and which tasks had returned when it did, depend on timing: onτ(e), which may be abovepublic. The trace records them as it records every outcome (spec/11 §5), under the accepted trace design of ADR 0116, as it records thetimeoutevents offor ever within: an operator who reads a trace of awithinwhoseτissecretreads a bit ofsecrettiming. The report'stiminglist names every suchwithin(rule 9). Under virtual time a deadline passes insideeonly through the run's own waits, a wait for a refill at a limit among them (§10), and both engines read the clock at every check point, so they cuteat the same one: these events, and the trace, are the same in every run and in both engines (§8 rule 3).
- Canceled tasks. When the cut stops a block of
-
Information flow (ADR 0117 IF2). Let
t = τ(e), the timing label of spec/26 §7 rule 5, computed by the same rule, withℓ(d)included and withτ_conc(e)as §11 computes it.- The failure is labeled
t, joined with the label ofe's own failure:if error use vruns under it and its value is raised by it (spec/07 §7 rule 3), andif error passandif error failare U4002 when it is abovepublic. - The places
eupdates, itseditarguments and the target of an assignment, MUST be labeled at leastt(U4001 at the place, with thewithinas a related location). - The timing floor. Every operation inside
e, and every call insideewith effects, is checked as if it ran underpc ⊔ t: the sinks of spec/07 §7 rule 4 (U4003), and the effect bound of each call (U4002). Failures insideekeep the ordinary program counter. - Residue.
tincludesL_res(spec/26 §7 rule 5, item 6), whether or notemakes a request: in a program whose started tasks or races make requests, everywithinis at leastinternal. A message about a label thatL_resraised names the construct whose requests can be left running. - Interruptible operations. An
Httpoperation thatecan reach declares its failureinternal(spec/24 §5), sotaboveinternalis U4001 at thewithin(ADR 0116 IF8). A time-out overHttpis therefore at leastinternal: it can be recovered from withuse,attemptorfailunder aninternalhandler, never passed on to a public failure. - Computing
t.tdepends on the whole package's call graph, so the checker computes it from a probe of its own checks, repeated until no label rises, and confirms after checking that no label it used was too low (U8001 otherwise).
- The failure is labeled
-
Report (ADR 0117 rule 13). The report's
information.timinglist (spec/13 §6) holds eachwithinwhosetis abovepublic, with its function andt, beside eachfor ever within. -
Core (spec/09).
e within diswithin(d, C_t, [C_w]) e, withdan atom bound before it. -
Costs. A
withinarms a timer in O(1) and ends it in O(1), in a timing wheel of 11 levels of 64 slots over nanoseconds of the monotonic clock, the finest slot one nanosecond wide, which covers about 584 years (ADR 0117 Costs; ADR 0116 amendment, P13). A timer fires in O(1) amortized: it moves down the levels at most 10 times, each move O(1), inside passes the timer thread makes at the start of a slot that holds it. Removal is eager: a canceled timer leaves the wheel at once, so after any history of armed and canceled timers the wheel holds only its live timers. Under the real clock, one thread per run, started beforemain(§1 rule 4), fires the timers, with one mutex that eachwithintakes to arm and to cancel its timer. The thread wakes only at the next expiration, which is always a live timer's: its exact deadline, or the start of a slot that holds it, where it is cascaded, at most 10 times per timer and shared by the timers of that slot; when a timer earlier than that moment is armed; and when the timer it waits for is canceled, to wait for the next one instead. Arming moves the wheel's time to the moment of arming, so the moments a timer wakes the thread follow from its own arming moment and deadline, never from earlier code. Canceled timers cause no later wake; a task's check points see a passed deadline as a cancellation, so the check point's fast path is that of a task (ADR 0102). In the interpreter, each check point inside awithinreads the clock once.