Metadata-Version: 2.4
Name: tracedb
Version: 0.1.1
Summary: 
License-File: LICENSE
Requires-Python: >=3.10,<4.0
Classifier: Intended Audience :: Developers
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: OS Independent
Classifier: Operating System :: POSIX
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Provides-Extra: aiohttp
Requires-Dist: aiohttp (>=3.14.0,<4) ; (python_version >= "3.10") and (extra == "aiohttp")
Requires-Dist: httpx (>=0.21.2)
Requires-Dist: httpx-aiohttp (==0.1.8) ; (python_version >= "3.10") and (extra == "aiohttp")
Requires-Dist: pydantic (>=1.9.2)
Requires-Dist: pydantic-core (>=2.18.2,<3.0.0)
Requires-Dist: typing_extensions (>=4.0.0)
Project-URL: Repository, https://github.com/Trace-DB/tracedb-python
Description-Content-Type: text/markdown

# TraceDb Python Library

[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen)](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2FTrace-DB%2Ftracedb-python)
[![pypi](https://img.shields.io/pypi/v/tracedb)](https://pypi.python.org/pypi/tracedb)

The TraceDb Python library provides convenient access to the TraceDb APIs from Python.

## Table of Contents

- [Install](#install)
- [Claim Boundary](#claim-boundary)
- [Installation](#installation)
- [Reference](#reference)
- [Usage](#usage)
- [Environments](#environments)
- [Async Client](#async-client)
- [Exception Handling](#exception-handling)
- [Advanced](#advanced)
  - [Access Raw Response Data](#access-raw-response-data)
  - [Retries](#retries)
  - [Timeouts](#timeouts)
  - [Custom Client](#custom-client)
- [Contributing](#contributing)

## Install

The package is live on PyPI:

```bash
pip install tracedb
```

> Install the `async` extra for `AsyncTraceDB` helpers backed by `aiohttp`:
> ```bash
> pip install tracedb[async]
> ```

Current public DX:

```python
from tracedb import TraceDB

db = TraceDB.from_env()
docs = db.table("docs").tenant("tenant-a")

docs.insert("intro", {
    "body": "TraceDB Python SDK",
    "embedding": [1, 0, 0],
    "status": "published",
})

docs.insert_rows([
    {"id": "sdk", "body": "TraceDB sync SDK", "embedding": [0.8, 0.2, 0], "status": "published"},
    {"id": "ops", "body": "TraceDB snapshot restore path", "embedding": [0, 1, 0], "status": "published"},
], idempotency_key="docs-batch-1")

rows = (
    db.table("docs")
    .where({"tenant_id": "tenant-a", "status": "published"})
    .match_text("body", "TraceDB")
    .near("embedding", [1, 0, 0])
    .with_options(explain=True, freshness="lazy")
    .limit(20)
    .all()
)

traceql_rows = db.traceql("""
FROM docs
TENANT tenant-a
WHERE status = "published"
MATCH body "TraceDB"
LIMIT 20
""")

graphql_schema = db.graphql_schema()

graphql_rows = db.graphql(
    'query { docs(tenant_id: "tenant-a", match: "TraceDB", limit: 20) { record_id } }'
)
```

The query builder preserves field selection: `match_text("body", ...)` becomes
`HybridQuery.text_field = "body"` and `near("embedding", ...)` becomes
`HybridQuery.vector_field = "embedding"` on the HTTP wire.
It also canonicalizes `strict`, `lazy`, and `allow_dirty` freshness inputs to
the `Strict`, `Lazy`, and `AllowDirty` wire modes.

Typed response dataclasses such as `ReadyResponse`, `HealthResponse`,
`QueryResult`, `ScanResult`, `PutResult`, and `BatchPutResult` are exported from
`tracedb` and preserve dict-like compatibility with `get(...)`, indexing,
membership checks, and `to_dict()`. The package exposes `__version__ = "0.1.1"`,
and sync/async HTTP requests send `User-Agent: tracedb-python/0.1.1`.

The package is fully typed and ships a `py.typed` marker (PEP 561). Type
checkers such as mypy, pyright, and IDE language servers will discover and
use the inline annotations automatically when the package is installed.

`TraceDB.from_env()` reads `TRACEDB_URL`, optional `TRACEDB_TOKEN`,
`TRACEDB_DATABASE_ID`, `TRACEDB_BRANCH_ID`, `TRACEDB_TIMEOUT_MS`, and
`TRACEDB_SAFE_RETRIES`, and `TRACEDB_IDEMPOTENCY_RETRIES`. Explicit keyword
arguments override matching environment values. Direct construction with
`TraceDB(url, token="dev-token")` remains supported. If `database_id` is
configured and `branch_id` is omitted, copied JSON POST bodies default
`branch_id` to `<database_id>:main`.

The sync client uses Python standard-library HTTP and imports without async
dependencies installed. Install the `async` extra for `AsyncTraceDB` helpers
backed by `aiohttp`. It preserves the raw HTTP escape
hatch with `request_json(...)`, exposes `TraceDBHTTPError` with method, path,
status, response body, parsed `error`, and optional `code`, and supports
caller-provided `Idempotency-Key` values on mutation/admin calls.
`table.insert_batch([{"id": ..., "fields": {...}}])` preserves the raw
TraceDB record-input shape. `table.insert_rows([...])` is the notebook/data
workflow helper: it accepts row dictionaries, reads the record id from `id` by
default, supports `id_field="..."` for custom row keys, copies row fields into
the canonical batch request, and still executes through `POST /v1/records/put-batch`.
`TraceDB.traceql(query)` and `traceql_request({"query": query})` execute native
TraceQL strings through `POST /v1/traceql`.
`TraceDB.graphql_schema()` reads generated SDL from `GET /v1/graphql/schema`.
`TraceDB.graphql(query)` and `graphql_request({"query": query})` execute native
GraphQL operations through `POST /v1/graphql`; `bounded_graphql(...)` uses the
bounded compatibility adapter at `POST /v1/graphql/bounded`.
`safe_retries` retries transient HTTP 5xx responses only for read-only routes:
health, ready, GraphQL schema export, get, scan, query, bounded GraphQL,
explain, and polymorphic native TraceQL/GraphQL payloads classified as
read-only. It does not retry mutating TraceQL/GraphQL commands/root fields or
other writes/admin mutations without an idempotency key. `idempotency_retries`
is default-off and retries transient HTTP 5xx responses for mutation/admin
routes, including mutating native TraceQL/GraphQL payloads, only when that
request carries a caller-provided `Idempotency-Key`; unkeyed writes and
4xx/conflict responses are not retried.

Run the local unit/package checks:

```bash
python3 -m unittest discover -s tests
python3 install_smoke.py
```

`install_smoke.py` prefers a temporary venv, installs this directory as the
`tracedb` package with pip `--no-deps`, and runs a consumer script from outside
the repo so source-path imports cannot hide package drift. On remote images
where Python can run tests but `ensurepip` is unavailable, it falls back to an
isolated temporary pip `--target` install. It emits `python sdk install smoke
ok`.

Optional loopback HTTP smoke:

```bash
python3 http_smoke.py
```

The smoke starts a local `tracedb-server` from `TRACEDB_CORE_REPO`, falling back
to sibling `../tracedb` from the standalone repo root. It drives schema apply,
single put,
row batch ingest, patch, get, scan, query, TraceQL string execution, explain,
GraphQL schema export, bounded GraphQL result/explain, delete, idempotency
replay and conflict, error envelope parsing, compact, snapshot, restore, and
admin jobs. It emits
`python sdk http smoke ok`.

This is sync Python SDK product-path evidence against a local server only. The
package metadata and checkpoint commands above are local project/package-shape
evidence only. The platform conformance lane installs a copied package into an
isolated temporary pip `--target` and runs this HTTP smoke with source-path
imports disabled, so SDK conformance cannot pass by accidentally importing the
repo copy. It is not hosted-alpha readiness,
managed-cloud proof, SQL compatibility, full GraphQL adapter parity, benchmark
evidence, async support, or Go SDK support.

## Claim Boundary

`tracedb==0.1.1` is Python SDK packaging for the current TraceDB HTTP product
surface. It does not claim managed-cloud readiness,
hosted-alpha readiness, SQL compatibility, benchmark wins, production SLA, or
Go SDK support.

## Installation

```sh
pip install tracedb
```

## Reference

A full reference for this library is available [here](https://github.com/Trace-DB/tracedb-python/blob/HEAD/./reference.md).

## Usage

Instantiate and use the client with the following:

```python
from tracedb import TraceDB

client = TraceDB(
    token="<token>",
)

client.tracedb.admin.post_admin_compact(
    request={
        "key": "value"
    },
)
```

## Environments

This SDK allows you to configure different environments for API requests.

```python
from tracedb import TraceDB
from tracedb.environment import TraceDBEnvironment

client = TraceDB(
    environment=TraceDBEnvironment.DEFAULT,
)
```

## Async Client

The SDK also exports an `async` client so that you can make non-blocking calls to our API. Note that if you are constructing an Async httpx client class to pass into this client, use `httpx.AsyncClient()` instead of `httpx.Client()` (e.g. for the `httpx_client` parameter of this client).

```python
import asyncio

from tracedb import AsyncTraceDB

client = AsyncTraceDB(
    token="<token>",
)


async def main() -> None:
    await client.tracedb.admin.post_admin_compact(
        request={
            "key": "value"
        },
    )


asyncio.run(main())
```

## Exception Handling

When the API returns a non-success status code (4xx or 5xx response), a subclass of the following error
will be thrown.

```python
from tracedb.core.api_error import ApiError

try:
    client.tracedb.admin.post_admin_compact(...)
except ApiError as e:
    print(e.status_code)
    print(e.body)
```

## Advanced

### Access Raw Response Data

The SDK provides access to raw response data, including headers, through the `.with_raw_response` property.
The `.with_raw_response` property returns a "raw" client that can be used to access the `.headers` and `.data` attributes.

```python
from tracedb import TraceDB

client = TraceDB(...)
response = client.tracedb.admin.with_raw_response.post_admin_compact(...)
print(response.headers)  # access the response headers
print(response.status_code)  # access the response status code
print(response.data)  # access the underlying object
```

### Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long
as the request is deemed retryable and the number of retry attempts has not grown larger than the configured
retry limit (default: 2).

Which status codes are retried depends on the `retryStatusCodes` generator configuration:

**`legacy`** (current default): retries on
- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
- [409](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409) (Conflict)
- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
- [5XX](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses) (All server errors, including 500)

**`recommended`**: retries on
- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
- [409](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409) (Conflict)
- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
- [502](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) (Bad Gateway)
- [503](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) (Service Unavailable)
- [504](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504) (Gateway Timeout)

Use the `max_retries` request option to configure this behavior.

```python
client.tracedb.admin.post_admin_compact(..., request_options={
    "max_retries": 1
})
```

### Timeouts

The SDK defaults to a 60 second timeout. You can configure this with a timeout option at the client or request level.

```python
from tracedb import TraceDB

client = TraceDB(..., timeout=20.0)

# Override timeout for a specific method
client.tracedb.admin.post_admin_compact(..., request_options={
    "timeout_in_seconds": 1
})
```

### Custom Client

You can override the `httpx` client to customize it for your use-case. Some common use-cases include support for proxies
and transports.

```python
import httpx
from tracedb import TraceDB

client = TraceDB(
    ...,
    httpx_client=httpx.Client(
        proxy="http://my.test.proxy.example.com",
        transport=httpx.HTTPTransport(local_address="0.0.0.0"),
    ),
)
```

## Contributing

While we value open-source contributions to this SDK, this library is generated programmatically.
Additions made directly to this library would have to be moved over to our generation code,
otherwise they would be overwritten upon the next generated release. Feel free to open a PR as
a proof of concept, but know that we will not be able to merge it as-is. We suggest opening
an issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!

