# ATS

An `ATS[K, V]` (Agentica Table Storage) is a table that tasks share and update in place, like Erlang's ETS. Values stay immutable; a table is the one shared place that changes. Use a [Channel](https://www.agentica-lang.com/agentica/library/concurrency/channel/index.md) to pass messages, and a table for state that many tasks read and update, such as a counter or a cache.

- A table is a handle: passing it to a function or task shares it, it is never copied. It may be a struct field, a list element, a `Map` value, or a `Task.spawn` argument or result, but not a value inside a table. A constant holds one only as its whole initializer, `ATS.new()` ([a constant table](https://www.agentica-lang.com/agentica/library/concurrency/ats/index.md#a-constant-table)); anywhere else in a constant it is `CHECK-CONSTANT-TYPE`. `ATS` is a reserved name: a user `struct`, `enum` or import alias named `ATS` is `CHECK-REDEFINED-NAME`.
- Keys are `Int`, `String` or `Bytes`, as for a `Map`, else `CHECK-MAP-KEY-TYPE`. Values are data with no `Fn`, `Task`, `Channel`, handle, `Lazy` or table inside, and not `Nil`, else `CHECK-ATS-VALUE` at the value type. The test is deep: it looks through struct fields, list elements, enum payloads, `Map` values and `Result`, and refuses `Fn` because a block can capture a handle. A channel's [`Address`](https://www.agentica-lang.com/agentica/library/concurrency/channel/index.md#channeladdress) is data, so a table can hold the addresses of channels. A nested `Result[Void]` is allowed; `V` itself as `Void` is `CHECK-VOID-TYPE`. A type parameter is refused as `V` (a generic enum payload `ATS[String, T]`), since its uses would not be checked; a generic alias is checked where it is used.
- Each call is atomic, on any scheduler: a reader sees the table before or after a write, never half of it. No call takes a block, so no user code runs inside a call, and a call cannot deadlock or re-enter the table.
- All but `new` also work as methods: `hits.add("home", 1)` is `ATS.add(hits, "home", 1)`.
- `puts`, `print`, interpolation and `==` on a table are `CHECK-TYPE-MISMATCH`, `.to_s` is `CHECK-UNKNOWN-METHOD`, and a struct with a table field is `CHECK-NOT-ENCODABLE` as JSON. `IO.inspect` prints `<ATS>` without the contents. Use `to_map` to see them.
- The garbage collector frees a table when nothing refers to it. It is not an OS resource, so the owner rule of handle ownership does not apply: the task that made it does not own it, its end does not close it, and `Task.spawn_owning` is not needed. A task reaches a table through a handle it was given or through a constant table. A table belongs to the run that made it, and a call from another run stops with `RUNTIME-ATS-CONTEXT`.
- There is no size limit and no expiry; a bounded cache is [std/cache](https://www.agentica-lang.com/agentica/library/concurrency/cache/index.md), a `std/` module on top of `ATS`, and an expiring one belongs in a module too. Not supported: ordered tables, duplicate keys (keep a list per key with [`ATS.push`](https://www.agentica-lang.com/agentica/library/concurrency/ats/index.md#atspush)), a block-based `update`, a compare-and-swap `replace`, and tables shared between OS processes.
- `put`, `put_new`, `delete`, `clear`, `add` and `push` carry the `concurrency` effect, which also keeps `CHECK-UNUSED-VALUE` away from an ignored `put_new`, `add` or `push`.
- `get`, `put`, `put_new`, `has_key?`, `delete`, `add` and `push` take O(1) on average, whatever the table size, and `size` and `clear` O(1). `keys` and `to_map` take O(n): they copy the table while no write runs, then build their list or map without holding back other tasks. A read takes no lock and writes nothing the other schedulers see, so tasks that read one table run in parallel; a read that a write overlaps tries again. A write waits for the other writes to that table, and for a `keys` or `to_map` copy, for the length of one call. So writes to one table do not run in parallel, also when they write different keys.
- In BDD, a worker process runs the step program's `main` once and then many scenarios, so a table made in `main` and captured by step blocks is shared by the scenarios that worker runs. To have a fresh one in each scenario, make it in a step and keep it with `BDD.keep`, or run `agentica test --isolate`, which runs each scenario, and `main` again, in a process of its own. A table cannot go in the JSON state of `BDD.set`.

## ATS.new

```signature
ATS.new() -> ATS[K, V]
```

Creates an empty table. It needs an expected type (annotation, parameter, field or return type), else `CHECK-EXPECTED-TYPE`.

```agentica
def main() -> Void
  hits = ATS.new()
end
```

Does not compile: `error[CHECK-EXPECTED-TYPE]`

```agentica
def main() -> Void
  jobs: ATS[String, Task[Int]] = ATS.new()
end
```

Does not compile: `error[CHECK-ATS-VALUE]`

## A constant table

A constant whose whole initializer is `ATS.new()`, with its type written, is a table made once per run before `main`, like every other constant. Every task of the run and every file that imports the constant share the one table, so it gives state per program with a static type, such as a registry of names to [addresses](https://www.agentica-lang.com/agentica/library/concurrency/channel/index.md#channeladdress). Without the type it is `CHECK-EXPECTED-TYPE`; a table anywhere else in a constant (`[ATS.new()]`, a struct field, another constant's table) is `CHECK-CONSTANT-TYPE`.

```agentica
HITS: ATS[String, Int] = ATS.new()

def visit(page: String) -> Int = HITS.add(page, 1)

def main() -> Void
  tasks = ["home", "home", "about"].map do |page| Task.spawn(&visit, page) end
  tasks.each do |t| Task.await(t) end
  puts(HITS.get("home").unwrap!)
end
```

```output
2
```

```agentica
TABLES: List[ATS[String, Int]] = [ATS.new()]

def main() -> Void
  puts(TABLES.size)
end
```

Does not compile: `error[CHECK-CONSTANT-TYPE]`

## ATS.put, ATS.put_new and ATS.get

```signature
ATS.put(table: ATS[K, V], key: K, value: V) -> Void
ATS.put_new(table: ATS[K, V], key: K, value: V) -> Bool
ATS.get(table: ATS[K, V], key: K) -> Result[V]
ATS.has_key?(table: ATS[K, V], key: K) -> Bool
```

`put` inserts or replaces. `put_new` inserts only when the key is absent and gives `true`; `false` leaves the table unchanged. `get` gives `ok(value)`, or an error when the key is absent.

```agentica
def main() -> Void
  names: ATS[Int, String] = ATS.new()
  names.put(1, "ana")
  names.put(1, "eve")
  puts(names.put_new(1, "bob"))
  puts(names.put_new(2, "bob"))
  puts(names.get(1).unwrap!)
  puts(names.get(3).ok?)
  puts(names.has_key?(2))
end
```

```output
false
true
eve
false
true
```

## ATS.add

```signature
ATS.add(table: ATS[K, Int], key: K, by: Int) -> Int
```

Adds `n` to the value of the key, an absent key counting as 0, and gives the new value. The read and the write are one atomic step, so tasks that add at the same time lose no update. It works only on a table of `Int` values, else `CHECK-TYPE-MISMATCH`. A result outside the 64-bit range stops with `RUNTIME-INTEGER-OVERFLOW` and leaves the table unchanged.

```agentica
def count_visits(hits: ATS[String, Int]) -> Void
  for _ in 1..100
    hits.add("home", 1)
  end
end

def main() -> Void
  hits: ATS[String, Int] = ATS.new()
  tasks = [1, 2, 3, 4].map do |_| Task.spawn(&count_visits, hits) end
  tasks.each do |task| Task.await(task) end
  puts(hits.get("home").unwrap!)
end
```

```output
400
```

## ATS.push

```signature
ATS.push(table: ATS[K, List[E]], key: K, value: E) -> Int
```

Appends `value` to the list of the key, an absent key counting as an empty list, and gives the new length. The read and the write are one atomic step, so tasks that push to the same key at the same time lose no item; a `get` followed by a `put` can lose one. A push builds its new list first and starts again when another task changed the key meanwhile, so many tasks that push to one key at the same time repeat work: give each its own key when the lists are long. It works only on a table whose values are lists, else `CHECK-TYPE-MISMATCH`.

```agentica
def main() -> Void
  rooms: ATS[String, List[String]] = ATS.new()
  tasks = ["ana", "bob", "eve"].map do |name| Task.spawn { rooms.push("lobby", name) } end
  tasks.each do |task| Task.await(task) end
  puts(rooms.get("lobby").unwrap!.sort)
  puts(rooms.push("hall", "ana"))
end
```

```output
["ana", "bob", "eve"]
1
```

## ATS.delete and ATS.clear

```signature
ATS.delete(table: ATS[K, V], key: K) -> Void
ATS.clear(table: ATS[K, V]) -> Void
```

`delete` removes the key; an absent key is ignored. `clear` removes every key in one step, whatever the size of the table: a reader sees the table full or empty, a snapshot taken before keeps its keys, and a write that runs at the same time lands before the clear and is removed, or after it and stays.

```agentica
def main() -> Void
  stock: ATS[String, Int] = ATS.new()
  stock.put("tea", 3)
  stock.put("milk", 1)
  before = stock.keys
  stock.clear
  puts(stock.size)
  puts(before)
  puts(stock.add("tea", 1))
end
```

```output
0
["tea", "milk"]
1
```

## ATS.size, ATS.keys and ATS.to_map

```signature
ATS.size(table: ATS[K, V]) -> Int
ATS.keys(table: ATS[K, V]) -> List[K]
ATS.to_map(table: ATS[K, V]) -> Map[K, V]
```

Each reads the table as it is at the call. `keys` and `to_map` list the keys in first-insertion order; a key deleted and put again goes to the end, as in `Map`. There is no `values` and no `get` with a default: use `to_map` and `Result.unwrap_or`.

```agentica
def main() -> Void
  stock: ATS[String, Int] = ATS.new()
  stock.put("tea", 3)
  stock.put("milk", 1)
  stock.put("bread", 2)
  stock.delete("tea")
  stock.put("tea", 5)
  puts(stock.size)
  puts(stock.keys)
  IO.inspect(stock.to_map)
end
```

```output
3
["milk", "bread", "tea"]
{"milk": 1, "bread": 2, "tea": 5}
```

## A cache that tasks fill

The first task that misses a key computes its value and stores it with `put_new`; a task that misses at the same time computes it too, but only one value is stored. A second table counts the work.

```agentica
struct Shared
  cache: ATS[Int, String]
  stats: ATS[String, Int]
end

def lookup(shared: Shared, n: Int) -> String
  found = shared.cache.get(n)
  return found.unwrap! if found.ok?

  text = "#{n} squared is #{n * n}"
  if shared.cache.put_new(n, text)
    shared.stats.add("stored", 1)
  end

  text
end

def work(shared: Shared) -> Void
  for n in 1..3
    lookup(shared, n)
  end
end

def main() -> Void
  cache: ATS[Int, String] = ATS.new()
  stats: ATS[String, Int] = ATS.new()
  shared = Shared(cache: cache, stats: stats)
  tasks = [1, 2, 3].map do |_| Task.spawn(&work, shared) end
  tasks.each do |task| Task.await(task) end
  puts(stats.get("stored").unwrap!)
  cache.keys.sort.each do |n| puts(cache.get(n).unwrap!) end
end
```

```output
3
1 squared is 1
2 squared is 4
3 squared is 9
```

`add` and `push` are the atomic updates and `put_new` the one conditional insert. There are no transactions over several keys: to update other values safely, let one owner task do the writes ([State owned by one task](https://www.agentica-lang.com/agentica/library/concurrency/channel/index.md#state-owned-by-one-task)).
