Skip to content

Python Annotation API

1
import hapti

API for naming specific ranges or points in time in code so that they appear in the trace.

Function Signature Notes
annotate (message: str) -> ContextManager[None] Context manager. Opens a Range on entry and closes it on exit, and closes it safely even if an exception is raised in the block
range_push (message: str) -> int Opens a new Range on the Range stack of the calling thread. Returns the nesting depth of the new Range (starting at 0)
range_pop () -> int Closes the most recently pushed Range. Returns the depth of the closed Range, or -1 if the stack is empty
range_start (message: str) -> int Opens an independent Range unrelated to the stack. Returns a handle (int) valid across the process
range_stop (id: int) -> None Closes a Range created with range_start() by its handle. Invalid handles are safely ignored
mark (message: str) -> None Records an instantaneous event (a point in time, not a Range)

Keep annotations in production code

Annotations are recorded in the trace only when the program runs under the haprof launcher. When it runs in a normal environment without haprof, the import and the related function calls complete without error but record nothing. It is therefore safe to keep annotation code in production code.


Example

annotate

Wraps one block in a range.

Example
1
2
3
4
import hapti

with hapti.annotate("decode"):
    out = model.step()

range_push

Opens a range that does not fit a block. Always close it with range_pop on the same thread.

Example
1
2
3
4
5
6
7
import hapti

depth = hapti.range_push("decode")   # 0 if no outer range is open
try:
    out = model.step()
finally:
    hapti.range_pop()

range_pop

Closes the most recently opened range. The return value lets you check the push/pop balance.

Example
1
2
3
4
5
6
7
import hapti

hapti.range_push("outer")
hapti.range_push("inner")
assert hapti.range_pop() == 1        # inner
assert hapti.range_pop() == 0        # outer
assert hapti.range_pop() == -1       # nothing to close

range_start

Opens a range independent of the stack. Ranges may overlap and may cross function and thread boundaries.

Example
1
2
3
4
5
import hapti

handle = hapti.range_start("request-42")
...                                  # may overlap other ranges
hapti.range_stop(handle)

range_stop

Closes a range with the handle returned by range_start.

Example
1
2
3
4
5
6
import hapti

a = hapti.range_start("request-1")
b = hapti.range_start("request-2")
hapti.range_stop(a)                  # can be closed in any order
hapti.range_stop(b)

mark

Records a point in time with no duration.

Example
1
2
3
import hapti

hapti.mark("first token")