# Run trace


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## The tracer

`trace_cell(code, ns)` compiles `code`, runs it in the namespace `ns`,
and returns a dict. It keeps these limits:

- `keep`: of one line, the first `keep` and the last `keep` runs are
  kept. The runs in between are a counter (an event named `skip`).
- `max_seen`: stop tracing after this many events, and `secs`: stop
  after this many seconds. The cell goes on running without the hook.
- `max_events`: the most events in the answer.
- `max_repr`: the longest value text.

Each event is `{step, line, event, depth, locals_changed}`. `event` is
`line`, `call`, `return` or `exception`. For a `line` event,
`locals_changed` holds what the names became *after* that line ran, so
one row of the table is one line and its effect.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/kunda/blob/main/kunda/trace.py#L14"
target="_blank" style="float:right; font-size:smaller">source</a>

### trace_cell

``` python
def trace_cell(
    code, ns, watch:NoneType=None, max_events:int=2000, max_repr:int=200, secs:float=5.0, keep:int=50,
    max_seen:int=200000, fn:NoneType=None
):
```

*Run `code` in `ns` under a bounded line tracer and return
`{events, error, seen, truncated, reason, source}`.*

A binary search with the classic bug (`low > high` never stops, `mid` is
stuck) is the best test. The trace shows `low`, `high` and `mid` for
every pass.

``` python
ns = {}
src = """def bsearch(a, x):
    low, high = 0, len(a) - 1
    while low <= high:
        mid = (low + high) // 2
        if a[mid] < x: low = mid + 1
        elif a[mid] > x: high = mid - 1
        else: return mid
    return -1
r = bsearch([1, 3, 5, 7, 9, 11], 7)
r"""
out, res, err, tb = trace_cell(src, ns)
test_eq(res, 3)
test_eq(err, None)
rows = [e for e in out['events'] if e['event'] == 'line' and e['line'] == 4]
test_eq([e['locals_changed'] for e in rows], [{'mid': '2'}, {'mid': '4'}, {'mid': '3'}])
test_eq([e['locals_changed'] for e in out['events'] if e['line'] == 5], [{'low': '3'}, {}, {}])
test_eq([e['locals_changed'] for e in out['events'] if e['line'] == 6 and e['event'] == 'line'], [{'high': '3'}, {}])
```

A loop of 10 000 passes keeps the first 50 and the last 50 passes of
each line, and a `skip` event with the count between.

``` python
out, res, err, tb = trace_cell("total = 0\nfor i in range(10000):\n    total += i\ntotal", {})
test_eq(res, 49995000)
body = [e for e in out['events'] if e['line'] == 3 and e['event'] == 'line']
test_eq(len(body), 100)
sk = [e for e in out['events'] if e['event'] == 'skip' and e['line'] == 3]
test_eq(sk[0]['count'], 9900)
test_eq(body[-1]['locals_changed'], {'total': '49995000'})
```

An exception keeps the events up to the error, and the error comes back
to the caller.

``` python
out, res, err, tb = trace_cell("x = 1\ny = x / 0\nz = 3", {})
test_eq(type(err), ZeroDivisionError)
test_eq([e['locals_changed'] for e in out['events'] if e['line'] == 1 and e['event'] == 'line'], [{'x': '1'}])
assert 'exception' in [e['event'] for e in out['events']]
assert not [e for e in out['events'] if e['line'] == 3]
assert out['error'].startswith('ZeroDivisionError')
```

## Running it in a kernel

`run_traced` is a method of every kernel. It sends the tracer as text,
runs the cell in the user’s namespace, and gets the events back in a
`display_data` message with a private mimetype. The person’s own output
is not changed. If the cell raises, the error is reported as usual.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/kunda/blob/main/kunda/trace.py#L161"
target="_blank" style="float:right; font-size:smaller">source</a>

### MessageRouter.run_traced

``` python
async def run_traced(
    code, watch:NoneType=None, max_events:int=2000, max_repr:int=200, secs:float=5.0, keep:int=50,
    timeout:NoneType=None, on_output:NoneType=None, **kw
):
```

*Run `code` like `execute` and return
`AttrDict(ok, error, outputs, execution_count, events, truncated, reason, seen, secs)`.
`events` holds one dict per traced line, call, return or exception.*

The real-kernel tests are in `tests/test_trace.py`; they start an
ipykernel and run the cells below.
