> For the complete documentation index, see [llms.txt](https://docs.keewano.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.keewano.com/lua-scripting/reference.md).

# Lua Reference

The complete surface: finders, chains, resolvers, the sandbox, limits, and errors.

This is the lookup companion to the [Lua Scripting over KeewanoDB — Guide](https://docs.keewano.com/lua-scripting/guide.md). It assumes the model the guide sets out: one script defines `partial`, `process_user`, `reduce`, and `output`; the runtime calls `process_user` once per user over that user's ordered event array, and `reduce` merges the per-group partials into the final result. If any term here is unfamiliar, the guide explains it in full.

***

## The event array and finders

Inside `process_user(user, events)`, `events` is one user's stream in time order, read by index.

| Accessor       | Meaning                                                                  |
| -------------- | ------------------------------------------------------------------------ |
| `events.count` | How many events this user has.                                           |
| `events[i]`    | The event at position `i` (0-based; last is `events[events.count - 1]`). |

Reading `events[i]` with `i` outside `[0, events.count)` fails the run with a clear error. A position is just an integer you control — remembering a spot to return to is copying the integer; stepping back one is `i - 1`.

### Reading an event

`events[i]` gives an event, which answers only about itself — it never moves you through the array.

| Accessor       | Meaning                                                 |
| -------------- | ------------------------------------------------------- |
| `ev.index`     | This event's own index (the `i` it came from).          |
| `ev.id`        | Event id — compare against `kdb.resolve_event_id(...)`. |
| `ev.data`      | Numeric data field.                                     |
| `ev.timestamp` | Unix timestamp (UTC seconds).                           |

### The finder family

When you are scanning for something, use a finder rather than stepping every event — each is one scan in native code, often 10×+ faster. The range rules are uniform:

* Every finder takes `start_index` first and a mandatory stop bound last.
* Forward finders scan `[start_index, stop)` — stop is **exclusive**; pass `events.count` to search to the end.
* Backward finders scan `[stop, start_index]` downward — stop is **inclusive**; pass `0` to search all history.
* A miss returns `events.count` either way. An empty or inverted range is simply a miss, never an error — so the usual `i + 1` loop arithmetic needs no guards.
* Passing `stop > events.count` stops the query with an error (the bound names an event that doesn't exist).

| Finder                                            | Returns                                                                                                                                                                                               |
| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `events:find_next(start, id, stop)`               | First event with `id` in `[start, stop)`; else `events.count`.                                                                                                                                        |
| `events:find_next_data(start, id, data, stop)`    | Same, also matching the event's data value.                                                                                                                                                           |
| `events:find_prev(start, id, stop)`               | First event with `id` in `[stop, start]`, scanning backward; else `events.count`.                                                                                                                     |
| `events:find_prev_data(start, id, data, stop)`    | Backward twin, also matching data.                                                                                                                                                                    |
| `events:find_next_with_ids(start, {ids}, stop)`   | First event whose id is any of up to 8 ids, one scan. The `{ids}` table must be a literal of names/numbers known at upload.                                                                           |
| `events:find_prev_with_ids(start, {ids}, stop)`   | Backward twin.                                                                                                                                                                                        |
| `events:find_next_income(start, stop)`            | Next purchase / ad-revenue / subscription event (needs `require "game_analytics"`).                                                                                                                   |
| `events:find_prev_income(start, stop)`            | Backward twin.                                                                                                                                                                                        |
| `events:find_next_gap_in_time(start, secs, stop)` | First event after a silence of at least `secs` — the next activity burst's start.                                                                                                                     |
| `events:find_prev_gap_in_time(start, secs, stop)` | First event of the burst containing `start`, never below `stop`. Returns `stop` when the burst extends past the bound — always a valid burst start, never a miss. An inverted range here is an error. |

The stop bound is what makes windowed questions both cheap and honest: a finder given a session's end never scans past it, and never matches the next session's events.

***

## User fields

Inside `process_user`, read per-user metadata via `user.<field>`. These don't touch the event array, are constant for the call, and are free to read.

| Field                                                                              | Meaning                                                      |
| ---------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| `user.id`                                                                          | Stringified user id.                                         |
| `user.reg_time`                                                                    | Registration time (unix).                                    |
| `user.last_activity`                                                               | Last activity time (unix).                                   |
| `user.campaign`                                                                    | Marketing campaign id.                                       |
| `user.is_tester` / `user.is_bot`                                                   | Booleans.                                                    |
| `user.is_paying_user`                                                              | Boolean.                                                     |
| `user.country`                                                                     | Country code (numeric).                                      |
| `user.platform` / `user.os`                                                        | Numeric.                                                     |
| `user.device_type` / `user.gpu_type`                                               | Numeric.                                                     |
| `user.ram_size` / `user.vram_size`                                                 | MB.                                                          |
| `user.screen_width` / `user.screen_height`                                         | Pixels.                                                      |
| `user.system_language` / `user.first_game_language` / `user.current_game_language` | Numeric language codes.                                      |
| `user.reg_app_version` / `user.current_app_version`                                | Version (numeric). Should be obtained via `event_data_text`. |

***

## Chains in full

Some events carry more than one field. In the stored array these are laid out as a first event followed by detail events — a **chain**. The first event anchors it: finders jump to it, and the chain spans from it to `end_pos`.

### Defining a chain

A descriptor names the layout. Every entry is `<field> = <event id or name>`, in stream order, and the first entry names the chain's first event. Field types are never declared — the platform reads each value's encoding (number, interned string, USD cents, float) from your event metadata at upload, so a text field compares to text and a cents field reads as USD. You cannot get it wrong because you never say it.

```lua
quest_reward = kdb.chain {
  at     = "Quest Done",          -- the chain's first event (any field name works)
  reward = "Quest Reward Item",
  qty    = "Quest Reward Qty",
}
```

A chain carrying a repeating run of pairs (a loot drop, a multi-item barter) declares that run with `kdb.array(<tuple>)`, where the tuple is a named top-level table. Arrays come after all scalar fields. Unions of your own chains work too: `mine = kdb.any_of { a, b }`.

```lua
loot_item = { name = "Loot Item", count = "Loot Count" }
loot_drop = kdb.chain { at = "Loot Dropped", items = kdb.array(loot_item) }
```

{% hint style="info" %}
**Limits per chain:** at most 8 scalar fields, 2 arrays of up to 4 members each, 8 distinct detail events. Definitions are top-level and compile-time; any event of your project can start a chain or be a detail.
{% endhint %}

From one descriptor the platform derives, at upload: a typed getter `events[i]:get_quest_reward()`; forward/backward finders `find_next_quest_reward` / `find_prev_quest_reward` (same range rules and miss value as `find_next`); the declared fields plus the span `start_pos` / `end_pos`; and the first entry as a usable event (`q.at.timestamp`, `q.at.id`, …).

### Reading a chain, and its validation

Two steps, always: ask the event for the chain (a handle, or `nil`), and only if non-nil, read the fields. The getter's result must be bound to a local — reading `ev:get_quest_reward().qty` inline is an upload error.

```lua
partial.qty = 0
function process_user(user, events)
  local n = events.count
  local i = events:find_next_quest_reward(0, n)
  while i < n do
    local q = events[i]:get_quest_reward()      -- ask
    if q then                                    -- confirmed → read
      partial.qty = partial.qty + q.qty
    end
    i = events:find_next_quest_reward(q and q.end_pos or i + 1, n)
  end
end
```

The getter verifies the chain's fixed part: its first event and every declared field must be present, so a chain cut off by the end of the stream answers `nil`, never a garbage read. Reading a field off an index the getter didn't confirm fails the run (`chain field mismatch at index N`).

An array's length is variable, so it is validated where it is read instead: a tuple that starts and doesn't finish while more events follow means the run was torn (a query filter dropped events the chain needs) and is a run-time error. A run cut by the very end of the stream simply yields the tuples that are fully there.

### Spanning and item groups

Every handle knows its span: `c.start_pos` (the first event's index) and `c.end_pos` (one past the last event, exclusive). Use `end_pos` to skip a whole chain's body in one move — `i = c.end_pos` lands on the first event after it.

A variable-length run is an **item group**. Bind it to a local first (that scans to its start once, making every `f[k]` read O(1)), then read `f.count` and index its 0-based elements:

```lua
local f = c.gave                      -- everything spent (bind once)
for k = 0, f.count - 1 do
  if f[k].name == kdb.resolve_event_data("coins") then
    partial.coins_spent = partial.coins_spent + f[k].count
  end
end
```

`f[k]` with `k >= f.count` is a run-time error, and item bindings are read-only. Summing a group visits every pair — a multi-item chain is never undercounted.

### Built-in chains — the game\_analytics module

`require "game_analytics"` registers the standard monetization and economy chains. Every one also carries `start_pos`, `end_pos`, and its first event `at`:

| Ask                                   | Handle fields                                          |
| ------------------------------------- | ------------------------------------------------------ |
| `ev:get_purchase()`                   | `usd`, `name`                                          |
| `ev:get_ad_revenue()`                 | `usd`, `name`                                          |
| `ev:get_subscription()`               | `usd`, `name`                                          |
| `ev:get_income()`                     | `usd`, `name`, `kind` (matches any of the three above) |
| `ev:get_items_exchange()`             | `from`, `to` — item groups                             |
| `ev:get_items_purchased_grant()`      | `items` — an item group                                |
| `ev:get_items_ad_granted()`           | `items` — an item group                                |
| `ev:get_items_subscription_granted()` | `items` — an item group                                |

`income` is defined as a union `kdb.any_of { purchase, ad_revenue, subscription }`, and `kind` is the member's position in that list — purchase = 0, ad\_revenue = 1, subscription = 2. The same rule applies to any `kdb.any_of` you define, and its finder scans all member heads in one pass.

***

## Resolvers and output markers

`ev.id` and `ev.data` are numbers. The resolvers convert strings to those numbers at upload; output markers convert numbers back to display text after the query. Neither costs anything at query time.

### Resolvers — strings in

```lua
local BOSS   = kdb.resolve_event_id("Boss Fight")    -- becomes a number at upload
local WANTED = kdb.resolve_event_data("dragon")
local i = events:find_next_data(0, BOSS, WANTED, events.count)
```

Arguments must be knowable at upload: a string literal or any path into `params`. Unknown event names are upload errors; a value that never occurs simply never matches. Comparing a raw string against `ev.id` / `ev.data` is rejected at upload with a hint to the right resolver — never silently false.

Structured params work at any nesting — string arrays, arrays of structs, structs of arrays — and stay fast: every resolved path projects into a hidden precomputed table of numbers, so all of these are plain table lookups at run time:

```lua
local ids = kdb.resolve_event_id(params.event_names)     -- hidden table of ids
for k, f in ipairs(params.filters) do                    -- {{event=,value=}, ...}
  local i = events:find_next_data(0, kdb.resolve_event_id(f.event),
                                     kdb.resolve_event_data(f.value), events.count)
end
```

Tracing follows lexical scope (renames, element copies, field reads, loops) but never crosses function parameters or returns — resolve at the leaf and pass numbers into functions.

### Output markers — text out

Two functions produce opaque markers the platform replaces with current display text after the query:

```lua
function reduce(partials)
  output.top_event = kdb.event_name(best_id)               -- → "Boss Fight"
  output.top_value = kdb.event_data_text(best_id, best_d)  -- → "dragon"
end
```

`event_data_text` needs the event id because the same data value can mean different text under different events. Values that were never strings show up as the number itself.

{% hint style="warning" %}
Markers are top-level and **reduce only** — calling them in `process_user` is an upload error. Keep numbers in partials and translate once in `reduce`. The marker prefix `@@kdb/` is reserved, so a literal or param containing it is rejected.
{% endhint %}

***

## Shared functions

A module can hold functions shared across reports, including ones that read the stream — pass the stream in like any argument, under any name. Which parameter is the stream is traced from the call sites at upload. The upload check enforces:

* The stream and the user flow only through direct calls to defined functions — neither can be stored in a table, captured by a closure, reassigned, or passed to an unknown callee.
* One meaning per call position: a parameter that receives the stream in one call and a number in another is rejected, naming both lines.
* Function names are flat globals: the same name in two modules (or colliding with a chain descriptor) is rejected, naming both sources.
* Modules cannot define `process_user` / `reduce` or touch `partial` / `output` — the contract lives in the report.
* Requires may nest (helpers over shared infra); cycles are rejected. A module function a report never calls is simply ignored.

Calls are plain Lua calls the JIT inlines, so helpers cost what inline code costs, and their errors name the module and its own line numbers.

***

## The sandbox

The runtime exposes a focused subset of Lua. Everything you need for analytics works as expected; a few standard libraries are deliberately absent.

### Allowed

* `assert`, `error`, `type`, `ipairs`, `pairs`, `next`, `select`, `rawequal`.
* A `math.*` subset: `floor`, `ceil`, `abs`, `min`, `max`, `sqrt`, `log`, `exp`, `pow`, `fmod`, trig, `deg`, `rad`, `pi`, `huge`.
* Tables, strings (as values), numbers, booleans, `nil`; function definitions, closures, recursion (bounded by stack depth); all control flow (`while`, `for`, `repeat`, `if`).

### Not available

* `io`, `os`, `package`, `module`, `load`, `loadfile`, `loadstring`, `dofile` — no runtime loader (`require` is a compile-time include only).
* `debug`, `ffi`, `jit`; the `string`, `table`, `bit`, `coroutine` library tables — use `#` for length and `ipairs`/`pairs` to iterate.
* `pcall`, `xpcall`, `setmetatable` / `getmetatable`, `rawset` / `rawget`, `setfenv` / `getfenv`.
* `print`, `collectgarbage`, `unpack`, `tostring`, `tonumber`, `goto`.
* `math.random` / `math.randomseed` — the same input data must always give the same output.

### Reserved names

`kdb` is reserved — it appears only as `kdb.<name>` in read position and can't be reassigned or assigned into. Identifiers starting with `kdb_` are reserved for the runtime.

A chain descriptor's name isn't a value — reach the chain through `events[i]:get_<name>()`. Descriptors can't be named `events`, `user`, `params`, `partial`, `output`, `kdb`, `process_user`, or `reduce`; chain fields can't be named `head`, `start_pos`, `end_pos`, `kind`, `count`, or `index`.

`params` is read-only at every depth — writes, shadowing, and writes through aliasing locals are all rejected at upload. Indexing or calling a scalar param (`params.threshold[1]`) is rejected too.

***

## Hard limits

| Limit         | Budget                                                                                                                                              |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Memory        | 64 MiB per script in the map stage, 128 MiB in reduce. Exceeding aborts with a memory error.                                                        |
| Wall clock    | \~200 µs per user × user count in map, 60 s in reduce. Exceeding aborts with a timeout.                                                             |
| Script size   | 16 KiB of source.                                                                                                                                   |
| Params size   | 1 MiB.                                                                                                                                              |
| Table nesting | Any value in `partial` / `output` may nest at most 1024 levels deep. Flat tables of any size (millions of entries) are fine — only depth is capped. |

Exceeding a limit is always an explicit error, never a silent truncation.

***

## Error messages

Every message names what went wrong and, usually, the fix. The ones you're most likely to see:

| Message                                                    | Meaning / fix                                                                                                          |
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `identifiers starting with kdb_ are reserved`              | Don't name variables or functions starting with `kdb_`.                                                                |
| `kdb is a reserved word`                                   | You used `kdb` as a name or assigned to it. Use it only as `kdb.<name>` in read position.                              |
| `goto is not allowed`                                      | Use loops and conditionals instead.                                                                                    |
| `script must define process_user(user, events)`            | Add the required contract function.                                                                                    |
| `lua budget exceeded (...)`                                | Hit the time, memory, or cancellation budget — see [Hard limits](#hard-limits).                                        |
| `event index out of range`                                 | You indexed `events[i]` with `i` outside `[0, events.count)`. Guard `i` with `i < events.count`.                       |
| `chain field mismatch at index N`                          | Read a chain field off an index the getter never confirmed — guard with `local c = ev:get_X(); if c then …`            |
| `unknown chain getter get_X`                               | The chain isn't defined — add `require "game_analytics"` or a `kdb.chain{…}`, or fix the name.                         |
| `no chain descriptor matches this finder`                  | `find_next_X` derives from a defined chain — define `X` or fix the spelling.                                           |
| `chain is already defined: X`                              | Same chain name defined twice — rename or drop one.                                                                    |
| `bind the chain first` / `bind the item group first`       | Chain handles and item groups read through a local: `local c = ev:get_X(); local f = c.from`.                          |
| `the query's <filter> filter removes or alters its events` | The query filters away events a chain reads — adjust the query or the script.                                          |
| `kll:quantile(q): q must be in [0,1]`                      | Quantiles are 0–1 (0.5 = median, 0.99 = p99), not 0–100.                                                               |
| `kll:merge(other): cannot merge a sketch into itself`      | Merge a different sketch; `sk:merge(sk)` is not allowed.                                                               |
| `cannot serialize partial: it holds a value that isn't…`   | `partial` holds a function/thread/cdata. Store only numbers, strings, booleans, nested tables, and `kdb.kll` sketches. |
| `unknown event name "X"`                                   | The string matches no event's display name — check spelling against the platform UI.                                   |
| `ambiguous event name`                                     | Several event ids share this display name — use a numeric id.                                                          |
| `strings don't compare to event ids/data`                  | Wrap the string: `kdb.resolve_event_id` / `kdb.resolve_event_data`, then compare the number.                           |
| `string parameters resolve explicitly`                     | Wrap the param: `kdb.resolve_event_id(params.x)` / `kdb.resolve_event_data(params.x)`.                                 |
| `keep numbers in partials and translate once in reduce`    | `kdb.event_name` / `kdb.event_data_text` are banned in `process_user` — move the call to `reduce`.                     |
| `"@@kdb/" is reserved for output markers`                  | Don't write the marker prefix — produce markers with `kdb.event_name` / `kdb.event_data_text`.                         |
| `used both as an event id and as an event data value`      | One param, one meaning — declare two separate params.                                                                  |
| `cannot trace this back to params`                         | The resolver can't see where the value came from — resolve at the leaf and pass numbers.                               |
| `params is read-only`                                      | The script writes into `params`, shadows it, or writes through an aliasing local — params are fixed for the run.       |
| `scalar query parameter cannot be indexed or called`       | `params.<name>` is a string or number — `params.x.y` / `params.x[i]` can only fail at run time.                        |
| `event id/data parameter must be a number`                 | A boolean or table landed in a numeric finder position — pass a number, or a string through the resolvers.             |

***

## Performance notes

### Don't write `(x or 0)` in the hot loop

`partial.x = (partial.x or 0) + v` inside `process_user` pays a nil-check on every event. Initialize once at the top level (`partial.x = 0` — the top level runs once per shard) and write `partial.x = partial.x + v`. Every partial then carries the field, so `reduce` reads `p.x` without `or 0`. The one exception is a dynamic key you only learn at runtime (`partial.by_campaign[c]`) — there `(partial.by_campaign[c] or 0)` is correct, and only there.

### Avoid in tight loops

Creating tables (`local t = {}` inside the loop), string concatenation (`a .. b`), and growing a table (`t[#t+1] = x`) all allocate.

### Do in reduce, not process\_user

Sorting, building output rows, and formatting — anything that runs once on the final aggregate.

### Prefer finders and skip chain bodies

A finder pays one native call per match; a Lua loop over every event pays one per event. Bound the range whenever the question is windowed.

When you handle a chain, set `i = c.end_pos` to jump past its detail events rather than visiting each one.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.keewano.com/lua-scripting/reference.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
