Skip to main content

No project description provided

Project description

TraceDb Python Library

fern shield pypi

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

Table of Contents

Install

The package is live on PyPI:

pip install tracedb

Install the async extra for AsyncTraceDB helpers backed by aiohttp:

pip install tracedb[async]

Current public DX:

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:

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:

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

pip install tracedb

Reference

A full reference for this library is available here.

Usage

Instantiate and use the client with the following:

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.

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).

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.

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.

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 (Timeout)
  • 409 (Conflict)
  • 429 (Too Many Requests)
  • 5XX (All server errors, including 500)

recommended: retries on

  • 408 (Timeout)
  • 409 (Conflict)
  • 429 (Too Many Requests)
  • 502 (Bad Gateway)
  • 503 (Service Unavailable)
  • 504 (Gateway Timeout)

Use the max_retries request option to configure this behavior.

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.

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.

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!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tracedb-0.1.1.tar.gz (59.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tracedb-0.1.1-py3-none-any.whl (104.5 kB view details)

Uploaded Python 3

File details

Details for the file tracedb-0.1.1.tar.gz.

File metadata

  • Download URL: tracedb-0.1.1.tar.gz
  • Upload date:
  • Size: 59.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for tracedb-0.1.1.tar.gz
Algorithm Hash digest
SHA256 6f5b15ea54d9c1213556e3dd063083f4e4cd64110e0e619870e684623719ba43
MD5 7cd7756d2396feeac90da5e844a9386b
BLAKE2b-256 fc6387e3527f9c4e7d3fe3993e58b39db03095974a28f31c8a9a171e3226cdc9

See more details on using hashes here.

Provenance

The following attestation bundles were made for tracedb-0.1.1.tar.gz:

Publisher: release.yml on Trace-DB/tracedb-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tracedb-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: tracedb-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 104.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for tracedb-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ec3b187c71547c69920bba7bca0ff846f0bc1629a101324ee042bdf10a313b44
MD5 98e3e1d908937df6f566d42d6238b83e
BLAKE2b-256 c25c1b648f92651bc150db98de55b7d03d8839748adec5407e9ee11d6e72e819

See more details on using hashes here.

Provenance

The following attestation bundles were made for tracedb-0.1.1-py3-none-any.whl:

Publisher: release.yml on Trace-DB/tracedb-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page