# Adding your own spans

i9 traces every process it runs. To see inside one (which function, which
phase, which request), your code adds spans of its own. They join the same
trace, under the process that wrote them, and every `i9 trace` verb reads them
like i9's own spans. No SDK or package is needed. In any language, a span is
one line of JSON written to a socket.

## The intake

Inside an i9 VM, every process has `I9_TRACE_SOCK` set to the intake: a unix
socket that takes newline-delimited JSON span records. On a host, `i9 trace
run -- <command>` gives the command and every process it starts the same
intake for the run, and records every process as a span besides; the whole
run is one session (`i9 trace ls --kind sessions` lists it as `trace-run`). Write one record per
line, and as many records per connection as you like. Either keep one
connection open for the life of your program, or open, write and close for
each span. The intake stamps each span with the writing process's pid, uid
and gid, so a span you write can never pass as one i9 measured.

In a macOS guest the same intake is served by the guest agent. `i9 vm exec`
sets `I9_TRACE_SOCK` for the command, and the agent sets it in launchd for
the logged-in user, so an app that user opens (from the Dock, Finder, `open`
or a LaunchAgent) has it too. An app that launched in the moment of login,
before the agent set the variable, does not have it; reopen it. An app in the App Sandbox
cannot reach the socket. Spans from a macOS guest land in the run's trace next
to the guest's own process and log spans; a record with no `trace_id` and no
`parent_id` lands under the run's span.

`TRACEPARENT` (`00-<trace id>-<span id>-01`) names the trace and the process's
own span. Put those two ids in your record and the span lands inside that
process.

## The record

```json
{"name": "myapp.load_index",
 "trace_id": "<32 hex, from TRACEPARENT>",
 "parent_id": "<16 hex: TRACEPARENT's span, or one of your own span ids>",
 "span_id": "<16 hex, optional: give one to parent other spans under it>",
 "start_ns": 1761600000000000000,
 "end_ns":   1761600000250000000,
 "status_ok": true,
 "status_msg": null,
 "attrs": {"rows": 1200, "path": "/data/index.bin", "cached": false}}
```

- `name` is the only required field. Use your own dotted names
  (`myapp.parse`, `build.link`). Names and attribute keys under `i9.` are
  i9's own vocabulary.
- Times are epoch nanoseconds (`CLOCK_REALTIME`). A missing time is the
  moment the record arrives.
- Attribute values are strings, integers or booleans. Keep one type per key:
  a key written as a string in one span and a number in another is two fields
  to the tools the trace exports to.
- To nest spans, give the outer one a `span_id` and set each inner one's
  `parent_id` to it.
- Under `i9 trace run`, a record with no `parent_id` lands under the process
  that wrote it; one that names a parent stays under that span.
- A failed span says why in `status_msg`.
- A record is at most 64 KiB.

## From the command line

```sh
start=$(date +%s%N)
make -j8
i9 trace add-span --name build.make --start-ns "$start" --end-ns "$(date +%s%N)" --attr jobs=8
```

`i9 trace add-span` writes to `$I9_TRACE_SOCK` when an intake listens (a VM,
or a command under `i9 trace run`). Elsewhere it files the span with the trace
this process belongs to. `--status-fail --status-msg <why>` records a failure
and its reason; `--span-id <id>` files a span under an id you already gave out,
such as a root you put in `TRACEPARENT`; `--batch` reads records like the one
above from stdin, one per line, and files them together:

```sh
i9 trace add-span --batch < spans.jsonl
```

## Python

```python
import json, os, socket, time
from contextlib import contextmanager

_tp = os.environ.get("TRACEPARENT", "").split("-")
_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
_sock.connect(os.environ["I9_TRACE_SOCK"])

@contextmanager
def span(name, **attrs):
    rec = {"name": name, "start_ns": time.time_ns(), "attrs": attrs}
    if len(_tp) == 4:
        rec["trace_id"], rec["parent_id"] = _tp[1], _tp[2]
    try:
        yield
    finally:
        rec["end_ns"] = time.time_ns()
        _sock.sendall((json.dumps(rec) + "\n").encode())

with span("myapp.load_index", rows=1200):
    load_index()
```

## Node

```js
const net = require("net");
const tp = (process.env.TRACEPARENT || "").split("-");
const sock = net.createConnection(process.env.I9_TRACE_SOCK);
const nowNs = () => BigInt(Date.now()) * 1000000n + process.hrtime.bigint() % 1000000n;

async function span(name, attrs, fn) {
  const start = nowNs();
  try { return await fn(); } finally {
    const rec = { name, attrs, trace_id: tp[1], parent_id: tp[2] };
    sock.write(JSON.stringify(rec).replace(/}$/,
      `,"start_ns":${start},"end_ns":${nowNs()}}`) + "\n");
  }
}

await span("myapp.fetch", { url }, () => fetch(url));
```

## Go

```go
var tp = strings.Split(os.Getenv("TRACEPARENT"), "-")
var intake, _ = net.Dial("unix", os.Getenv("I9_TRACE_SOCK"))

func span(name string, attrs map[string]any) func() {
	start := time.Now().UnixNano()
	return func() {
		rec := map[string]any{"name": name, "attrs": attrs,
			"start_ns": start, "end_ns": time.Now().UnixNano()}
		if len(tp) == 4 {
			rec["trace_id"], rec["parent_id"] = tp[1], tp[2]
		}
		b, _ := json.Marshal(rec)
		intake.Write(append(b, '\n'))
	}
}

defer span("myapp.solve", map[string]any{"n": n})()
```

## Rust

```rust
use std::{io::Write, os::unix::net::UnixStream, time::SystemTime};

fn now_ns() -> u128 { SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos() }

fn emit(sock: &mut UnixStream, name: &str, start: u128, end: u128) {
    let tp = std::env::var("TRACEPARENT").unwrap_or_default();
    let p: Vec<&str> = tp.split('-').collect();
    let ids = if p.len() == 4 { format!(r#","trace_id":"{}","parent_id":"{}""#, p[1], p[2]) } else { String::new() };
    let rec = String::from("{") + &format!(r#""name":"{name}","start_ns":{start},"end_ns":{end}{ids}"#) + "}";
    let _ = writeln!(sock, "{rec}");
}

let mut sock = UnixStream::connect(std::env::var("I9_TRACE_SOCK").unwrap()).unwrap();
let t0 = now_ns();
solve();
emit(&mut sock, "myapp.solve", t0, now_ns());
```

## C

With the standard headers for stdio, stdlib, string, sys/socket, sys/un and
time included:

```c
static long long now_ns(void) { struct timespec t; clock_gettime(CLOCK_REALTIME, &t); return t.tv_sec * 1000000000LL + t.tv_nsec; }

static FILE *intake_open(void) {
    struct sockaddr_un a = {.sun_family = AF_UNIX};
    strncpy(a.sun_path, getenv("I9_TRACE_SOCK"), sizeof(a.sun_path) - 1);
    int fd = socket(AF_UNIX, SOCK_STREAM, 0);
    return connect(fd, (struct sockaddr *)&a, sizeof(a)) == 0 ? fdopen(fd, "w") : NULL;
}

static void span_emit(FILE *f, const char *name, long long start, long long end) {
    char tid[33] = "", sid[17] = "";
    const char *tp = getenv("TRACEPARENT");
    if (tp && strlen(tp) == 55) { memcpy(tid, tp + 3, 32); memcpy(sid, tp + 36, 16); }
    fprintf(f, "{\"name\":\"%s\",\"trace_id\":\"%s\",\"parent_id\":\"%s\",\"start_ns\":%lld,\"end_ns\":%lld}\n",
            name, tid, sid, start, end);
    fflush(f);
}
```

## Reading them back

Your spans are in the session's trace like any other:

```sh
i9 trace stats --by by-name --session my-vm                 # count and time per span name
i9 trace stats --by slowest --session my-vm                  # your slowest spans among i9's
i9 trace search --session my-vm --where 'name =~ "^myapp\."' # the spans themselves
```
