Metadata-Version: 2.4
Name: fxprofiler
Version: 1.0.1
Summary: Create marker-only performance profiles in the Firefox Profiler.
License-Expression: MPL-2.0
Project-URL: Homepage, https://github.com/gregtatum/fxprofiler-py
Project-URL: Repository, https://github.com/gregtatum/fxprofiler-py
Project-URL: Issues, https://github.com/gregtatum/fxprofiler-py/issues
Project-URL: Changelog, https://github.com/gregtatum/fxprofiler-py/blob/main/CHANGELOG.md
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# fxprofiler

Create marker-only performance profiles in the Firefox Profiler. The [profiling](https://docs.python.org/3/library/profiling.html)
module allows for sampling based profiling, but no markers. Unfortunately it's not possible
yet to do both sampling and markers in Python together. This package is designed for
manually instrumenting python code with deterministic tracing markers or spans.

 * Example [file reads](https://share.firefox.dev/4zhJorl) vai `task example -- walk_source`
 * Example [network profile](https://share.firefox.dev/3WwoNSs) via `task example -- fetch`

## Designing a good marker chart representation

Marker information is a heirarchy that starts with the `category`. This creates a separater
in the Firefox Profiler marker chart, and all markers are grouped in this category.
Next is the marker `name`, which groups a series of markers into the same part of the
graph. Sharing a `name` across markers is better since it reveals useful patterns in how
the markers get drawn in the graph. Finally the `chart_label` is the text that is actually
shown on the marker itself in the marker chart, and should be the most specific piece of
information.

```py
@dataclass
class FetchMarker(Marker):
    type_name = "Fetch"
    # Put this in a Network category.
    category = Category("Network")
    # Pick the URL from the data payload and show it as the label.
    chart_label = "{marker.data.url}"

    # The data payload:

    # Collect the URL as a custom piece of data. Also show it as a URL in the tooltip.
    url: str = marker_field(label="URL", format=MarkerFormat.URL)


# Now actually collect the marker. Notice that name="fetch" will be shared across all
# markers to group them into the same marker layout.
with profile.measure(
    thread, "fetch", FetchMarker(url="https://example.com/api/user", status=200)
):
    # Do the actual work of fetching a user.
    fetch_user()
```

## Building the tooltip

Expanding on the Fetch example, we can collect more information in the tooltip. Set the
`tooltip_label` first for the initial label used when you hover over a marker. Then
add `marker_field` with a format to collect and show more information in the tooltip.

```py
@dataclass
class FetchMarker(Marker):
    type_name = "Fetch"
    category = Category("Network")

    # Combine the URL and Status information in the tooltip label.
    tooltip_label = "Fetch {marker.data.url} - {marker.data.status}"

    # Collect the URL as a custom piece of data. Also show it as a URL in the tooltip.
    url: str = marker_field(label="URL", format=MarkerFormat.URL)
    # For instance 200, 404.
    status: int = marker_field(label="Status", format=MarkerFormat.INTEGER)
    # The size of the fetch, in bytes.
    size: int = marker_field(label="Size", format=MarkerFormat.BYTES)
```

This could be expanded to whatever metadata you wish to collect.

There are many available marker format fields, which have custom display rules in the
profiler, or choose `UNIQUE_STRING` for a custom field type.

 * URL
 * FILE_PATH
 * SANITIZED_STRING
 * STRING
 * UNIQUE_STRING
 * FLOW_ID
 * TERMINATING_FLOW_ID
 * DURATION
 * TIME
 * SECONDS
 * MILLISECONDS
 * MICROSECONDS
 * NANOSECONDS
 * BYTES
 * PERCENTAGE
 * INTEGER
 * DECIMAL
 * HEXADECIMAL
 * PID
 * TID
 * LIST

## Building a profile

In order to add markers, a full profile must be built. The profiles follow a thread and
process model. Even if your system has a different abstraction, you can fit your data
into these groupings. Threads are grouped by pid in the profiler UI. You can create
synthetic PIDs to group threads.

```python
from fxprofiler import Profile, MarkerTiming

profile = Profile(name="My Script", start_time_ms_since_epoch=0.0)
thread = profile.add_thread("Main Thread", pid=1, tid=1, is_main=True)

profile.add_marker(
    thread, "startup", MarkerTiming.instant(0.0), TextMarker(text="App launched")
)
profile.add_marker(
    thread,
    "allocate",
    MarkerTiming.interval(5.0, 42.0),
    AllocationMarker(
        event_name="alloc",
        allocation_size=512_000,
        url="https://example.com/",
        latency_ms=12.3,
    ),
)
```

## Context managers for timing

`measure()` records an interval marker for the duration of the context block.

```python
with profile.measure(thread, "render", TextMarker(text="Rendered frame")):
    render_frame()
```

`thread()` adds a thread that is alive for the duration of the context block.

```python
import threading


def worker(profile):
    with profile.thread("Worker") as thread:
        with profile.measure(thread, "task", TextMarker(text="task")):
            do_work()


threading.Thread(target=worker, args=(profile,)).start()
```

## Interval-start / interval-end pairs

If markers involve a duration, the API supports adding them with two different markers.

```python
profile.add_marker(
    thread, "fetch", MarkerTiming.interval_start(2.0), TextMarker(text="fetch started")
)
# ... later, possibly after the end time wasn't known yet when the marker started ...
profile.add_marker(
    thread, "fetch", MarkerTiming.interval_end(30.0), TextMarker(text="fetch finished")
)
```

## Writing and opening a profile

A profile can be saved to disk:

```python
profile.write_json("profile.json")
```

Or served directly instead:

```python
from fxprofiler import show

server = show(profile)
input("Press Enter to stop serving...\n")
server.shutdown()
```

## Working with colors

First off, please be careful using colors. They can be over-used and not accessible. It's
preferable to encode your chart meaning in other ways, but the profiler does support it.

```py
@dataclass
class ColorMarker(Marker):
    type_name = "Color"
    chart_label = "{marker.data.color}"
    # Points at the "color" field below, so each marker's rectangle is drawn
    # using whatever GraphColor is stored there.
    color_field = "color"

    color: str = marker_field(label="Color", format=MarkerFormat.STRING)


profile.add_marker(
    thread,
    "red",
    MarkerTiming.interval(0.0, 10.0),
    ColorMarker(color=GraphColor.RED),
)
```

Supported colors are:

 * `BLUE`
 * `GREEN`
 * `GREY`
 * `INK`
 * `MAGENTA`
 * `ORANGE`
 * `PURPLE`
 * `RED`
 * `TEAL`
 * `YELLOW`

See `task example -- colors` for [an example](https://share.firefox.dev/48fZh6q).

## Drawing a graph from markers

Set `graphs` to give a marker its own graph track in the timeline. Every distinct marker
name sharing that type gets its own track, labeled with the name, drawn from whatever
numeric field `graphs` points at. See [https://share.firefox.dev/4zhJorl](https://share.firefox.dev/4zhJorl)
for an example.

```py
@dataclass
class BytesPerFileMarker(Marker):
    type_name = "BytesPerFile"
    graphs = (
        MarkerGraph(key="value", type=MarkerGraphType.BAR, color=GraphColor.ORANGE),
    )

    value: int = marker_field(label="Bytes", format=MarkerFormat.BYTES)


profile.add_marker(
    thread,
    "Bytes Per File",
    MarkerTiming.instant(12.0),
    BytesPerFileMarker(value=4096),
)
```

Supported graph types are:

 * `LINE` - a continuous line, good for cumulative or slowly changing values.
 * `LINE_FILLED` - a continuous line with the area beneath it filled in.
 * `BAR` - a vertical bar per marker, good for bursty or per-event values.

See `task example -- walk_source` for an example that uses both: cumulative line
graphs alongside per-event bar graphs, built from the same real file reads.

## Examples

Some examples are present in `examples/` and runnable locally:

```sh
task example -- markers
```

## Development

All of the tasks can be run through [Taskfile](https://taskfile.dev/).

## Releasing

Describe the release under `## Unreleased` in `CHANGELOG.md`, then run:

```sh
task publish -- patch   # or minor / major
```
