Metadata-Version: 2.5
Name: fictura
Version: 0.4.0
Summary: Backend error capture, logs and tracing for FastAPI / any ASGI app — grouped by cause, ranked by users affected, reported to Fictura.
Project-URL: Homepage, https://fictura.co
Project-URL: Source, https://github.com/Apex-Byte-Technologies/fictura_backend
Project-URL: Issues, https://github.com/Apex-Byte-Technologies/fictura_backend/issues
Author: Apex Byte Technologies
License: MIT
Keywords: asgi,error-tracking,fastapi,fictura,monitoring,observability
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown

# fictura — backend error capture, logs and tracing

One stdlib-only file that reports your FastAPI (or any ASGI) backend's errors
to Fictura's Issues page, grouped by cause and ranked by users affected, sends
your logs to the Logs page, and traces every request: route, status, user,
outgoing HTTP, Gemini, MCP and subprocess calls, exported as OpenTelemetry
(OTLP/HTTP JSON).

## Install

```bash
pip install fictura==0.4.0
```

Pin it in `requirements.txt`. The package has **no dependencies**.

Prefer to vendor? The same file is served by the backend:

```bash
curl -o app/fictura.py https://api.fictura.co/sdk/fictura.py
```

Check a setup with `FICTURA_API_KEY=gk_... FICTURA_API_BASE=... python -m fictura`.
It sends four test events, a span and a log line.

## Wire it (2 lines)

```python
import fictura
from fastapi import FastAPI

fictura.init(service_name="my-api")
app = FastAPI()
fictura.instrument(app)
```

Call `init()` before the app serves its first request. It reads the rest from
the environment:

| Setting | Argument | Environment | Default |
|---|---|---|---|
| Ingest key (`gk_...`, Dashboard → Setup) | `api_key` | `FICTURA_API_KEY` | none → disabled |
| API host | `api_base` | `FICTURA_API_BASE` | `https://api.fictura.co` |
| Release | `release` | `FICTURA_RELEASE`, else `RAILWAY_GIT_COMMIT_SHA` (first 12) | none |
| Environment | `environment` | `FICTURA_ENVIRONMENT`, else `RAILWAY_ENVIRONMENT_NAME` | `production` |
| Service name (traces, logs) | `service_name` | `FICTURA_SERVICE_NAME` | `python-app` |

It is a no-op without a key, and under pytest unless you pass `enabled=True`.
Every other option is in [Options](#options).

## What reaches the Issues page

1. **Crashes.** Exceptions that escape the app, with status 500. They are
   re-raised, so your error handling is untouched.
2. **Handled 5xx.** `raise HTTPException(500, ...)` becomes a response in an
   exception handler and never reaches a middleware as an exception, so the
   middleware watches the response status instead (`mechanism: "http_5xx"`).
   If the request already reported the real error (usually a `logger.error`
   just before the `raise`), that event stands and no second one is sent.
3. **Errors you already log.** Every `logger.error(...)` becomes an Issue,
   with the full traceback even from a bare `logger.error(f"failed: {e}")`:
   handlers run on the calling thread, where the exception is still live.
   A log line with no exception in flight groups on its call site.
4. **Uncaught exceptions** at top level (`sys.excepthook`), in threads
   (`threading.excepthook`), and those Python can only print, as in `__del__`
   (`sys.unraisablehook`). The previous hooks still run.
5. **Thread pools and background work:**

   ```python
   executor.submit(fictura.wrap(work), item)   # captures, and carries the trace/route/user
   with fictura.capture_errors():              # captures, then re-raises
       ...
   ```
6. **Explicit:**

   ```python
   fictura.capture_exception()                 # the exception being handled, or pass one
   fictura.capture_message("quota low", level="warning")
   fictura.capture_event({"message": "built by hand", "exc_type": "Import"})
   ```

   All three take `level`, `tags`, `extra`, `contexts`, `fingerprint` and `user`.

One exception is one Issue: logging it and re-raising it, or wrapping it with
`raise X from e`, does not create a second one.

## What is on an event

- **Where:** the route **template** with router prefixes
  (`/api/v1/items/{item_id}`, never the raw URL; `<unmatched>` when no route
  matched), method, status, the user id (read after your auth dependency ran),
  release, environment, `server_name`, `event_id`, and `trace_id`/`span_id`.
- **Frames**, newest first, with the source lines around each and its local
  variables as short `repr`s: at most 30 a frame and 200 characters a value, on
  your own code's frames and the newest 5. The frames of what caused the
  exception follow its own, and `causes` lists the chain. The raw `stack` is
  sent too, in Python's format. Grouping reads that, so frames never change
  how Issues group.
- **The request:** URL, full query string, method, filtered headers, and JSON or
  form bodies. See [Privacy](#privacy).
- **Tags:** `runtime`, `server_name`, `handled`, `mechanism`, `level`,
  `transaction`, `url`, `logger`, `browser`, `client_os`, `device` (from the
  `User-Agent`: `HouseAI/81 CFNetwork/...` is browser HouseAI 81 on iOS),
  `geo.country` (from Cloudflare's `cf-ipcountry`), and yours.
- **Contexts:** `runtime`, `browser`, `client_os`, `device`, `trace`, `user`,
  `extra` (your extras and `sys.argv`), `modules` (installed packages), and yours.
- **Breadcrumbs:** the last 100 things that happened in that request, INFO+ log
  lines and outgoing HTTP calls (method, URL, query, status, reason) and your
  `add_breadcrumb` calls, each with `type`, `level` and `data`.

Request body capture copies bytes as the app reads them, so the app gets exactly
what the server sent. A body the app never read is not on the event. An
`HTTPException(500)` has frames as long as `init()` ran before the app's first
request.

## Scopes

```python
fictura.set_tag("plan", "pro")
fictura.set_tags({"region": "eu", "tier": 2})
fictura.set_context("gpu", {"name": "t4"})
fictura.set_extra("job_id", 42)
fictura.set_user({"id": "u1", "email": "a@b.co"})      # only what you pass is sent
fictura.add_breadcrumb(category="payment", message="charged", level="info", type="transaction", data={"cents": 5})

with fictura.new_scope() as scope:                     # for this block only
    scope.set_tag("handled_error", "insufficient_credits")
    scope.set_level("warning")
    scope.fingerprint = ["{{ default }}", "credits"]
    scope.add_event_processor(lambda event, hint: event)
    fictura.capture_message("Hit credit limit")

fictura.add_global_event_processor(lambda event, hint: event)
```

Three scopes are active at once, applied in this order, the last one winning:
`get_global_scope()` (the whole process), `get_isolation_scope()` (one per
request) and `get_current_scope()` (`new_scope()` forks it). Module-level
`set_tag` and friends write to the isolation scope, so inside `new_scope()` set
things on the scope it gives you. Outside a request, `isolation_scope()` gives a
job the same fresh start a request gets.

Requests can't see each other's scope, whether async or in the thread pool.
Threads inherit a copy of the scope that started them, along with its route,
user and current span. What a thread sets stays in the thread. Work given to a
`ThreadPoolExecutor` inherits the scope and route too, and its events land in the
request's trace, but its spans start a new trace unless you use `fictura.wrap()`.
`propagate_scope=False` turns off the inheritance.

## Logs

With `enable_logs=True` (the `init()` default), log records at `logs_level`
(default `logging.INFO`) and up go to the Logs page. Each line carries the trace,
route, user, release, environment, logger, template and SDK name. It sees loggers
with `propagate=False`, and a later `logging.basicConfig(force=True)` can't detach
it. A logger's own level still applies: a logger left at `WARNING` sends no `INFO`.

```python
logger.info("job %s done", job_id, extra={"shard": 3})    # stdlib, as you already do

fictura.logger.info("user {id} bought {item}", id=7, item="lamp", attributes={"plan": "pro"})
```

`fictura.logger` has `trace`, `debug`, `info`, `warning`, `error` and `fatal`. The
kwargs fill the placeholders and become attributes. Its lines never become
Issues, and they ignore `logs_level`. `enable_logs=False` turns both off.

`before_send_log(line, hint)` edits a line or drops it by returning `None`. A line
is the JSON that gets sent: `{ts, level, message, logger, template, trace_id,
span_id, route, method, user_id, release, environment, service, server_name,
attributes}`.

Lines go to `{api_base}/api/v1/logs` in batches of up to 500, from their own queue
of 5,000 (oldest dropped first), so a log flood can't push out an error. The
SDK's own logger is never sent, and nothing logged during delivery or inside your
hooks is captured, so it can't loop. `urllib3` and access logs (which carry the
client's IP) are skipped.

## Tracing

With `traces_sample_rate` > 0 (the `init()` default is 1.0) or a `traces_sampler`:

- A **server span** per request named `GET /api/v1/items/{item_id}` with
  `http.request.method`, `http.route`, `http.response.status_code`, `url.full`,
  `url.query`, `url.path`, `enduser.id` and `fictura.session_id` (from the app's
  `X-Fictura-Session-Id` header). An incoming W3C `traceparent` is continued;
  a `sentry-trace` header is the fallback.
- **Client spans** for `httpx` (sync and async) and `requests`, with
  `http.request.method`, `url.full` (no query) and `url.query` (filtered). Calls
  over 100 ms also say which line of your code made them: `code.filepath`,
  `code.lineno`, `code.function`. `traceparent` is sent only to URLs matching
  `trace_propagation_targets` (regexes; default: none).
- **Gemini spans** (`google-genai`): `gen_ai.generate_content` /
  `gen_ai.generate_images` with the model and token counts. Prompt and
  response text are never recorded.
- **MCP spans** (`mcp`, SDK 1.x and 2.x): `tools/call <name>`, `prompts/get <name>`
  and `resources/read <uri>`, op `mcp.server`, with `mcp.method.name`,
  `mcp.tool.name`, `mcp.transport`, `mcp.request_id` and `mcp.session_id`.
  Arguments and results are never recorded.
- **Subprocess spans** under the current span: the command (scrubbed), `wait` and
  `communicate`.
- **Your own spans:**

  ```python
  with fictura.start_span(op="db.query", name="load rooms") as span:
      span.set_data("rows", 3)
      span.set_status("ok")
      child = span.start_child(op="parse", name="decode")
      child.finish()

  with fictura.start_transaction(op="task", name="nightly sync"):   # always a new trace
      ...

  @fictura.trace(op="service", name="score candidates", attributes={"v": 2})
  async def score(...): ...

  fictura.update_current_span(name="renamed", attributes={"k": "v"})
  fictura.get_current_span()

  with fictura.span("resize image", width=1024):                    # the 0.3 API still works
      ...
  ```
- Sampling is decided once per trace. `traces_sampler(context)` decides first,
  returning a bool or a rate, and sees `transaction_context`, `parent_sampled` and,
  for requests, `asgi_scope`. Then a parent's sampled flag, then `traces_sample_rate`.

The span's `op` is sent as the `fictura.op` attribute. Spans go to
`{api_base}/v1/traces` as OTLP/HTTP JSON on the same background worker as errors
(separate queue, so a span flood never evicts an error).

## Options

Hooks take `(value, hint)`, as Sentry's do, or just `(value)`. `hint` holds
`exc_info` and, for anything from logging, `log_record`. A hook that raises drops
what it was given, so a broken filter can't leak what it meant to filter.

| Option | Default | What it does |
|---|---|---|
| `sample_rate` | `1.0` | Share of error events sent |
| `error_sampler(event, hint)` | none | Replaces `sample_rate`. Returns a bool or a rate |
| `ignore_errors` | `[]` | Classes (subclasses match) or names (`"KeyError"`, `"app.errors.Busy"`) |
| `before_send(event, hint)` | none | Edit an event, or drop it with `None` |
| `before_breadcrumb(crumb, hint)` | none | The same for a breadcrumb |
| `max_breadcrumbs` | `100` | Kept per request |
| `attach_stacktrace` | `False` | Adds `frames` to messages and log events with no exception. Grouping stays as it was |
| `max_value_length` | none | Cuts messages, variable values, breadcrumbs and extras to this. Without it: 500, 200, 300, 8 KB |
| `dist` | none | Sent with each event and log line |
| `server_name` | hostname | |
| `shutdown_timeout` | `2` | Seconds to deliver what is queued at exit |
| `include_source_context` | `True` | The 5 lines above and below each frame |
| `include_local_variables`, `capture_locals` | `True` | Either one `False` turns variables off |
| `max_stack_frames` | `100` | Keeps the newest |
| `add_full_stack` | `False` | Adds the callers above where the exception was caught |
| `in_app_include`, `in_app_exclude` | `[]` | Module prefixes. Include wins |
| `project_root` | `os.getcwd()` | Frames under it are your code, except `site-packages` |
| `custom_repr(obj)` | none | A string to show for `obj`, or `None` for the default |
| `max_request_body_size` | `"medium"` | `never`, `small` (1,000 bytes), `medium` (10,000), `always` |
| `capture_body` | `True` | `False` sends no bodies |
| `event_scrubber` | `EventScrubber()` | See [Privacy](#privacy) |
| `enable_logs`, `logs_level`, `before_send_log` | `True`, `logging.INFO`, none | See [Logs](#logs) |
| `traces_sample_rate`, `traces_sampler` | `1.0`, none | `None` and no sampler turn tracing off |
| `before_send_transaction(event, hint)` | none | Sees a whole trace when its root ends: rename it, remove spans, edit their `data`, or drop it with `None` |
| `trace_ignore_status_codes` | none | Requests answered with these aren't traced, children included |
| `functions_to_trace` | `[]` | `[{"qualified_name": "app.jobs.run"}]` traces it without touching its code |
| `trace_propagation_targets` | `[]` | See [Tracing](#tracing) |
| `get_user_id(scope)` | `request.state.user["id"]` | Also `.user.id` and `.user_id`. `set_user` wins |
| `capture_logs`, `log_level` | `True`, `logging.ERROR` | Log records at this level become Issues |
| `breadcrumbs`, `capture_5xx`, `request_sessions` | `True` | Turn each off |
| `instrument_http`, `instrument_genai`, `instrument_mcp`, `instrument_subprocess` | `True` | Turn each off |
| `install_excepthooks`, `install_signal_handler`, `propagate_scope` | `True` | Turn each off |

The last two hooks on a trace buffer its spans until the root ends, at most 1,000
per trace. Without them, spans go out as they end.

## Release health for backends (request sessions)

Each request through the middleware counts as a session: **crashed** when an
exception escaped the app, **errored** on a 5xx response or an error-level
event reported during it, **ok** otherwise (a 4xx is ok). Counts are kept per
minute and sent as each minute closes, and on `flush()`, to
`{api_base}/api/v1/sessions/aggregates` with the release and environment. The
Releases page shows a crash-free and an error-free request rate per release.
`request_sessions=False` turns it off.

Record deploys from CI with `npx fictura-sdk deploy --release $RELEASE` (from
`@fictura/sdk`) to list them on the Releases page and get suspect commits on
issues. Use the same release string the SDK reports (`FICTURA_RELEASE`, else
the first 12 characters of `RAILWAY_GIT_COMMIT_SHA`).

## Privacy

**Never sent:** cookies, `Authorization` headers, the client's IP address
(`x-forwarded-for`, `x-real-ip`, `cf-connecting-ip` and the like are dropped, and the
socket address is never read), uploaded files (multipart bodies are not read at all)
and `ip_address` from `set_user`.

**Filtered by key.** The value of a sensitive key becomes `[Filtered]` in local
variables, headers, bodies, query strings, tags, contexts, breadcrumb data and log
attributes: password, secret, token, api_key, auth, authorization, cookie, session,
csrf, jwt, credit_card, card_number, cvv, ssn, private_key, credentials, email and
similar. Keys match on whole words, so `access_token` and `X-Api-Key` are filtered and
`author` and `max_tokens` are not. An email address in a local variable is filtered in
any shape. One you pass to `set_user` is sent, since you chose to.

**Filtered by pattern.** Every string, messages and source lines included, has
secrets replaced wherever they appear: JWTs, `Bearer`/`Basic` credentials,
`key=value` secrets, cookie headers, passwords in URLs, provider keys
(`sk_`/`pk_`/`fk_`/`gk_`, `sk-`, `AKIA`, `AIza`, `ghp_`, `xox*`) and Luhn-valid
card numbers. This runs after `before_send`, so whatever it returns is scrubbed too.

**Your controls:**

```python
fictura.init(
    capture_locals=False,                                  # no local variables
    capture_body=False,                                    # no request bodies
    event_scrubber=fictura.EventScrubber(denylist=["password", "api_key", "room_code"]),
)
```

`event_scrubber` replaces the key filter: pass an `EventScrubber` with your own
list, an object with `scrub_event(event)`, or a function `event -> event`. If it
raises, the event is dropped. The pattern filter always runs.

Bodies over the size limit are dropped whole, with `data_truncated: true`, never
cut in half. The server keeps at most 16 KB of a request, so the SDK drops a body
that would go over it, whatever `max_request_body_size` says.

## Delivery guarantees

- Never raises into your app and never blocks a response: one daemon thread,
  bounded queues (200 errors, 2000 spans, 5000 log lines, 1440 session minutes),
  oldest dropped first, 2s timeout. Scrubbing, sizing and reading the package list
  happen on that thread.
- Batches of at most 20 errors and under 900 KB. An event too big for one sheds
  its body, then variables, source lines, packages, breadcrumbs and so on, until
  it fits. One that can't be serialized is dropped alone, not with its batch.
- `fictura.flush(timeout=2)` waits for queued **and** in-flight batches; it runs
  at exit and on SIGTERM, after which the previous SIGTERM handler runs (the
  signal is never swallowed). On Railway, set `RAILWAY_DEPLOYMENT_DRAINING_SECONDS`
  ≥ 5 so there is time to flush.
- 429 and 503 park that queue until `Retry-After` passes and keep the batch
  (same `event_id`s), on every queue. Other 5xx and network errors get one retry
  after a short backoff, then the batch is dropped. Other 4xx are dropped.

## Moving from Sentry

Most calls keep their name, so `fictura.capture_exception(e)`,
`fictura.set_tag(...)`, `with fictura.push_scope() as scope:`,
`@fictura.trace` and the hooks above port as they are. The differences:

| Sentry | Fictura |
|---|---|
| `event` in hooks is Sentry's shape | It is the shape of `POST /api/v1/errors`: `exc_type`, `message`, `frames`, `request`, `tags`, `contexts`, ... |
| `log["body"]`, `log["severity_text"]` in `before_send_log` | `line["message"]`, `line["level"]` |
| `enable_logs` defaults to off | On, from `init()` |
| `sentry_sdk.logger` runs without `enable_logs` | `enable_logs=False` also stops `fictura.logger` |
| `EventScrubber` keys match exactly | They match on words, and `email` is on the list, which filters more |
| `Authorization` header sent as `[Filtered]` | Not sent at all |
| `event_scrubber` runs before `before_send`; a value added by `before_send` is not scrubbed | It runs after, on everything |
| `ThreadPoolExecutor` work is under the caller's span | Use `fictura.wrap()` for that. Its events still land in the trace |
| Reads the request body itself | Copies what the app reads, so a body the app never read isn't on the event |
| `http.client` / `urllib` spans | Only `httpx` and `requests` |
| `subprocess` passes `SUBPROCESS_SENTRY_TRACE` in the child's environment | The environment is left alone |

## Upgrading from 0.3

Nothing to change. New on every event: frames, the request, tags, contexts and up
to 100 breadcrumbs (20 before). Fingerprints don't change, since grouping still
reads `stack`.

Two things you may want to look at. `enable_logs` is on, so your INFO+ lines now
reach the Logs page; pass `enable_logs=False` to keep them off. And log capture no
longer adds a handler to the root logger, so a process with no logging set up at
all now prints warnings to stderr, as Python does by default.

## Upgrading from 0.2

The 0.2 constructor still works, and `GrowthAgent` is still an alias:

```python
agent = Fictura(api_base, api_key, release, environment, get_user_id)
app.add_middleware(agent.middleware)
```

What changes with no code change: the route is the real template (0.2 sent
the raw path), user and status are read after the app ran (0.2 sent no user),
handled 5xx are reported, events are flushed at exit, and secrets are
scrubbed. A bare constructor does not trace, sends no log lines and installs no
global hooks; `fictura.init()` does all three.

## Development

```bash
pip install pytest fastapi httpx requests            # add mcp and python-multipart for those tests
python scripts/check_version.py        # pyproject version == fictura.__version__
python -m pytest tests                 # no network: every test uses a fake transport
```

Releases publish to PyPI from CI when a `fictura-py-v<version>` tag is pushed
(see `.github/workflows/python-sdk.yml`).
