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 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
Mapvalue, or aTask.spawnargument or result, but not a value inside a table. A constant holds one only as its whole initializer,ATS.new()(a constant table); anywhere else in a constant it isCHECK-CONSTANT-TYPE.ATSis a reserved name: a userstruct,enumor import alias namedATSisCHECK-REDEFINED-NAME. - Keys are
Int,StringorBytes, as for aMap, elseCHECK-MAP-KEY-TYPE. Values are data with noFn,Task,Channel, handle,Lazyor table inside, and notNil, elseCHECK-ATS-VALUEat the value type. The test is deep: it looks through struct fields, list elements, enum payloads,Mapvalues andResult, and refusesFnbecause a block can capture a handle. A channel’sAddressis data, so a table can hold the addresses of channels. A nestedResult[Void]is allowed;Vitself asVoidisCHECK-VOID-TYPE. A type parameter is refused asV(a generic enum payloadATS[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
newalso work as methods:hits.add("home", 1)isATS.add(hits, "home", 1). puts,print, interpolation and==on a table areCHECK-TYPE-MISMATCH,.to_sisCHECK-UNKNOWN-METHOD, and a struct with a table field isCHECK-NOT-ENCODABLEas JSON.IO.inspectprints<ATS>without the contents. Useto_mapto 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_owningis 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 withRUNTIME-ATS-CONTEXT. - There is no size limit and no expiry; a bounded cache is std/cache, a
std/module on top ofATS, and an expiring one belongs in a module too. Not supported: ordered tables, duplicate keys (keep a list per key withATS.push), a block-basedupdate, a compare-and-swapreplace, and tables shared between OS processes. put,put_new,delete,clear,addandpushcarry theconcurrencyeffect, which also keepsCHECK-UNUSED-VALUEaway from an ignoredput_new,addorpush.get,put,put_new,has_key?,delete,addandpushtake O(1) on average, whatever the table size, andsizeandclearO(1).keysandto_maptake 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 akeysorto_mapcopy, 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
mainonce and then many scenarios, so a table made inmainand 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 withBDD.keep, or runagentica test --isolate, which runs each scenario, andmainagain, in a process of its own. A table cannot go in the JSON state ofBDD.set.
ATS.new #
ATS.new() -> ATS[K, V]Creates an empty table. It needs an expected type (annotation, parameter, field or return type), else CHECK-EXPECTED-TYPE.
def main() -> Void
hits = ATS.new()
enderror[CHECK-EXPECTED-TYPE]def main() -> Void
jobs: ATS[String, Task[Int]] = ATS.new()
enderror[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. 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.
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!)
end2TABLES: List[ATS[String, Int]] = [ATS.new()]
def main() -> Void
puts(TABLES.size)
enderror[CHECK-CONSTANT-TYPE]ATS.put, ATS.put_new and ATS.get #
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) -> Boolput 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.
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))
endfalse
true
eve
false
trueATS.add #
ATS.add(table: ATS[K, Int], key: K, by: Int) -> IntAdds 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.
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!)
end400ATS.push #
ATS.push(table: ATS[K, List[E]], key: K, value: E) -> IntAppends 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.
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["ana", "bob", "eve"]
1ATS.delete and ATS.clear #
ATS.delete(table: ATS[K, V], key: K) -> Void
ATS.clear(table: ATS[K, V]) -> Voiddelete 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.
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))
end0
["tea", "milk"]
1ATS.size, ATS.keys and ATS.to_map #
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.
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)
end3
["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.
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
end3
1 squared is 1
2 squared is 4
3 squared is 9add 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).