Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

### Features

* add audience collection mode

* **api:** add native server batch overloads and align with client specs v0.13.0

## [0.2.0](https://github.com/altertable-ai/altertable-python/compare/altertable-v0.1.0...altertable-v0.2.0) (2026-03-09)
Expand Down
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,21 @@ client.track([

Pass arrays to `identify` and `alias` for the same pass-through behavior.

### Audience measurement

With an environment-bound API key, pass `mode="audience"` to send events without
identity or environment fields:

```python
audience = Altertable("your_api_key", mode="audience")
audience.track("docs_opened", options={"properties": {"page": "install"}})
```

Mode is fixed for each client. Audience events contain only `mode`, `event`,
`timestamp`, and `properties`, including in batches; `identify()` and `alias()`
return `None` without sending a request. Product clients drop any top-level
`mode` field from batch entries.

### Identifying Users

```python
Expand Down
4 changes: 2 additions & 2 deletions src/altertable/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from importlib.metadata import version, PackageNotFoundError
from .client import Altertable
from .client import Altertable, TrackingMode

try:
__version__ = version("altertable")
except PackageNotFoundError:
__version__ = "unknown"

__all__ = ["Altertable", "__version__"]
__all__ = ["Altertable", "TrackingMode", "__version__"]
41 changes: 36 additions & 5 deletions src/altertable/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import datetime
import requests
from typing import Dict, Any, List, Optional, Union
from typing import Dict, Any, List, Literal, Optional, Union

TrackingMode = Literal["product", "audience"]

class AltertableError(Exception):
pass
Expand All @@ -17,23 +19,48 @@ def __init__(self, message: str, cause: Exception):
self.cause = cause

class Altertable:
def __init__(self, api_key: str, server_url: str = "https://api.altertable.ai", environment: str = "production", timeout: int = 10000):
def __init__(self, api_key: str, server_url: str = "https://api.altertable.ai", environment: str = "production", timeout: int = 10000, *, mode: TrackingMode = "product"):
"""
Initialize the Altertable client.

:param api_key: API key used to authenticate with the Altertable API.
:param server_url: Base URL of the Altertable API server.
:param environment: Environment name (for example, "production" or "staging").
:param mode: Collection mode, fixed for this client. Audience mode sends events
without identity or environment fields and ignores identify and alias.
:param timeout: Request timeout in milliseconds. This value is converted to seconds
before being passed to the underlying `requests` session.
"""
if mode not in ("product", "audience"):
raise ValueError('Invalid tracking mode. Use "product" or "audience".')
self._mode: TrackingMode = mode
self.api_key = api_key
self.server_url = server_url.rstrip("/")
self.environment = environment
self.timeout = timeout / 1000.0
self.session = requests.Session()
self.session.headers.update({"X-API-Key": self.api_key, "Content-Type": "application/json"})

@property
def mode(self) -> TrackingMode:
"""Collection mode. Create a new client to change modes."""
return self._mode

def _ignore_identity(self) -> bool:
return self._mode == "audience"

def _apply_mode(self, payload: Dict[str, Any]) -> Dict[str, Any]:
# The client owns the mode: raw batches and options cannot select another
# mode or restore identity and environment fields.
if self._mode == "product":
return {key: value for key, value in payload.items() if key != "mode"}
return {
"mode": "audience",
"event": payload["event"],
"timestamp": self._get_timestamp(payload.get("timestamp")),
"properties": payload.get("properties") or {},
}

def _get_timestamp(self, timestamp: Optional[Union[str, int]] = None) -> str:
if timestamp is None:
return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
Expand All @@ -56,8 +83,8 @@ def _post(self, endpoint: str, payload: Union[Dict[str, Any], List[Dict[str, Any

def track(self, event: Union[str, List[Dict[str, Any]]], distinct_id: Optional[str] = None, options: Optional[Dict[str, Any]] = None):
if isinstance(event, list):
return self._post("/track", event)
if distinct_id is None:
return self._post("/track", [self._apply_mode(payload) for payload in event])
if distinct_id is None and self._mode == "product":
raise TypeError("distinct_id is required when tracking one event")

options = options or {}
Expand All @@ -73,9 +100,11 @@ def track(self, event: Union[str, List[Dict[str, Any]]], distinct_id: Optional[s
if "device_id" in options:
payload["device_id"] = options["device_id"]

return self._post("/track", payload)
return self._post("/track", self._apply_mode(payload))

def identify(self, distinct_id: Union[str, List[Dict[str, Any]]], options: Optional[Dict[str, Any]] = None):
if self._ignore_identity():
return None
if isinstance(distinct_id, list):
return self._post("/identify", distinct_id)

Expand All @@ -95,6 +124,8 @@ def identify(self, distinct_id: Union[str, List[Dict[str, Any]]], options: Optio
return self._post("/identify", payload)

def alias(self, distinct_id: Union[str, List[Dict[str, Any]]], new_user_id: Optional[str] = None, options: Optional[Dict[str, Any]] = None):
if self._ignore_identity():
return None
if isinstance(distinct_id, list):
return self._post("/alias", distinct_id)
if new_user_id is None:
Expand Down
136 changes: 136 additions & 0 deletions tests/test_audience.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import copy
import warnings
from unittest.mock import Mock

import pytest

from altertable import Altertable

AUDIENCE_FIELDS = {"mode", "event", "timestamp", "properties"}


def make_client(**kwargs):
client = Altertable("key", **kwargs)
response = Mock(ok=True)
response.json.return_value = {"ok": True}
client.session.post = Mock(return_value=response)
return client


def sent_payloads(client):
return [call.kwargs["json"] for call in client.session.post.call_args_list]


def test_track_sends_only_audience_fields_and_leaves_properties_unchanged():
client = make_client(environment="ignored", mode="audience")
properties = {
"section": "docs",
"environment": "business-value",
"$url": "https://user:password@example.com/docs?token=private#secret",
"$referer": "https://search.example/private?token=private",
"$viewport": "1234x987",
}
options = {
"mode": "product",
"environment": "private-env",
"anonymous_id": "private-anon",
"device_id": "private-device",
"timestamp": "2026-11-09T10:00:00.000Z",
"properties": properties,
}
original = copy.deepcopy(options)

assert client.track("Opened", "private-user", options) == {"ok": True}

assert sent_payloads(client) == [
{
"mode": "audience",
"event": "Opened",
"timestamp": "2026-11-09T10:00:00.000Z",
"properties": properties,
}
]
assert options == original


def test_track_does_not_require_distinct_id():
client = make_client(mode="audience")

client.track("Opened")

[payload] = sent_payloads(client)
assert set(payload) == AUDIENCE_FIELDS
assert payload["properties"] == {}


def test_raw_batch_cannot_restore_identity_or_select_product_mode():
client = make_client(mode="audience")
events = [
{
"mode": "product",
"event": "First",
"timestamp": 0,
"distinct_id": "legacy-user",
"anonymous_id": "legacy-anonymous",
"device_id": "legacy-device",
"session_id": "legacy-session",
"environment": "ignored",
"properties": {"$url": "/relative?token=private", "environment": "business-value"},
},
{"event": "Second"},
]
original = copy.deepcopy(events)

client.track(events)

[batch] = sent_payloads(client)
assert batch[0] == {
"mode": "audience",
"event": "First",
"timestamp": "1970-01-01T00:00:00.000Z",
"properties": {"$url": "/relative?token=private", "environment": "business-value"},
}
assert set(batch[1]) == AUDIENCE_FIELDS
assert batch[1]["properties"] == {}
assert events == original


def test_identify_and_alias_are_ignored_silently():
client = make_client(mode="audience")

with warnings.catch_warnings():
warnings.simplefilter("error")
assert client.identify("user", {"traits": {"email": "private"}}) is None
assert client.alias("user") is None
assert client.identify([{"distinct_id": "user"}]) is None
assert client.alias([{"distinct_id": "user", "new_user_id": "other"}]) is None

client.session.post.assert_not_called()


def test_mode_is_validated_and_fixed():
for invalid in ("anonymous", "", None):
with pytest.raises(ValueError, match="Invalid tracking mode"):
Altertable("key", mode=invalid)
client = Altertable("key", mode="audience")
with pytest.raises(AttributeError):
client.mode = "product"
assert client.mode == "audience"
assert Altertable("key").mode == "product"


def test_product_batch_cannot_select_audience_mode():
client = make_client()
event = {
"mode": "audience",
"event": "Product",
"distinct_id": "user",
"properties": {"mode": "business-value"},
}

client.track([event])

assert sent_payloads(client) == [
[{"event": "Product", "distinct_id": "user", "properties": {"mode": "business-value"}}]
]
assert event["mode"] == "audience"
Loading