> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bitfab.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Go subtree tracing

> Capture first-party Go calls from one root with Trace and configure discovered calls with Node.

`Client.Trace` records a root and the first-party functions it calls.
Compile or run your application with `bitfab-instrument` to enable automatic discovery.
`Client.Node` configures a discovered function.

```bash theme={null}
go install github.com/Project-White-Rabbit/bitfab-go/cmd/bitfab-instrument@latest
bitfab-instrument run ./cmd/app
# Or build an instrumented executable or run instrumented tests.
bitfab-instrument build -o app ./cmd/app
bitfab-instrument test ./...
```

The command reads the current module and uses a temporary Go source overlay.
Your source files stay unchanged.
The command respects the requested packages or files and build flags such as `-tags`, `-race`, `-mod`, `-modfile`, and `-C`.
Run and build commands skip unrelated tests.
Program and test arguments pass through to Go unchanged.
Explicit `-overlay` files are composed with the generated overlay.
Pass overlays as command arguments instead of `GOFLAGS=-overlay`, which the instrumenter rejects.
The compiled executable includes instrumentation and needs no separate tracing process.
Ordinary builds still execute `Trace` roots but do not discover descendants.

```go theme={null}
func answer(ctx context.Context) (any, error) {
    return generateAnswer(ctx, "What shipped today?")
}

client.Node(generateAnswer, bitfab.NodeOptions{Name: "generateAnswer", Type: "llm"})
result, err := client.Trace(ctx, "answer", answer, bitfab.TraceOptions{})
client.FlushTraces(5 * time.Second)
```

## Trace

```go theme={null}
func (c *Client) Trace(
    ctx context.Context,
    traceFunctionKey string,
    fn bitfab.SpanFunc,
    options bitfab.TraceOptions,
) (any, error)
```

| Option                | Type                   | Default       | Behavior                                                                                                             |
| --------------------- | ---------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------- |
| `Name`                | `string`               | Function name | Root span name. Anonymous callbacks use the trace function key.                                                      |
| `Type`                | `string`               | `"custom"`    | Root span type.                                                                                                      |
| `Input`               | `[]any`                | Omitted       | Root arguments to record. Descendant arguments are captured automatically. Context and method receivers are omitted. |
| `TestRunID`           | `string`               | Inherited     | Associates the root with a test run.                                                                                 |
| `MaxDepth`            | `*int`                 | `30`          | Maximum recorded descendant levels. A pointer to zero records only the root.                                         |
| `MaxSpans`            | `*int`                 | `500`         | Maximum recorded descendants. The root does not consume this budget.                                                 |
| `Exclude`             | `[]string`             | Empty         | Simple or qualified function names to omit. Shell-style patterns also match qualified names.                         |
| `IncludeWrappers`     | `bool`                 | `false`       | Includes functions whose only parameter is a variadic argument. Explicitly configured nodes are always considered.   |
| `MockOnReplayDefault` | `bool`                 | `false`       | Marks discovered descendants for the replay `marked` mock strategy.                                                  |
| `CaptureWhen`         | `bitfab.CaptureWhen`   | Always        | `CaptureWhenNested` records only beneath another automatic trace.                                                    |
| `Finalize`            | `bitfab.SpanFinalizer` | None          | Changes the recorded root output after the function returns.                                                         |

Negative limits return an error before running the function.
Hitting a limit marks the trace's `bitfabAutoTrace` metadata as truncated.
Excluded nodes do not consume the budget.
Their children attach to the nearest recorded parent.

Nested `Trace` calls create independent traces and mirrored nodes in their enclosing traces.
The inner root records `enclosing_trace_id`, `enclosing_span_id`, and `enclosing_trace_function_key` in `span_data`.
Its enclosing copy records `nested_trace_id`, `nested_root_span_id`, and `nested_trace_function_key`.
Replay and seed keep nested calls in the item-owned trace.

## Node

```go theme={null}
func (c *Client) Node(fn any, options bitfab.NodeOptions) error
```

Pass a function, a bound method, or its qualified Go symbol name.
`Node` configures future calls without replacing the function.
Combining `Capture=false` with `MockOnReplay=true` returns an error.
It creates no independent trace or replay boundary.

| Option         | Type                   | Default                  | Behavior                                                       |
| -------------- | ---------------------- | ------------------------ | -------------------------------------------------------------- |
| `Name`         | `string`               | Discovered function name | Recorded span name.                                            |
| `Type`         | `string`               | `"custom"`               | Recorded span type. Unconfigured descendants use `"function"`. |
| `TestRunID`    | `string`               | Inherited                | Test run for this node's span.                                 |
| `Capture`      | `*bool`                | `true`                   | A pointer to false omits the node and reparents its children.  |
| `MockOnReplay` | `*bool`                | Trace default            | Overrides `MockOnReplayDefault`, including an explicit false.  |
| `Finalize`     | `bitfab.SpanFinalizer` | None                     | Transforms this call's recorded output.                        |

## Finalization and concurrency

```go theme={null}
client.Node(generateAnswer, bitfab.NodeOptions{
    Finalize: func(output any) (any, error) {
        return redactSecrets(output), nil
    },
})
```

Finalizers run asynchronously once per call, including calls mirrored into multiple traces.
The original result returns to application code.
Mocked outputs skip finalization because the replacement is already the recorded output.
A finalizer error or panic is recorded on the span.
`FlushTraces` and `Close` wait for finalizers within their existing total timeout.
They return false when that deadline expires.

Generated goroutine launches preserve argument evaluation in the launching goroutine.
Captured children inherit parentage from launch time.
Named return values are recorded after application defers run.
Errors and panics retain their normal application behavior.
Work still running when its owning root returns is recorded as incomplete.
Its late completion does not send a duplicate span or run a late finalizer.

`Span` and `Start` cannot enter an automatic subtree.
`Trace` and configured nodes cannot enter an opt-in span stack.
These combinations produce `MixedTracingError`.
`Start` and generated node calls panic with that error because their function signatures have no error return.

## Instrumentation scope

The transform captures named functions and methods in the current module, including generic functions and methods.
It also instruments first-party test files.
It skips generated files, the SDK, dependencies, and functions marked `//bitfab:ignore`.
Anonymous function bodies remain transparent while named functions called beneath them are discovered.
Go functions in first-party cgo packages are supported.
The transform uses the Go compiler’s generated type information while preserving the original C preamble.
Native function bodies remain outside Go discovery.

The runtime uses Go's public stack formatter to associate contextless calls with their goroutine.
If the formatter cannot identify a goroutine, that call executes without capture.
The inactive instrumentation path does not inspect stacks.
