# \[Concurrency\]\[Pitch\] Task Local Values

**URL:** <https://forums.swift.org/t/concurrency-pitch-task-local-values/42829>\
**Category:** Pitches\
**Tags:** concurrency\
**Created:** [December 15, 2020, 3:58am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829 "2020-12-15T03:58:06Z")\
**Posts on this page:** 20\
**Page:** 2

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [December 21, 2020, 3:57am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/21 "2020-12-21T03:57:08Z")

</div>

Hi David, thanks for the references - the concepts are similar indeed.

The semantics are pretty much the same, yes; scopes inherit their parent's values, and cannot mutate them. And we can only bind values by introducing scopes.

I am also working on not requiring creating new child tasks for introducing new scopes, so the mechanism can be very light-weight. Semantics wise nothing changes though, a given `withLocal` scope binds values, and destroys these bindings once it exits (same as your linked Scheme environment mechanism).

* * *

> [@gnuoyd](#):
>
> It seems like an environment of this kind can subsume the functions  
> of your task-local values without relying on tasks.

I would actually say it's somewhat the inverse to actually be able to implement this.

> [@gnuoyd](#):
>
> Are environments of this kind very different from what you propose?

I think what you're after can absolutely be expressed with task local values, and in fact we have similar use cases for them.

For example in [Swift System](https://github.com/apple/swift-system) the team had to ad-hoc invent contextual mocking (and tracing), which will break as this code would be used in async settings because the [`withMockingEnabled`](https://github.com/apple/swift-system/pull/8/files#diff-9e369bd109521aa185f8c63d962d415e58f03f6d8e80c3abd5e544511937452dR115-R128) relies on thread local values – this will stop working with `async` as part of the language. So today's:

```swift
withMockingEnabled { driver in 
   // synchronous IO calls
  _ = try fd.write(writeBuf, retryOnInterrupt: retryOnInterrupt)
}

```

works okey because all calls are synchronous, however in the future these APIs may want to become `async`:

```swift
withMockingEnabled { driver in 
   // asynchronous IO calls
  _ = await try fd.write(writeBuf, retryOnInterrupt: retryOnInterrupt)
  _ = await try fd.write(writeBuf, retryOnInterrupt: retryOnInterrupt)
}

```

today, they'd be left with no way to keep the mocking working; The mocking is just an example, it could absolutely be your `roundingMode` example value.

The point is, that we need to persist it "throughout the _scope_" that we defined there. But... there is no real place to put such context values on, except either the task (this proposal) or deeply changing stack and variable semantics (I guess).

* * *

I think the core of your question might be... can we use this in _synchronous_ functions though?

And the answer is we'll be able to do this once async functions get their ABI locked in (which will happen some time in 2021), then this [Access from non-async functions](https://github.com/ktoso/swift-evolution/blob/wip-tasklocals/proposals/nnnn-task-locals.md#access-from-non-async-functions) section will be able to complete and allow us access to these values even in synchronous functions. The reason this needs ABI of async functions to be locked in, is because they will change to set the task in a thread-local and manage it properly throughout suspension points, we can then rely on reading it to get access to the task and implement task local values even in sync functions -- this will allow use cases as you pasted, which don't really use async by itself, but technically _are_ running in _some_ task somewhere anyway 🙂

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [December 28, 2020, 9:43pm UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/22 "2020-12-28T21:43:51Z")

</div>

After contemplating a little more, I think we should:

- Have `TaskLocal` subscript takes `KeyPath<TaskLocalValues, Value>` instead of `KeyPath<TaskLocalValue, Key>`,
- Use `dynamicMemberLookup` for the read site instead of function call,
- Have `with` returns `TaskLocal` instead for chaining `with`, and add `TaskLocal.callAsFunction` to be used on actual binding.

i.e.

> **(collapsed)**
>
> ```swift
> protocol TaskLocalKey {
> associatedtype Value
> static var defaultValue: Value { get }
> }
> 
> struct TaskLocalValues {
> subscript<Key>(key: Key.Type) -> Key.Value where Key: TaskLocalKey {
> get { ... }
> set { ... }
> }
> }
> 
> @dynamicMemberLookup
> enum TaskLocal {
> subscript<Value>(dynamicMember: KeyPath<TaskLocalValues, Value>) -> Value {
> ...
> }
> 
> func with<Value>(_ keyPath: WritableKeyPath<TaskLocalValues, Value>, boundTo value: Value) -> TaskLocal {
> ...
> }
> 
> func callAsFunction(_ scope: () async -> ()) {
> ...
> }
> }
> 
> ```

with the three sites

```swift
// Declare
extension TaskLocalValues {
  enum Key: TaskLocalKey {
    static var defaultValue: Int { 0 }
  }

  var record: Int {
    get { self[Key.self] }
    set { self[Key.self] = newValue }
  }
}

// Get
let local = TaskLocal.record

// Bind
TaskLocal.with(\.record, boundTo: 1) {
  ...
}

```

This way, the read and write syntaxes compose much nicer with chaining:

```swift
// Only retrieve `some.component`
let local = TaskLocal.record.some.component

// Only bind `some.component`, leaving other parts intact
TaskLocal, then bind `other`
  .with(local: \.record.some.component, boundTo: ...)
  .with(local: \.other, boundTo: ...) {
  ...
}

```

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [December 29, 2020, 2:07am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/23 "2020-12-29T02:07:04Z")

</div>

What you are suggesting is not possible to implement.

The implementation needs access to a Task, which is only possible inside async functions today. This is not just syntax but ABI related which is discussed in the [https://github.com/ktoso/swift-evolution/blob/wip-tasklocals/proposals/nnnn-task-locals.md#access-from-non-async-functions](https://github.com/ktoso/swift-evolution/blob/wip-tasklocals/proposals/nnnn-task-locals.md#access-from-non-async-functions)

Re pushing about async getters... it really isn’t what we strongly care about. We care about access to Tasks from sync functions using an unsafe api. This will be provided but not “now” — it depends on ABI changes of async functions, as explained in the linked section.

This pitch plays into Task ABI and it is important to discuss those aspects as the Task apis go through evolution soon.

// typo fix: now now -\> not now

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [December 29, 2020, 2:15am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/24 "2020-12-29T02:15:12Z")

</div>

> [@ktoso](#):
>
> The implementation needs access to a Task, which is only possible inside async functions today.

🤔 Totally forget about this... again...

> [@ktoso](#):
>
> This will be provided but now now — it depends on ABI changes of async functions, as explained in the linked section.

Can we have a main non-sync `Task` instead of optional `unsafeCurrentTask`, or is it that a `Task` needs to be allocated somewhere inside `runDetach`?

---

<div class="post-metadata">

**Author:** ![hishnash](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/hishnash/32/9519_2.png) [@hishnash](https://forums.swift.org/u/hishnash)\
**Post date:** [January 5, 2021, 12:05am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/26 "2021-01-05T00:05:44Z")

</div>

A little orthogonal to the proposal but maybe related? As part of this implementation it could be nice if the method that swift uses for saving (and retrieving) values based on type is something that is exposed to other devs who want to build apis with a similar interface rather than being something that is exclusive to the c/c++ implementation of Tasks.

From SwiftUI we already have a load of examples of this style of api being used so I see other devs in the community wishing to build APIs that provide value storage in a similar way (I have been developing a package [KeyWindow](https://github.com/LostMoa/KeyWindow) that currently keys using `String(reflecting: Key.self)` that I am sure is not the best way to do it...), having a consistent method for doing this, that does not require adding c/c++ header code each and every new api, would bring consistency to developer's implementations.

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [January 5, 2021, 1:57am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/27 "2021-01-05T01:57:00Z")

</div>

Thanks for chiming in!

> [@hishnash](#):
>
> As part of this implementation it could be nice if the method that swift uses for saving (and retrieving) values based on type is something that is exposed to other devs who want to build apis with a similar interface rather than being something that is exclusive to the c/c++ implementation of Tasks.

There really isn't anything magic about it -- it just is the object identity of the type, which you can do in Swift today already: `ObjectIdentifier(Clazz.self)` and we've done in open source packages already as well: [https://github.com/apple/swift-distributed-tracing-baggage-core/blob/main/Sources/CoreBaggage/Baggage.swift](https://github.com/apple/swift-distributed-tracing-baggage-core/blob/main/Sources/CoreBaggage/Baggage.swift)

We've seen various projects apply this pattern, inside and outside Apple, and indeed it is very useful but really seems like it's "just a pattern" and we would not want to complicate the proposal by introducing additional protocols or types for the sake of it here IMHO.

* * *

edit: I just remembered that @slashmo documented the pattern [Type-safe dictionaries | Universal Swift](https://www.universalswift.blog/articles/type-safe-dictionaries/) if you'd like to read up more on it. It's basically the same how all such dictionary style APIs work like.

---

<div class="post-metadata">

**Author:** ![xAlien95](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/xalien95/32/12558_2.png) [@xAlien95](https://forums.swift.org/u/xAlien95)\
**Post date:** [January 5, 2021, 4:06am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/28 "2021-01-05T04:06:38Z")

</div>

_Disclaimer: I am unfamiliar with SwiftUI's Environment, please let me know if I'm proposing something unimplementable._

At first glance the addition of new local variables looks quite verbose: we need to create a type, make it conform to a protocol and extend `TaskLocalValues` with a computed property. We only need three things: the variable name/path, its type and a default value. Wouldn't it be possible to have something a little more straightforward?

```swift
enum Task {
  struct Local {}
  
  static func withLocal<Value, BodyResult>(
    _ path: KeyPath<Local, Value>,
    boundTo value: Value,
    body: @escaping () async -> BodyResult
  ) async -> BodyResult { ... }
  
  static func local<Value>(
    _ path: KeyPath<Local, Value>
  ) async -> Value { ... }
}

```

In order to add a new task-local variable, we would now only need to extend `Task.Local` with a property and its default value:

```swift
extension Task.Local {
  var foo: String { "Swift" }
}

```

**Write side:** same as proposed.  
**Read side:** same as proposed.  
**Declaration:** reduced to the definition of a single computed property returning the default value instead of both a computed property and a type. (It also removes the need of having `TaskLocalValues ` and the protocol `TaskLocalKey`)

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [January 6, 2021, 1:25pm UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/29 "2021-01-06T13:25:53Z")

</div>

Thanks for the idea Stefano. I will admit I’m mostly trying to stay consistent with existing patterns which are somewhat solid, and that reducing boilerplate of definitions isn’t really a goal in my mind — those values should be used _very carefully_ and if it’s a blocker for someone to write a key type I’d be worried if they’re seriously considering the implications of using those values 🤔

Having that said, I think your proposed API shape could work. Sadly my work in progress branch is in trouble after rebasing after some xmasish changes that seem to have landed so I was not able to confirm or benchmark it.

It feels however that we would need to _actually use_ the keypaths to get the default value which I’m worried could be slow — while accessing default values should be as fast as possible (and the previous impl has it rather easy, invoke a static function)... I don’t have benchmarks to prove or disprove this yet due to the branch trouble I mentioned.

I’ll keep this in mind though. I’m trying to also get a feel for what the core team would want here. To be honest the surface API is the least critical piece here, and the semantics and storage implementation and capabilities is something I hope to get ACK on from a few teams and the community as well.

Thanks for the continious API ideas though, it definitely is useful.

---

<div class="post-metadata">

**Author:** ![filip-sakel](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/filip-sakel/32/8697_2.png) [@filip-sakel](https://forums.swift.org/u/filip-sakel)\
**Post date:** [January 7, 2021, 2:29pm UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/30 "2021-01-07T14:29:36Z")

</div>

Overall I like this proposal; however I have some questions about the API:

1. In the current proposal text, there is the `TaskLocalValues` namespace. Is there a reason why it is not `Task.LocalValues`? I think it would fit in better with the rest of the `Task` API.

2. Has the direction of having `TaskLocalKey` be replaced by a `_TaskLocalKey` protocol and a type alias `Task.LocalValues.Key` been explored?. Since the protocol will be underscore-prefixed, users outside the standard library will rarely interact with it, and declaring a new key will become a little simpler:

```swift
extension Task.LocalValues {
  struct RequestInformationKey : Key {
    static var defaultValue: RequestInformation? { .none }
  }

  var session: RequestInformationKey { RequestInformationKey() }
}

```

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [January 7, 2021, 2:31pm UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/31 "2021-01-07T14:31:08Z")

</div>

> [@filip-sakel](#):
>
> In the current proposal text, there is the `TaskLocalValues` namespace. Is there a reason why it is not `Task.LocalValues` ? I think it would fit in better with the rest of the `Task` API.

No strong preference, was just "to look similar to swift ui", I'm a fan of "consistency is king 👑". But you may be right, with Task we do a lot of nesting already in other proposals after all. If we're happy with the namespaces (awaiting core team feedback on the general style), I'd be happy to do `Task.LocalValues` as the namespace -- good idea 👍

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [January 7, 2021, 2:32pm UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/32 "2021-01-07T14:32:59Z")

</div>

> [@filip-sakel](#):
>
> ```swift
> extension Task.LocalValues {
> struct RequestInformationKey : Key {
> 
> ```

I'd be open to that, not sure what the core team and style guide would say about this style of nesting. It may be harder to know what `Key` is without an IDE, but honestly that's a minor concern -- those are always defined in a small extension like you propose.

Yeah could be fine, pending on what style of key definitions the core team will be happy with.

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [January 7, 2021, 2:39pm UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/33 "2021-01-07T14:39:58Z")

</div>

Is it possible to detect if the task-local storage is accessed in a non-async function at runtime?

If it is, maybe we can have `read` returns default value on non-async context, and have only bind function be `async`.

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [January 7, 2021, 2:51pm UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/34 "2021-01-07T14:51:42Z")

</div>

> [@Lantua](#):
>
> Is it possible to detect if the task-local storage is accessed in a non-async function at runtime?
> 
> If it is, maybe we can have `read` returns default value on non-async context

I'm sorry but I don't see what the gain of that would be?

Please refer to [https://github.com/ktoso/swift-evolution/blob/wip-tasklocals/proposals/nnnn-task-locals.md#access-from-non-async-functions](https://github.com/ktoso/swift-evolution/blob/wip-tasklocals/proposals/nnnn-task-locals.md#access-from-non-async-functions) which outlines future direction how accessing those values will be implemented once we can get to a task from a non-async function. We _need_ the actual values, not just returning the default.

---

<div class="post-metadata">

**Author:** ![Lantua](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lantua/32/8868_2.png) [@Lantua](https://forums.swift.org/u/Lantua)\
**Post date:** [January 7, 2021, 3:27pm UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/35 "2021-01-07T15:27:00Z")

</div>

> [@ktoso](#):
>
> I'm sorry but I don't see what the gain of that would be?

Sorry, I was exploring what can be done on the non-async side since I don't exactly like `UnsafeCurrentTask`. Ideally, I'd like it if we can combine Scheme's environment (on the non-async side) with the task-local value (on the async side). Especially that, as is, task-local values don't work on non-task contexts at all.

It doesn't help that I don't quite understand the mechanism behind task-local storage. So I don't even know if we can combine the two. As far as my investigation goes, things pivot around `Builtin.getCurrentAsyncTask()`.

---

<div class="post-metadata">

**Author:** ![Chris\_Lattner3](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/chris_lattner3/32/348_2.png) [@Chris\_Lattner3](https://forums.swift.org/u/Chris_Lattner3)\
**Post date:** [January 25, 2021, 6:04am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/36 "2021-01-25T06:04:45Z")

</div>

> [@ktoso](#):
>
> Hello everyone,
> 
> We'd like to share with you this pitch introducing _Task Local Values_ to the [Swift's concurrency model](https://forums.swift.org/t/swift-concurrency-roadmap/41611).

Awesome. This is so great, I am thrilled to see this proposal. I'm sorry for the delay getting a chance to read this, but hopefully better late than never. If this is too late, then I can bring up similar points in the formal review threads.

> Task local values set in a task _cannot_ out-live the task, solving many of the pain points relating to un-structured primitives such as thread-locals, as well as aligning this feature closely with Swift's take on Structured Concurrency.

Nice.

> Tasks already require the capability to "carry metadata with them," and that metadata used to implement both cancellation, deadlines as well as priority propagation for a `Task` and its child tasks.

Yep!

> Task local values may only be accessed from contexts that are running in a task: asynchronous functions. As such all operations, except declaring the task-local value's handle are asynchronous operations.

Is this imprecision in the wording, or do you mean this literally? Synchronous functions can be called from async functions and would like to access task-local values just like async functions do. This is commonly seen in builder APIs (e.g. S4TF, SwiftUI, LLVM IR wrappers, etc) where you want to have an implicit task local context and don't want to pass it around explicitly all the time.

For example, it would be untenable in S4TF or other machine learning frameworks to have to pass context objects into calls like `Tensor<Int>(42)`, but such calls need access to task local state (so you know the current device etc) and it would be impractical to force all builder style APIs to be in async functions.

I don't think it is acceptable to punt this to [Future Directions](https://github.com/ktoso/swift-evolution/blob/wip-tasklocals/proposals/nnnn-task-locals.md#future-directions). This is core to the proposal, and the proposal isn't very useful without solving this.

> [@](#):
>
> Next, in order to access the value one has to `await Task.local(_:)` it:
> 
> func printRequestID() async { let id = await Task.local(.requestID) ?? "" print("request-id: (id)") }
> 
> Since it is not known statically if the value will be present or not, the returned value is an `Optional<String>` .
> 
> Note that none of the operations on task locals handle actually suspend; they return immediately.

I don't understand this at all. The only reason for a function to be marked `async` is if it suspends. Access to a task local value never does that, so I don't see why it would be marked async.

> [@](#):
>
> Setting values is the most crucial piece of this design, as it embraces the structured nature of Swift's concurrency. Unlike thread-local values, it is not possible to just "set" a task local using an arbitrary identifier for a look-up. The handle is bound to a specific declaration that is accessible only to its lexical _scope_ . The handle's underlying value is represented by storing it on the executing child's `Task` within that scope. Once the scope ends, the child task ends, and the associated task local value is discarded:
> 
> await Task.withLocal(.requestID, boundTo: "1234-5678") { await printRequestID() // 1234-5678 } await printRequestID() //

I understand your design point of being for library authors (e.g. like the internals of S4TF) but this seems really awkward to use in practice. Why not have a more direct getter/setter style of API, possibly wrapped up with keypaths or other nice things to make them beautiful?

> Task local values are retained until `withLocal` 's operation scope exits. Usually this means until all child tasks created in such scope exit.

This is a great goal, I agree that task-local values should be bounded by the lifetime of the task. This implies that tasks created by the structured concurrency affordances should be destroyed when their tasks are destroyed.

That said, I don't understand the need for this complexity with the `withLocal` stuff. Why can't I just have unstructured access to a task-local value with a get/set value style of API? You're already handling the case where you get a value that isn't already initialized.

Reading your "rejected alternatives" section, I agree with you that it isn't correct to just use thread local or dispatch local values naively. The solution is that the "Executor" runtime needs to be able to provide an opaque token from a sync function executing in its context for the task-local dictionary to hang off. If that executor is implemented in terms of pthreads then it can use pthreads TLS to do this. If it is implemented in dispatch, then it can use dispatch local values to implement this. If it is implementing its own mechanism, then that mechanism can handle this.

In any case, none of the executor implementation details should be exposed to the Swift code (either in syntax or in ABI) because the Swift code should be compatible with multiple different executors.

.... oh I see you address this in [future directions](https://github.com/ktoso/swift-evolution/blob/wip-tasklocals/proposals/nnnn-task-locals.md#future-directions), I agree that something like `unsafeCurrent` is the way to go. It isn't clear to me why it is unsafe though. You say:

> The `Unsafe` part of the name originates from the fact that it is NOT safe to modify such task object from _other_ tasks, and such developers must not pass such task object to other tasks.

This is also concerning to me. Why are you conflating mutability into this? Swift has well defined ways to handle mutability, why do we need another one? There should be nothing unsafe about getting an opaque task handle. Such a thing is the basis for a lot of functionality (e.g. debugging and reflection APIs etc).

While actors are out of scope for this proposal, it should also be possible to get a pointer to the current actor (or nil if not on one) from sync code as well for the same reason.

> Task local variables are semantically _inherited_ the same way by _child tasks_ similar to some other properties of a task, such as priority, deadline etc. Note that when storing reference types in task-local storage, they can be _read_ by child tasks of a task, meaning they should SHOULD be either immutable, or thread-safe by some other means.

Please refine the proposal to tie into the `ConcurrentValue` proposal here. We need one safe and consistent way to handle/reject transfers across concurrency domains.

> It is important to keep in mind the intended use case of this API. Task local values are not indented to "avoid passing parameters because I'm lazy" because generally the implicit propagation of values makes the application harder to reason about.

Just a suggestion on the writing, but I don't think it is productive to imply laziness. There are perfectly legit reasons to use "global" or "task local" state. It is also (factually) a thing that would be abused in some cases, but if you're going to try to address this concern, then please do so in a way that is more based on technical concerns than a character insult.

-Chris

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [January 25, 2021, 9:17am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/37 "2021-01-25T09:17:02Z")

</div>

Thanks a lot for the review, Chris - great to have some in-depth discussion on this 🙂

> [@Chris\_Lattner3](#):
>
> [...] better late than never. If this is too late, then I can bring up similar points in the formal review threads.

It's just on time, as this was first posted to highlight missing things in the Task proposal (which you also notice in this review 🙂) and since this was posted the missing things we ironed out in Task APIs and the upcoming Structured Concurrency Pitch #3 will have all APIs which enable this proposal to be implemented _properly_ (i.e. also working from within sync functions).

At the time of writing this in December it wasn't clear what will happen with the Task / unsafeCurrent APIs if they'll happen or not, so the linked complete implementation and pitch were not able to implement the full potential of this pitch yet -- thankfully now soon we'll be able to as the calling convention and ABI of tasks/executors is changing to manage a thread local for the `Task` so it can be used for `Task.unsafeCurrent` which enables great updates to these APIs).

So timing is good, thanks for chiming in, let's dive in...

* * *

### Usage in synchronous functions (coming very soon)

> [@Chris\_Lattner3](#):
>
> > Task local values may only be accessed from contexts that are running in a task: asynchronous functions. As such all operations, except declaring the task-local value's handle are asynchronous operations.
> 
> Is this imprecision in the wording, or do you mean this literally? Synchronous functions can be called from async functions and would like to access task-local values just like async functions do. [...]
> 
> I don't think it is acceptable to punt this to [Future Directions](https://github.com/ktoso/swift-evolution/blob/wip-tasklocals/proposals/nnnn-task-locals.md#future-directions). This is core to the proposal, and the proposal isn't very useful without solving this.

Yeah, I absolutely agree!

Back in December when this was implemented and pitched I had my hands tied somewhat by being unable to implement this given the restrictive state of the Task APIs. Access to tasks is currently implemented as "magical extra parameter to async functions," making it impossible to implement accessing a task from a sync function. It is indeed a huge, feature-breaking even, limitation...

Thankfully, during Pitch #2 of Structure Concurrency in the last weeks ([this design](https://forums.swift.org/t/pitch-2-structured-concurrency/43452/116)) we were able to hash out the missing and misaligned APIs which resulted in: [Task as struct, static non-async funcs, and UnsafeCurrentTask by ktoso · Pull Request #48 · DougGregor/swift-evolution · GitHub](https://github.com/DougGregor/swift-evolution/pull/48) which will be Pitch #3 of those APIs.

This implies changes in ABI/calling-convention how a Task is passed around, so it's still not implementable until that is changed, but at least the team seems to be agreeing on adding `Task.unsafeCurrent` so finally we can express task locals within synchronous functions and this proposal becomes wholly useful then 🥳

> [@Chris\_Lattner3](#):
>
> I don't understand this at all. The only reason for a function to be marked `async` is if it suspends. Access to a task local value never does that, so I don't see why it would be marked async.

The writeup above I hope answers this: this _was_ the only way to implement this. It sucks, and it will be fixed in Pitch #3 with introduction of `Task.unsafeCurrent` 👍

Indeed, `Task.local(\.x) ` becomes non-async then 👍

* * *

### withLocal { ... } spelling

> [@Chris\_Lattner3](#):
>
> > [@](#):
> >
> > await Task.withLocal(.requestID, boundTo: "1234-5678") { await printRequestID() // 1234-5678 } await printRequestID() //
> 
> I understand your design point of being for library authors (e.g. like the internals of S4TF) but this seems really awkward to use in practice. Why not have a more direct getter/setter style of API, possibly wrapped up with keypaths or other nice things to make them beautiful?

> [@Chris\_Lattner3](#):
>
> Why can't I just have unstructured access to a task-local value with a get/set value style of API? You're already handling the case where you get a value that isn't already initialized.

Reads are trivial and solved, as you say.

It is the "binds" that must be _structured_. The reason it can't be "just a setter" you kind of said yourself -- it would not be structured.

As usual... with enough compiler magic, everything is doable, and we could implement it as:

```swift
func foo() {
  // yeah we could even do Task.local.foo = 222, 
  // I did exactly such API for swift-distributed-tracing's attributes;
  Task.local(\.foo) = 222 // "pushes" a binding to task-local bindings stack

  // every binding magically generates:
  // @synthesized defer { Task._popTaskLocalValue() }
  // which must "pop" the binding off the task-local bindings as we return

  assert(Task.local == 222)
}

Task.local(\.foo) = 111
foo() // NOT a child task; foo is 222 inside there.
assert(Task.local(\.foo) == 111) // this assertion MUST hold

```

So while this may be "less noise" it is definitely a lot more magic and surprising: we're writing to something that looks static, but it'll automagically isn't and unbinds at the end of the scope...

Whereas the `with` style has lots of prior art and feels like pretty normal day-to-day Swift. There is no need to explain any magical semantics when presenting the following code:

```swift
func foo() {
  let before = Task.local(\.foo)

  Task.with(\.foo, boundTo: 222) {
    assert(Task.local(\.foo) == 222)
  }

  assert(Task.local(\.foo) == before)
}

```

This both enforces the right semantics, and informs the programmer with the shape of the API what's going to happen here. Is pretty much "normal" swift code and no-one has to jump through learning the specialized magical semantics of scoped task local values to understand this. Therefore, I think, the body/scope of `withLocal(...) {...}` is not noise, but helpful information.

So I really believe the less magic version is much preferable here, because it is more true to what is actually happening.

### "currentActor"

> While actors are out of scope for this proposal, it should also be possible to get a pointer to the current actor (or nil if not on one) from sync code as well for the same reason.

Yeah that's absolutely useful and probably one of the main things we'd spend time on when instrumenting Akka 😉 It helps a lot in debugging/logging and just understanding what's going on in the system.

+1 overall, but let's keep this separate from this proposal. I do suspect though we'll end up having such thing. Probably through the Task.current APIs 🤔

* * *

> [@Chris\_Lattner3](#):
>
> > The `Unsafe` part of the name originates from the fact that it is NOT safe to modify such task object from _other_ tasks, and such developers must not pass such task object to other tasks.
> 
> This is also concerning to me. Why are you conflating mutability into this? Swift has well defined ways to handle mutability, why do we need another one? There should be nothing unsafe about getting an opaque task handle. Such a thing is the basis for a lot of functionality (e.g. debugging and reflection APIs etc).

That's a specific request from @John_McCall -- this isn't really about the task local values but about the general existence of an "give me a handle with full access to everything, even APIs which should never be called from a _different_ task". We can get into the details of that `Unsafe...` name and type in the Pitch #3 of Structured Concurrency which should be posted this week I hope.

The actual unsafety of it comes not really from the `Task.unsafeCurrent` but the fact someone could escape/store this value and then use it from a different task, that's the unsafeness we're concerned about. John wanted to eventually make a type that's "un-movable" which then could be safe, since we'd prevent people from doing this. `ConcurrentValue` things don't really solve this -- people could store it in some property and then touch the same property, get that `UnsafeCurrentTask` from a different task and poke at it unsafely.

> [@Chris\_Lattner3](#):
>
> > Task local variables are semantically _inherited_ the same way by _child tasks_ similar to some other properties of a task, such as priority, deadline etc. Note that when storing reference types in task-local storage, they can be _read_ by child tasks of a task, meaning they should SHOULD be either immutable, or thread-safe by some other means.
> 
> Please refine the proposal to tie into the `ConcurrentValue` proposal here. We need one safe and consistent way to handle/reject transfers across concurrency domains.

Will do, by now the `ConcurrentValue ` is fleshed out enough and looking good that this seems like a good time to refer to it. I agree that restricting values stored in task locals to `ConcurrentValue` is a good idea 👍

* * *

> [@Chris\_Lattner3](#):
>
> > It is important to keep in mind the intended use case of this API. Task local values are not indented to "avoid passing parameters because I'm lazy" because generally the implicit propagation of values makes the application harder to reason about.
> 
> Just a suggestion on the writing, but I don't think it is productive to imply laziness. There are perfectly legit reasons to use "global" or "task local" state. It is also (factually) a thing that would be abused in some cases, but if you're going to try to address this concern, then please do so in a way that is more based on technical concerns than a character insult.

Thanks for the catch here; my self-deprecating humor backfired here, will reword this -- thanks for pointing it out 👍

Please let me know if this makes sense -- in the meantime I think it's time to prepare Pitch #2 here and base it on the existence of the upcoming Task.unsafeCurrent 🙂

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [January 25, 2021, 1:05pm UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/38 "2021-01-25T13:05:06Z")

</div>

Amended proposal to assume the upcoming `Task.unsafeCurrent` so those will be able to be used inside synchronous functions as well.

Diff here: [[Concurrency] Task Local Values by ktoso · Pull Request #1245 · apple/swift-evolution · GitHub](https://github.com/apple/swift-evolution/pull/1245/commits/8733e61d9b0d02945570649a9d2f92a73b0f687b)

I'll kick off a Pitch #2 thread after pitch #3 of the structured APIs is out, but we can also just continue in this thread for now.

---

<div class="post-metadata">

**Author:** ![michelf](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/michelf/32/1180_2.png) [@michelf](https://forums.swift.org/u/michelf)\
**Post date:** [January 25, 2021, 2:05pm UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/39 "2021-01-25T14:05:22Z")

</div>

> [@ktoso](#):
>
> It is the "binds" that must be _structured_ . The reason it can't be "just a setter" you kind of said yourself -- it would not be structured.

I do wonder why it is a requirement that it be structured like this though. Global variables aren't modeled like this. It also occurs to me that it's relatively easy to implement the current scoped design on top of unstructured variables while the reverse is cumbersome and less efficient.

After looking at those examples since the first pitch, I don't find the forced scoped nature to be intuitive, neither as a concept nor as a syntax. It seems to me the learning curve would be much easier if they worked like global variables. And it's not hard to make something scoped if you need that for a particular variable.

> **Scoped task-local implemented on top of an unstructured task-local**
>
> ```swift
> @taskLocal private(set) var foo: Int = 0
> func withFoo(_ value: Int, _ task: () -> ()) {
> let savedValue = foo
> foo = value
> defer { foo = savedValue }
> task()
> }
> func test() {
> assert(foo == 0)
> withFoo(1) {
> assert(foo == 1)
> }
> assert(foo == 0)
> }
> 
> ```

* * *

(That said, if they keep their current scoped nature, I think if they should be called "task _environment_ values". "Task _local_ value" sounds too close to thread-local, which has a lot of history for being a per-thread global-like unstructured variable.)

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [January 27, 2021, 2:16am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/40 "2021-01-27T02:16:06Z")

</div>

No, there _must not_ be any unstructured API to "set" such values with the _hope_ that everyone actually only ever uses it in a structured way.

This is exactly the world of pain asynchronous runtimes are continuously facing when trying to apply instrumentation, yet a single user-call using the wrong pattern completely breaks all traces and instrumentation performed on the system.

I base this on both personal experience of building _and_ instrumenting asynchronous actor and streaming runtimes, as well as specific [prior art](https://github.com/ktoso/swift-evolution/blob/wip-tasklocals/proposals/nnnn-task-locals.md#prior-art), most notably [Project Loom's](https://cr.openjdk.java.net/~rpressler/loom/loom/sol1_part2.html#scope-variables) latest efforts which are a direct answer to the suffering of instrumenting async systems without such structure. Not mentioning the numerous threads of various tracers where the most common issue is accidentally dropping a value, forgetting to "reset it to the previous value on return" and all these things which are impossible to get wrong if we stick to scopes as the _only_ API to bind such values.

* * *

Just one simple example to show how things break down with the unstructured access you are proposing:

```swift
// what-if unstructured writes allowed
// (semantics as proposed by @michelf in post #39)
@taskLocal private(set) var traceID: String = "none"

{
traceID = "parent"
  func inner() async { 
    assert(traceID == "parent")
    traceID = "inner"
    // isn't a child task; is not even suspending
  }
  await inner() 
    // assert traceID == parent, OK
    // ! traceID = inner, correctly, within this function we have a new "ID"
    // ! no "reset"
  await inner() 
    // assert traceID != parent, BAD (!)
}

```

And the only way to restore correctness here, is to force every single function that ever touches any task local to also store the previous value (causes copying, and retain/releases), and restore/reset it as it returns. This is exactly what current day, un-structured runtimes have to do. Most of them have to weave code into functions to actually get it right, which is error prone, goes wrong often and is just incredibly accidental complexity.

Even the best developers, who absolutely _know_ about this rule get it wrong _all the time_ and it tremendously undercuts the usefulness of instrumentations when such mistakes are made. Even worse, finding out where the mistake is is often a very difficult task, since it is the _missing_ of a call in a _very specific place_ that is the bug, not the presence of a wrong call.

And if "tracing" seems alien and not something you're using, consider that Instruments needs exactly the same semantics and infrastructure to weave through identifiers through asynchronous code. We _must_ get this right, and not be swayed by it looking slightly unfamiliar.

* * *

Naming: Sure we can continue discussing names but I don't think it is reason enough to move away from "Task Local" because it sounds similar to "Thread Local", in fact that's good -- it's the "you should be using this instead of thread locals", so similarity is fine and welcome. If we had to change then "Scope Values" is a good name candidate, but I had feedback already that "Scope" is very generic, there's tons of scopes in Swift, which can lead to confusion i.e. "is any let in a scope a scope value?"

edit: typos  
edit 2: added note on naming

---

<div class="post-metadata">

**Author:** ![michelf](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/michelf/32/1180_2.png) [@michelf](https://forums.swift.org/u/michelf)\
**Post date:** [January 27, 2021, 3:34am UTC](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829/41 "2021-01-27T03:34:01Z")

</div>

> [@ktoso](#):
>
> No, there _must not_ be any unstructured API to "set" such values with the _hope_ that everyone actually only ever uses it in a structured way.

That's why I made it `private(set)` in my example. I acknowledge that for some use cases you don't want to allow arbitrary writes, and the answer is to provide a scoped setter that guaranties the structure you want and make the storage `private(set)`.

There's definitely a place for structured variables, I'm mostly wondering whether this should be the only option. For instance, consider a use case more like this:

```swift
// what-if unstructured writes allowed
@taskLocal private(set) var taskLog: [String] = []

try {
   taskLog.append("Beginning Task")
   func inner() async { 
     taskLog.append("Doing inner things")
   }
   await inner() 
   taskLog.append("Between two inner things")
   await inner() 
   taskLog.append("Task Done")
} catch {
   print("Something went wrong: \(error)")
   print(taskLog) // only print if something goes wrong
}

```

Is this something reasonable to want to implement that way?

I can also see someone wanting to refactor a single-threaded program or algorithm to make it parallelizable: add `@taskLocal` to all the global variables and most of the work is done. (Maybe not the best way, but it'd be quick and convenient.)

[Previous page](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829.md?page=1)

[Next page](https://forums.swift.org/t/concurrency-pitch-task-local-values/42829.md?page=3)
