From f4df41a2ba68e254744d3b5aea3a5986dbcf7790 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Wed, 4 Nov 2026 16:39:38 +0100 Subject: [PATCH 1/5] feat: add audience collection mode --- CHANGELOG.md | 2 + README.md | 53 +++++++ src/altertable/__init__.py | 4 +- src/altertable/client.py | 149 +++++++++++++++++-- src/altertable/py.typed | 0 tests/test_audience.py | 285 +++++++++++++++++++++++++++++++++++++ 6 files changed, 477 insertions(+), 16 deletions(-) create mode 100644 src/altertable/py.typed create mode 100644 tests/test_audience.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f9dfd94..1294fa9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ### Features +* add audience collection mode with identity suppression and sanitized single and batch events + * **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) diff --git a/README.md b/README.md index 4c6fc8c..bdd5219 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,59 @@ client.track([ ``` Pass arrays to `identify` and `alias` for the same pass-through behavior. +The client owns the collection mode: top-level `mode` fields in product batches +are removed before sending, so a batch cannot switch to audience processing. + +### Audience measurement + +Use `mode="audience"` to collect events without client identity fields: + +```python +audience = Altertable("your_api_key", mode="audience") +audience.track( + "Docs Opened", + options={"properties": {"$url": "https://example.com/docs?source=email", "section": "intro"}}, +) +audience.track([ + {"event": "Install Copied", "properties": {"package": "python"}}, + {"event": "Docs Opened", "properties": {"$url": "https://example.com/docs"}}, +]) +``` + +Product mode remains the default. `mode` is read-only for a client's lifetime; +create a new client to change modes. Only `"product"` and `"audience"` are accepted. + +Audience requests contain only `mode: "audience"`, `event`, `timestamp`, and +`properties`. Both single events and every event in a batch follow this policy, +even if the caller supplies identity, environment, or a conflicting mode. +Audience mode requires an API key bound to an environment; that key determines +the audience environment. Legacy unbound keys cannot select an audience +environment. Product mode continues to honor the existing `environment` argument and per-event overrides. + +In audience properties, `$url` is reduced to origin plus path and `$referer` to +origin only. Credentials, query strings, and fragments are removed; invalid or +non-HTTP(S) URLs become `None`. `$viewport` is removed. Missing `$url` and +`$referer` are sent as `None`. Other caller properties are retained, including +custom identifiers or personal information: review your properties and URL paths +before sending them. The SDK does not automatically collect browser context or +extract query parameters. Sanitization copies properties without changing inputs. + +`identify()` and `alias()` (including batch calls) return `None` without sending +requests in audience mode. The client emits a `RuntimeWarning` once when these +methods are used. HTTP transport adapters mounted on `client.session` remain +supported. + +This is a synchronous server SDK. It does not persist identities or events, +buffer events, automatically retry requests, or replay failed events in a new +client. Failed sends raise the existing `ApiError` or `NetworkError`; applications +can retry explicitly. It has no consent API: applications must gate calls on their +own consent decisions, and audience mode does not override those decisions. + +Audience visitor hashing on the backend uses the request IP and User-Agent. +With this server SDK, those describe your server and HTTP client, rather than the +end-user browser. Browser visitor counts therefore cannot be reconstructed +reliably from these server requests. The SDK does not forward end-user IP or +User-Agent headers automatically. ### Identifying Users diff --git a/src/altertable/__init__.py b/src/altertable/__init__.py index 008cfaa..cce499d 100644 --- a/src/altertable/__init__.py +++ b/src/altertable/__init__.py @@ -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__"] diff --git a/src/altertable/client.py b/src/altertable/client.py index d78b279..d6a1acc 100644 --- a/src/altertable/client.py +++ b/src/altertable/client.py @@ -1,63 +1,171 @@ import datetime +import warnings +from typing import Dict, Any, List, Literal, Optional, Union +from urllib.parse import urlsplit + import requests -from typing import Dict, Any, List, Optional, Union + +TrackingMode = Literal["product", "audience"] + + +def _sanitize_url(value: Any, origin_only: bool = False) -> Optional[str]: + if not isinstance(value, str): + return None + try: + # Reject ambiguous input rather than forwarding potentially sensitive text. + if "\\" in value or any(char.isspace() or ord(char) < 32 for char in value): + return None + url = urlsplit(value) + if url.scheme not in ("http", "https") or not url.hostname: + return None + host = url.hostname.encode("idna").decode("ascii") + if ":" in host: + host = f"[{host}]" + port = url.port + if port is not None and port != (443 if url.scheme == "https" else 80): + host = f"{host}:{port}" + origin = f"{url.scheme}://{host}" + return origin if origin_only else origin + (url.path or "/") + except (ValueError, UnicodeError): + return None + class AltertableError(Exception): pass + class ApiError(AltertableError): def __init__(self, status: int, message: str, details: Any = None): super().__init__(message) self.status = status self.details = details + class NetworkError(AltertableError): def __init__(self, message: str, cause: Exception): super().__init__(message) 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 omits identity + and environment fields and reduces page context. :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._identity_warning_emitted = False 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"}) + 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: + if self.mode != "audience": + return False + if not self._identity_warning_emitted: + warnings.warn( + "Altertable identify() and alias() calls are ignored in audience mode.", + RuntimeWarning, + stacklevel=3, + ) + self._identity_warning_emitted = True + return True + + def _prepare_track(self, payload: Dict[str, Any]) -> Dict[str, Any]: + # The client owns collection policy, including for caller-supplied batches. + if self.mode == "product": + return {key: value for key, value in payload.items() if key != "mode"} + properties = dict(payload.get("properties", {})) + properties["$url"] = _sanitize_url(properties.get("$url")) + properties["$referer"] = _sanitize_url( + properties.get("$referer"), origin_only=True + ) + properties.pop("$viewport", None) + return { + "mode": "audience", + "event": payload["event"], + "timestamp": self._get_timestamp(payload.get("timestamp")), + "properties": properties, + } 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") + return ( + datetime.datetime.now(datetime.timezone.utc) + .isoformat(timespec="milliseconds") + .replace("+00:00", "Z") + ) if isinstance(timestamp, int): - return datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") + return ( + datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc) + .isoformat(timespec="milliseconds") + .replace("+00:00", "Z") + ) return timestamp - def _post(self, endpoint: str, payload: Union[Dict[str, Any], List[Dict[str, Any]]]): + def _post( + self, endpoint: str, payload: Union[Dict[str, Any], List[Dict[str, Any]]] + ): + if endpoint == "/track": + payload = ( + [self._prepare_track(event) for event in payload] + if isinstance(payload, list) + else self._prepare_track(payload) + ) try: - response = self.session.post(f"{self.server_url}{endpoint}", json=payload, timeout=self.timeout) + response = self.session.post( + f"{self.server_url}{endpoint}", json=payload, timeout=self.timeout + ) if not response.ok: try: error_data = response.json() - raise ApiError(response.status_code, error_data.get("message", "API Error"), error_data) + raise ApiError( + response.status_code, + error_data.get("message", "API Error"), + error_data, + ) except ValueError: raise ApiError(response.status_code, response.text) return response.json() except requests.exceptions.RequestException as e: raise NetworkError("Network request failed", e) - def track(self, event: Union[str, List[Dict[str, Any]]], distinct_id: Optional[str] = None, options: Optional[Dict[str, Any]] = None): + 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: + if distinct_id is None and self.mode == "product": raise TypeError("distinct_id is required when tracking one event") options = options or {} @@ -66,16 +174,22 @@ def track(self, event: Union[str, List[Dict[str, Any]]], distinct_id: Optional[s "event": event, "environment": options.get("environment", self.environment), "distinct_id": distinct_id, - "properties": options.get("properties", {}) + "properties": options.get("properties", {}), } if "anonymous_id" in options: payload["anonymous_id"] = options["anonymous_id"] if "device_id" in options: payload["device_id"] = options["device_id"] - + return self._post("/track", payload) - def identify(self, distinct_id: Union[str, List[Dict[str, Any]]], options: Optional[Dict[str, Any]] = None): + 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) @@ -94,7 +208,14 @@ 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): + 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: diff --git a/src/altertable/py.typed b/src/altertable/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_audience.py b/tests/test_audience.py new file mode 100644 index 0000000..3f91fe4 --- /dev/null +++ b/tests/test_audience.py @@ -0,0 +1,285 @@ +"""Applicable audience contracts from altertable-js/test/audience.test.ts. + +This server SDK has no browser storage, automatic context, consent queue, hooks, +analytics-source adapters, or built-in retry loop. Inspect serialized requests +through an ordinary HTTP transport adapter, including caller-managed retries. +""" + +import copy +import datetime +import json +import warnings + +import pytest +import requests +from requests.adapters import BaseAdapter + +from altertable import Altertable +from altertable.client import ApiError, NetworkError + + +class RecordingAdapter(BaseAdapter): + def __init__(self): + super().__init__() + self.payloads = [] + self.status = 200 + self.error = None + + def send(self, request, **kwargs): + self.payloads.append(json.loads(request.body)) + if self.error: + raise self.error + response = requests.Response() + response.status_code = self.status + response._content = b'{"ok": true}' + return response + + def close(self): + pass + + +@pytest.fixture +def audience(): + client = Altertable("key", environment="ignored", mode="audience") + adapter = RecordingAdapter() + client.session.mount("https://", adapter) + yield client, adapter + client.session.close() + + +def assert_audience(payload): + assert set(payload) == {"mode", "event", "timestamp", "properties"} + assert payload["mode"] == "audience" + datetime.datetime.fromisoformat(payload["timestamp"].replace("Z", "+00:00")) + assert "$viewport" not in payload["properties"] + + +def test_track_without_identity(audience): + client, adapter = audience + assert client.track("Opened", options={"properties": {"section": "docs"}}) == { + "ok": True + } + payload = adapter.payloads[0] + assert_audience(payload) + assert payload["properties"] == {"section": "docs", "$url": None, "$referer": None} + + +def test_single_track_reduces_context_without_mutating_caller(audience): + client, adapter = audience + options = { + "mode": "product", + "environment": "private-env", + "anonymous_id": "private-anon", + "device_id": "private-device", + "session_id": "private-session", + "timestamp": "2026-11-04T12:00:00.000Z", + "properties": { + "$url": "https://user:password@Site.Example:443/docs?token=secret#hash", + "$referer": "https://search.example/private?token=secret", + "$viewport": "1234x987", + "section": "docs", + "custom_email": "caller@example.com", + }, + } + original = copy.deepcopy(options) + client.track("Opened", "private-user", options) + payload = adapter.payloads[0] + assert_audience(payload) + assert payload["timestamp"] == options["timestamp"] + assert payload["properties"] == { + "$url": "https://site.example/docs", + "$referer": "https://search.example", + "section": "docs", + "custom_email": "caller@example.com", + } + assert options == original + assert "secret" not in json.dumps(payload) + assert "private-" not in json.dumps(payload) + + +def test_every_batch_event_is_normalized_without_chunking(audience): + client, adapter = audience + events = [ + { + "event": f"event-{index}", + "mode": "product", + "distinct_id": "private-user", + "anonymous_id": "private-anon", + "device_id": "private-device", + "session_id": "private-session", + "environment": "private-env", + "extra": "private-extra", + "timestamp": 0, + "properties": { + "$url": "https://site.example/docs?email=secret#code", + "$referer": "https://search.example/private?token=secret", + "$viewport": "1234x987", + "section": "docs", + }, + } + for index in range(101) + ] + events.append({"event": "Defaults"}) + original = copy.deepcopy(events) + client.track(events) + assert len(adapter.payloads) == 1 + assert len(adapter.payloads[0]) == 102 + for payload in adapter.payloads[0]: + assert_audience(payload) + assert adapter.payloads[0][0]["timestamp"] == "1970-01-01T00:00:00.000Z" + assert adapter.payloads[0][0]["properties"] == { + "$url": "https://site.example/docs", + "$referer": "https://search.example", + "section": "docs", + } + assert "private-" not in json.dumps(adapter.payloads) + assert events == original + + +@pytest.mark.parametrize( + "value", + [ + "not a URL?token=secret", + "javascript:secret", + "/relative?token=secret", + "https://[invalid", + "https://example.com:invalid/path", + None, + 42, + "https://example.com\\@private/path", + "https://bad host/private", + ], +) +def test_invalid_urls_are_discarded_in_singles_and_batches(audience, value): + client, adapter = audience + properties = {"$url": value, "$referer": value} + client.track("Single", options={"properties": properties}) + client.track([{"event": "Batch", "properties": properties}]) + for payload in [adapter.payloads[0], adapter.payloads[1][0]]: + assert payload["properties"] == {"$url": None, "$referer": None} + + +@pytest.mark.parametrize( + "url, expected", + [ + ("https://example.com?secret#hash", "https://example.com/"), + ( + "http://user:password@example.com:8080/path?q#hash", + "http://example.com:8080/path", + ), + ("https://[::1]:443/path?q#hash", "https://[::1]/path"), + ("https://éxample.com/path?q#hash", "https://xn--xample-9ua.com/path"), + ], +) +def test_url_origins_and_paths(audience, url, expected): + client, adapter = audience + client.track("Opened", options={"properties": {"$url": url}}) + assert adapter.payloads[0]["properties"]["$url"] == expected + + +def test_identity_calls_are_ignored_before_validation_and_warn_once(audience): + client, adapter = audience + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always") + assert client.identify("user", {"traits": {"email": "secret"}}) 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": "secret"}]) is None + assert len(recorded) == 1 + assert "ignored in audience mode" in str(recorded[0].message) + assert not adapter.payloads + client.track("After identity calls") + assert_audience(adapter.payloads[0]) + + +def test_mode_is_fixed_for_client_lifecycle(audience): + client, adapter = audience + with pytest.raises(AttributeError): + client.mode = "product" + for invalid in ("anonymous", "", None): + with pytest.raises(ValueError, match="Invalid tracking mode"): + Altertable("key", mode=invalid) + client.track("Still active") + assert_audience(adapter.payloads[0]) + product = Altertable("key") + product.session.mount("https://", adapter) + product.track("Product", "user") + assert adapter.payloads[1]["distinct_id"] == "user" + assert "mode" not in adapter.payloads[1] + product.session.close() + + +def test_network_failure_is_not_queued_or_replayed_by_new_client(audience): + client, adapter = audience + adapter.error = requests.exceptions.ConnectionError("Offline") + with pytest.raises(NetworkError): + client.track("Offline") + adapter.error = None + other = Altertable("key", mode="audience") + other.session.mount("https://", adapter) + other.track("New client") + assert [payload["event"] for payload in adapter.payloads] == [ + "Offline", + "New client", + ] + for payload in adapter.payloads: + assert_audience(payload) + other.session.close() + + +def test_caller_retry_retains_audience_policy(audience): + client, adapter = audience + event = {"event": "Retry", "distinct_id": "private", "mode": "product"} + adapter.status = 503 + with pytest.raises(ApiError) as exc: + client.track([event]) + assert exc.value.status == 503 + assert len(adapter.payloads) == 1 # No implicit retry loop. + adapter.status = 200 + client.track([event]) + for batch in adapter.payloads: + assert_audience(batch[0]) + + +@pytest.mark.parametrize("mode", ["product", None]) +def test_product_tracking_preserves_context_and_requires_identity(mode): + client = Altertable( + "key", environment="staging", **({"mode": mode} if mode else {}) + ) + adapter = RecordingAdapter() + client.session.mount("https://", adapter) + with pytest.raises(TypeError, match="distinct_id is required"): + client.track("Missing identity") + properties = {"$url": "https://example.com/?secret#hash", "$viewport": "100x200"} + client.track( + "Product", + "user", + {"properties": properties, "anonymous_id": "anon", "device_id": "device"}, + ) + payload = adapter.payloads[0] + assert payload["distinct_id"] == "user" + assert payload["anonymous_id"] == "anon" + assert payload["device_id"] == "device" + assert payload["environment"] == "staging" + assert payload["properties"] == properties + assert "mode" not in payload + client.session.close() + + +def test_product_batch_cannot_select_audience_processing(): + client = Altertable("key") + adapter = RecordingAdapter() + client.session.mount("https://", adapter) + event = { + "event": "Product", + "mode": "audience", + "distinct_id": "user", + "environment": "staging", + "properties": {"mode": "business-value"}, + } + client.track([event]) + assert adapter.payloads == [ + [{key: value for key, value in event.items() if key != "mode"}] + ] + assert event["mode"] == "audience" + client.session.close() From 91b740aba3f263805ec667fea9c3597fad15e178 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Fri, 6 Nov 2026 16:10:27 +0100 Subject: [PATCH 2/5] docs: focus audience setup and collection behavior --- README.md | 56 +++++++++++++++++++------------------------------------ 1 file changed, 19 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index bdd5219..b014c1c 100644 --- a/README.md +++ b/README.md @@ -59,54 +59,36 @@ are removed before sending, so a batch cannot switch to audience processing. ### Audience measurement -Use `mode="audience"` to collect events without client identity fields: +Use an environment-bound Product Analytics API key and `mode="audience"` to collect events without client identity fields: ```python audience = Altertable("your_api_key", mode="audience") audience.track( "Docs Opened", - options={"properties": {"$url": "https://example.com/docs?source=email", "section": "intro"}}, + options={"properties": {"$url": "https://example.com/docs?source=email"}}, ) audience.track([ {"event": "Install Copied", "properties": {"package": "python"}}, - {"event": "Docs Opened", "properties": {"$url": "https://example.com/docs"}}, ]) ``` -Product mode remains the default. `mode` is read-only for a client's lifetime; -create a new client to change modes. Only `"product"` and `"audience"` are accepted. - -Audience requests contain only `mode: "audience"`, `event`, `timestamp`, and -`properties`. Both single events and every event in a batch follow this policy, -even if the caller supplies identity, environment, or a conflicting mode. -Audience mode requires an API key bound to an environment; that key determines -the audience environment. Legacy unbound keys cannot select an audience -environment. Product mode continues to honor the existing `environment` argument and per-event overrides. - -In audience properties, `$url` is reduced to origin plus path and `$referer` to -origin only. Credentials, query strings, and fragments are removed; invalid or -non-HTTP(S) URLs become `None`. `$viewport` is removed. Missing `$url` and -`$referer` are sent as `None`. Other caller properties are retained, including -custom identifiers or personal information: review your properties and URL paths -before sending them. The SDK does not automatically collect browser context or -extract query parameters. Sanitization copies properties without changing inputs. - -`identify()` and `alias()` (including batch calls) return `None` without sending -requests in audience mode. The client emits a `RuntimeWarning` once when these -methods are used. HTTP transport adapters mounted on `client.session` remain -supported. - -This is a synchronous server SDK. It does not persist identities or events, -buffer events, automatically retry requests, or replay failed events in a new -client. Failed sends raise the existing `ApiError` or `NetworkError`; applications -can retry explicitly. It has no consent API: applications must gate calls on their -own consent decisions, and audience mode does not override those decisions. - -Audience visitor hashing on the backend uses the request IP and User-Agent. -With this server SDK, those describe your server and HTTP client, rather than the -end-user browser. Browser visitor counts therefore cannot be reconstructed -reliably from these server requests. The SDK does not forward end-user IP or -User-Agent headers automatically. +Product mode is the default. Mode is fixed for each client; create a new client to +change it. Audience events omit user, anonymous, device, session, and environment +fields, including caller-supplied batch fields. The API key selects the environment; +legacy unbound keys cannot be used. `identify()` and `alias()` return `None` without +sending requests and emit a `RuntimeWarning` once per client. + +Audience mode removes `$viewport`, reduces `$url` to HTTP(S) origin plus path, and +reduces `$referer` to origin. Invalid URLs become `None`. Custom properties and URL +paths can still contain personal information; choose them accordingly. + +Gate calls on your application's consent decisions. Events are sent synchronously; +failed sends raise `ApiError` or `NetworkError` without automatic retries or replay. + +The backend derives audience visitors from the request IP and User-Agent. For this +server SDK, those identify your server and HTTP client, so these events cannot +reliably measure distinct browser visitors. End-user request headers are not +forwarded automatically. ### Identifying Users From d8c2d98545ee2ffacb9d39941be4b2ae6d8ce47f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Mon, 9 Nov 2026 13:09:47 +0100 Subject: [PATCH 3/5] fix: isolate audience HTTP transport --- CHANGELOG.md | 2 +- README.md | 4 ++ src/altertable/client.py | 28 ++++++++- tests/test_audience.py | 123 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 154 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1294fa9..9276b35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Features -* add audience collection mode with identity suppression and sanitized single and batch events +* add audience collection mode with identity suppression, sanitized single and batch events, and cookie- and ambient-credential-isolated transport * **api:** add native server batch overloads and align with client specs v0.13.0 diff --git a/README.md b/README.md index b014c1c..edef79a 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,10 @@ paths can still contain personal information; choose them accordingly. Gate calls on your application's consent decisions. Events are sent synchronously; failed sends raise `ApiError` or `NetworkError` without automatic retries or replay. +Audience requests do not accept or send cookies, including cookies supplied through +the client's session. To avoid ambient credentials, they also do not use Requests' +environment configuration: `.netrc`, proxy, and CA-bundle environment settings are +ignored. Configure any required proxy or TLS settings directly on `client.session`. The backend derives audience visitors from the request IP and User-Agent. For this server SDK, those identify your server and HTTP client, so these events cannot diff --git a/src/altertable/client.py b/src/altertable/client.py index d6a1acc..89996f4 100644 --- a/src/altertable/client.py +++ b/src/altertable/client.py @@ -8,6 +8,29 @@ TrackingMode = Literal["product", "audience"] +class _AudienceCookieJar(requests.cookies.RequestsCookieJar): + """A cookie jar that neither retains response cookies nor sends supplied ones.""" + + def set_cookie(self, cookie, *args, **kwargs): + return None + + +class _AudienceSession(requests.Session): + """HTTP transport for audience collection, which must not carry credentials.""" + + def __init__(self): + super().__init__() + self.cookies = _AudienceCookieJar() + # requests otherwise obtains basic authentication from a user's .netrc file. + self.trust_env = False + + def send(self, request, **kwargs): + # Session.send runs for the original request and each redirect hop. + for header in ("Cookie", "Cookie2", "Authorization"): + request.headers.pop(header, None) + return super().send(request, **kwargs) + + def _sanitize_url(value: Any, origin_only: bool = False) -> Optional[str]: if not isinstance(value, str): return None @@ -76,7 +99,7 @@ def __init__( self.server_url = server_url.rstrip("/") self.environment = environment self.timeout = timeout / 1000.0 - self.session = requests.Session() + self.session = _AudienceSession() if mode == "audience" else requests.Session() self.session.headers.update( {"X-API-Key": self.api_key, "Content-Type": "application/json"} ) @@ -102,7 +125,8 @@ def _prepare_track(self, payload: Dict[str, Any]) -> Dict[str, Any]: # The client owns collection policy, including for caller-supplied batches. if self.mode == "product": return {key: value for key, value in payload.items() if key != "mode"} - properties = dict(payload.get("properties", {})) + properties_value = payload.get("properties", {}) + properties = {} if properties_value is None else dict(properties_value) properties["$url"] = _sanitize_url(properties.get("$url")) properties["$referer"] = _sanitize_url( properties.get("$referer"), origin_only=True diff --git a/tests/test_audience.py b/tests/test_audience.py index 3f91fe4..dde0da0 100644 --- a/tests/test_audience.py +++ b/tests/test_audience.py @@ -8,7 +8,9 @@ import copy import datetime import json +import threading import warnings +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import pytest import requests @@ -38,6 +40,61 @@ def close(self): pass +@pytest.fixture +def cookie_server(): + requests_seen = [] + + class Handler(BaseHTTPRequestHandler): + def log_message(self, format, *args): + pass + + def _record(self): + requests_seen.append( + ( + self.path, + self.headers.get("Cookie"), + self.headers.get("Cookie2"), + self.headers.get("Authorization"), + ) + ) + + def _respond(self): + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(b'{"ok": true}') + + def do_POST(self): + self._record() + content_length = int(self.headers.get("Content-Length", 0)) + payload = json.loads(self.rfile.read(content_length)) + if payload["event"] == "Redirect": + self.send_response(302) + self.send_header("Location", "/redirected") + self.send_header("Set-Cookie", "server=redirect") + self.end_headers() + return + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Set-Cookie", "server=sequential") + self.end_headers() + self.wfile.write(b'{"ok": true}') + + def do_GET(self): + self._record() + self._respond() + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}", requests_seen + finally: + server.shutdown() + thread.join() + server.server_close() + + @pytest.fixture def audience(): client = Altertable("key", environment="ignored", mode="audience") @@ -64,6 +121,50 @@ def test_track_without_identity(audience): assert payload["properties"] == {"section": "docs", "$url": None, "$referer": None} +def test_audience_transport_does_not_store_or_replay_cookies(cookie_server): + server_url, requests_seen = cookie_server + client = Altertable("key", server_url=server_url, mode="audience") + client.session.headers["Cookie"] = "caller=header" + client.session.headers["Cookie2"] = "caller=legacy-header" + client.session.headers["Authorization"] = "Bearer caller-token" + client.session.cookies.set("caller", "jar", domain="127.0.0.1", path="/") + + client.track("First") + client.track("Second") + + assert requests_seen == [("/track", None, None, None), ("/track", None, None, None)] + assert not list(client.session.cookies) + client.session.close() + + +def test_audience_transport_does_not_replay_redirect_cookies(cookie_server): + server_url, requests_seen = cookie_server + client = Altertable("key", server_url=server_url, mode="audience") + + client.track("Redirect") + + assert requests_seen == [ + ("/track", None, None, None), + ("/redirected", None, None, None), + ] + assert not list(client.session.cookies) + client.session.close() + + +def test_product_transport_keeps_its_cookie_behavior(cookie_server): + server_url, requests_seen = cookie_server + client = Altertable("key", server_url=server_url) + + client.track("First", "user") + client.track("Second", "user") + + assert requests_seen == [ + ("/track", None, None, None), + ("/track", "server=sequential", None, None), + ] + client.session.close() + + def test_single_track_reduces_context_without_mutating_caller(audience): client, adapter = audience options = { @@ -97,6 +198,28 @@ def test_single_track_reduces_context_without_mutating_caller(audience): assert "private-" not in json.dumps(payload) +def test_null_properties_are_normalized_without_mutating_scalar_or_batch_input(audience): + client, adapter = audience + scalar_options = {"properties": None} + batch = [{"event": "Batch", "properties": None}] + original_scalar_options = copy.deepcopy(scalar_options) + original_batch = copy.deepcopy(batch) + + client.track("Scalar", options=scalar_options) + client.track(batch) + + scalar_payload = adapter.payloads[0] + batch_payload = adapter.payloads[1][0] + assert_audience(scalar_payload) + assert_audience(batch_payload) + assert scalar_payload["event"] == "Scalar" + assert batch_payload["event"] == "Batch" + assert scalar_payload["properties"] == {"$url": None, "$referer": None} + assert batch_payload["properties"] == {"$url": None, "$referer": None} + assert scalar_options == original_scalar_options + assert batch == original_batch + + def test_every_batch_event_is_normalized_without_chunking(audience): client, adapter = audience events = [ From 51f6d1d18864f948ccce0e18cf9b85f84a771cca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Mon, 9 Nov 2026 14:31:02 +0100 Subject: [PATCH 4/5] refactor: limit audience mode to the server wire contract Server SDKs do not rewrite $url, $referer, or $viewport and need no audience-specific transport, cookie, redirect, or credential isolation. Drop that code, its tests, the unrelated py.typed marker and formatting churn, and shorten the docs. --- CHANGELOG.md | 2 +- README.md | 38 +--- src/altertable/client.py | 159 +++------------ src/altertable/py.typed | 0 tests/test_audience.py | 429 ++++++++------------------------------- 5 files changed, 114 insertions(+), 514 deletions(-) delete mode 100644 src/altertable/py.typed diff --git a/CHANGELOG.md b/CHANGELOG.md index 9276b35..be00c7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Features -* add audience collection mode with identity suppression, sanitized single and batch events, and cookie- and ambient-credential-isolated transport +* add audience collection mode * **api:** add native server batch overloads and align with client specs v0.13.0 diff --git a/README.md b/README.md index edef79a..a73fc30 100644 --- a/README.md +++ b/README.md @@ -54,45 +54,21 @@ client.track([ ``` Pass arrays to `identify` and `alias` for the same pass-through behavior. -The client owns the collection mode: top-level `mode` fields in product batches -are removed before sending, so a batch cannot switch to audience processing. ### Audience measurement -Use an environment-bound Product Analytics API key and `mode="audience"` to collect events without client identity fields: +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": {"$url": "https://example.com/docs?source=email"}}, -) -audience.track([ - {"event": "Install Copied", "properties": {"package": "python"}}, -]) +audience.track("docs_opened", options={"properties": {"page": "install"}}) ``` -Product mode is the default. Mode is fixed for each client; create a new client to -change it. Audience events omit user, anonymous, device, session, and environment -fields, including caller-supplied batch fields. The API key selects the environment; -legacy unbound keys cannot be used. `identify()` and `alias()` return `None` without -sending requests and emit a `RuntimeWarning` once per client. - -Audience mode removes `$viewport`, reduces `$url` to HTTP(S) origin plus path, and -reduces `$referer` to origin. Invalid URLs become `None`. Custom properties and URL -paths can still contain personal information; choose them accordingly. - -Gate calls on your application's consent decisions. Events are sent synchronously; -failed sends raise `ApiError` or `NetworkError` without automatic retries or replay. -Audience requests do not accept or send cookies, including cookies supplied through -the client's session. To avoid ambient credentials, they also do not use Requests' -environment configuration: `.netrc`, proxy, and CA-bundle environment settings are -ignored. Configure any required proxy or TLS settings directly on `client.session`. - -The backend derives audience visitors from the request IP and User-Agent. For this -server SDK, those identify your server and HTTP client, so these events cannot -reliably measure distinct browser visitors. End-user request headers are not -forwarded automatically. +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 diff --git a/src/altertable/client.py b/src/altertable/client.py index 89996f4..3647869 100644 --- a/src/altertable/client.py +++ b/src/altertable/client.py @@ -1,93 +1,34 @@ import datetime import warnings -from typing import Dict, Any, List, Literal, Optional, Union -from urllib.parse import urlsplit - import requests +from typing import Dict, Any, List, Literal, Optional, Union TrackingMode = Literal["product", "audience"] - -class _AudienceCookieJar(requests.cookies.RequestsCookieJar): - """A cookie jar that neither retains response cookies nor sends supplied ones.""" - - def set_cookie(self, cookie, *args, **kwargs): - return None - - -class _AudienceSession(requests.Session): - """HTTP transport for audience collection, which must not carry credentials.""" - - def __init__(self): - super().__init__() - self.cookies = _AudienceCookieJar() - # requests otherwise obtains basic authentication from a user's .netrc file. - self.trust_env = False - - def send(self, request, **kwargs): - # Session.send runs for the original request and each redirect hop. - for header in ("Cookie", "Cookie2", "Authorization"): - request.headers.pop(header, None) - return super().send(request, **kwargs) - - -def _sanitize_url(value: Any, origin_only: bool = False) -> Optional[str]: - if not isinstance(value, str): - return None - try: - # Reject ambiguous input rather than forwarding potentially sensitive text. - if "\\" in value or any(char.isspace() or ord(char) < 32 for char in value): - return None - url = urlsplit(value) - if url.scheme not in ("http", "https") or not url.hostname: - return None - host = url.hostname.encode("idna").decode("ascii") - if ":" in host: - host = f"[{host}]" - port = url.port - if port is not None and port != (443 if url.scheme == "https" else 80): - host = f"{host}:{port}" - origin = f"{url.scheme}://{host}" - return origin if origin_only else origin + (url.path or "/") - except (ValueError, UnicodeError): - return None - - class AltertableError(Exception): pass - class ApiError(AltertableError): def __init__(self, status: int, message: str, details: Any = None): super().__init__(message) self.status = status self.details = details - class NetworkError(AltertableError): def __init__(self, message: str, cause: Exception): super().__init__(message) self.cause = cause - class Altertable: - def __init__( - self, - api_key: str, - server_url: str = "https://api.altertable.ai", - environment: str = "production", - timeout: int = 10000, - *, - mode: TrackingMode = "product", - ): + 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 omits identity - and environment fields and reduces page context. + :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. """ @@ -99,10 +40,8 @@ def __init__( self.server_url = server_url.rstrip("/") self.environment = environment self.timeout = timeout / 1000.0 - self.session = _AudienceSession() if mode == "audience" else requests.Session() - self.session.headers.update( - {"X-API-Key": self.api_key, "Content-Type": "application/json"} - ) + self.session = requests.Session() + self.session.headers.update({"X-API-Key": self.api_key, "Content-Type": "application/json"}) @property def mode(self) -> TrackingMode: @@ -110,86 +49,49 @@ def mode(self) -> TrackingMode: return self._mode def _ignore_identity(self) -> bool: - if self.mode != "audience": + if self._mode != "audience": return False if not self._identity_warning_emitted: - warnings.warn( - "Altertable identify() and alias() calls are ignored in audience mode.", - RuntimeWarning, - stacklevel=3, - ) + warnings.warn("Altertable identify() and alias() calls are ignored in audience mode.", RuntimeWarning, stacklevel=3) self._identity_warning_emitted = True return True - def _prepare_track(self, payload: Dict[str, Any]) -> Dict[str, Any]: - # The client owns collection policy, including for caller-supplied batches. - if self.mode == "product": + 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"} - properties_value = payload.get("properties", {}) - properties = {} if properties_value is None else dict(properties_value) - properties["$url"] = _sanitize_url(properties.get("$url")) - properties["$referer"] = _sanitize_url( - properties.get("$referer"), origin_only=True - ) - properties.pop("$viewport", None) return { "mode": "audience", "event": payload["event"], "timestamp": self._get_timestamp(payload.get("timestamp")), - "properties": properties, + "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") - ) + return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") if isinstance(timestamp, int): - return ( - datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc) - .isoformat(timespec="milliseconds") - .replace("+00:00", "Z") - ) + return datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") return timestamp - def _post( - self, endpoint: str, payload: Union[Dict[str, Any], List[Dict[str, Any]]] - ): - if endpoint == "/track": - payload = ( - [self._prepare_track(event) for event in payload] - if isinstance(payload, list) - else self._prepare_track(payload) - ) + def _post(self, endpoint: str, payload: Union[Dict[str, Any], List[Dict[str, Any]]]): try: - response = self.session.post( - f"{self.server_url}{endpoint}", json=payload, timeout=self.timeout - ) + response = self.session.post(f"{self.server_url}{endpoint}", json=payload, timeout=self.timeout) if not response.ok: try: error_data = response.json() - raise ApiError( - response.status_code, - error_data.get("message", "API Error"), - error_data, - ) + raise ApiError(response.status_code, error_data.get("message", "API Error"), error_data) except ValueError: raise ApiError(response.status_code, response.text) return response.json() except requests.exceptions.RequestException as e: raise NetworkError("Network request failed", e) - def track( - self, - event: Union[str, List[Dict[str, Any]]], - distinct_id: Optional[str] = None, - options: Optional[Dict[str, Any]] = None, - ): + 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 and self.mode == "product": + 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 {} @@ -198,20 +100,16 @@ def track( "event": event, "environment": options.get("environment", self.environment), "distinct_id": distinct_id, - "properties": options.get("properties", {}), + "properties": options.get("properties", {}) } if "anonymous_id" in options: payload["anonymous_id"] = options["anonymous_id"] if "device_id" in options: payload["device_id"] = options["device_id"] + + return self._post("/track", self._apply_mode(payload)) - return self._post("/track", payload) - - def identify( - self, - distinct_id: Union[str, List[Dict[str, Any]]], - options: Optional[Dict[str, Any]] = None, - ): + 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): @@ -232,12 +130,7 @@ def identify( 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, - ): + 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): diff --git a/src/altertable/py.typed b/src/altertable/py.typed deleted file mode 100644 index e69de29..0000000 diff --git a/tests/test_audience.py b/tests/test_audience.py index dde0da0..19d61a0 100644 --- a/tests/test_audience.py +++ b/tests/test_audience.py @@ -1,408 +1,139 @@ -"""Applicable audience contracts from altertable-js/test/audience.test.ts. - -This server SDK has no browser storage, automatic context, consent queue, hooks, -analytics-source adapters, or built-in retry loop. Inspect serialized requests -through an ordinary HTTP transport adapter, including caller-managed retries. -""" - import copy -import datetime -import json -import threading import warnings -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest.mock import Mock import pytest -import requests -from requests.adapters import BaseAdapter from altertable import Altertable -from altertable.client import ApiError, NetworkError - - -class RecordingAdapter(BaseAdapter): - def __init__(self): - super().__init__() - self.payloads = [] - self.status = 200 - self.error = None - - def send(self, request, **kwargs): - self.payloads.append(json.loads(request.body)) - if self.error: - raise self.error - response = requests.Response() - response.status_code = self.status - response._content = b'{"ok": true}' - return response - - def close(self): - pass - - -@pytest.fixture -def cookie_server(): - requests_seen = [] - - class Handler(BaseHTTPRequestHandler): - def log_message(self, format, *args): - pass - def _record(self): - requests_seen.append( - ( - self.path, - self.headers.get("Cookie"), - self.headers.get("Cookie2"), - self.headers.get("Authorization"), - ) - ) +AUDIENCE_FIELDS = {"mode", "event", "timestamp", "properties"} - def _respond(self): - self.send_response(200) - self.send_header("Content-Type", "application/json") - self.end_headers() - self.wfile.write(b'{"ok": true}') - def do_POST(self): - self._record() - content_length = int(self.headers.get("Content-Length", 0)) - payload = json.loads(self.rfile.read(content_length)) - if payload["event"] == "Redirect": - self.send_response(302) - self.send_header("Location", "/redirected") - self.send_header("Set-Cookie", "server=redirect") - self.end_headers() - return - self.send_response(200) - self.send_header("Content-Type", "application/json") - self.send_header("Set-Cookie", "server=sequential") - self.end_headers() - self.wfile.write(b'{"ok": true}') +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 do_GET(self): - self._record() - self._respond() - server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) - thread = threading.Thread(target=server.serve_forever) - thread.start() - try: - yield f"http://127.0.0.1:{server.server_port}", requests_seen - finally: - server.shutdown() - thread.join() - server.server_close() +def sent_payloads(client): + return [call.kwargs["json"] for call in client.session.post.call_args_list] -@pytest.fixture -def audience(): - client = Altertable("key", environment="ignored", mode="audience") - adapter = RecordingAdapter() - client.session.mount("https://", adapter) - yield client, adapter - client.session.close() - - -def assert_audience(payload): - assert set(payload) == {"mode", "event", "timestamp", "properties"} - assert payload["mode"] == "audience" - datetime.datetime.fromisoformat(payload["timestamp"].replace("Z", "+00:00")) - assert "$viewport" not in payload["properties"] - - -def test_track_without_identity(audience): - client, adapter = audience - assert client.track("Opened", options={"properties": {"section": "docs"}}) == { - "ok": True +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", } - payload = adapter.payloads[0] - assert_audience(payload) - assert payload["properties"] == {"section": "docs", "$url": None, "$referer": None} - - -def test_audience_transport_does_not_store_or_replay_cookies(cookie_server): - server_url, requests_seen = cookie_server - client = Altertable("key", server_url=server_url, mode="audience") - client.session.headers["Cookie"] = "caller=header" - client.session.headers["Cookie2"] = "caller=legacy-header" - client.session.headers["Authorization"] = "Bearer caller-token" - client.session.cookies.set("caller", "jar", domain="127.0.0.1", path="/") - - client.track("First") - client.track("Second") - - assert requests_seen == [("/track", None, None, None), ("/track", None, None, None)] - assert not list(client.session.cookies) - client.session.close() - - -def test_audience_transport_does_not_replay_redirect_cookies(cookie_server): - server_url, requests_seen = cookie_server - client = Altertable("key", server_url=server_url, mode="audience") - - client.track("Redirect") - - assert requests_seen == [ - ("/track", None, None, None), - ("/redirected", None, None, None), - ] - assert not list(client.session.cookies) - client.session.close() - - -def test_product_transport_keeps_its_cookie_behavior(cookie_server): - server_url, requests_seen = cookie_server - client = Altertable("key", server_url=server_url) - - client.track("First", "user") - client.track("Second", "user") - - assert requests_seen == [ - ("/track", None, None, None), - ("/track", "server=sequential", None, None), - ] - client.session.close() - - -def test_single_track_reduces_context_without_mutating_caller(audience): - client, adapter = audience options = { "mode": "product", "environment": "private-env", "anonymous_id": "private-anon", "device_id": "private-device", - "session_id": "private-session", - "timestamp": "2026-11-04T12:00:00.000Z", - "properties": { - "$url": "https://user:password@Site.Example:443/docs?token=secret#hash", - "$referer": "https://search.example/private?token=secret", - "$viewport": "1234x987", - "section": "docs", - "custom_email": "caller@example.com", - }, + "timestamp": "2026-11-09T10:00:00.000Z", + "properties": properties, } original = copy.deepcopy(options) - client.track("Opened", "private-user", options) - payload = adapter.payloads[0] - assert_audience(payload) - assert payload["timestamp"] == options["timestamp"] - assert payload["properties"] == { - "$url": "https://site.example/docs", - "$referer": "https://search.example", - "section": "docs", - "custom_email": "caller@example.com", - } + + 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 - assert "secret" not in json.dumps(payload) - assert "private-" not in json.dumps(payload) -def test_null_properties_are_normalized_without_mutating_scalar_or_batch_input(audience): - client, adapter = audience - scalar_options = {"properties": None} - batch = [{"event": "Batch", "properties": None}] - original_scalar_options = copy.deepcopy(scalar_options) - original_batch = copy.deepcopy(batch) +def test_track_does_not_require_distinct_id(): + client = make_client(mode="audience") - client.track("Scalar", options=scalar_options) - client.track(batch) + client.track("Opened") - scalar_payload = adapter.payloads[0] - batch_payload = adapter.payloads[1][0] - assert_audience(scalar_payload) - assert_audience(batch_payload) - assert scalar_payload["event"] == "Scalar" - assert batch_payload["event"] == "Batch" - assert scalar_payload["properties"] == {"$url": None, "$referer": None} - assert batch_payload["properties"] == {"$url": None, "$referer": None} - assert scalar_options == original_scalar_options - assert batch == original_batch + [payload] = sent_payloads(client) + assert set(payload) == AUDIENCE_FIELDS + assert payload["properties"] == {} -def test_every_batch_event_is_normalized_without_chunking(audience): - client, adapter = audience +def test_raw_batch_cannot_restore_identity_or_select_product_mode(): + client = make_client(mode="audience") events = [ { - "event": f"event-{index}", "mode": "product", - "distinct_id": "private-user", - "anonymous_id": "private-anon", - "device_id": "private-device", - "session_id": "private-session", - "environment": "private-env", - "extra": "private-extra", + "event": "First", "timestamp": 0, - "properties": { - "$url": "https://site.example/docs?email=secret#code", - "$referer": "https://search.example/private?token=secret", - "$viewport": "1234x987", - "section": "docs", - }, - } - for index in range(101) + "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"}, ] - events.append({"event": "Defaults"}) original = copy.deepcopy(events) + client.track(events) - assert len(adapter.payloads) == 1 - assert len(adapter.payloads[0]) == 102 - for payload in adapter.payloads[0]: - assert_audience(payload) - assert adapter.payloads[0][0]["timestamp"] == "1970-01-01T00:00:00.000Z" - assert adapter.payloads[0][0]["properties"] == { - "$url": "https://site.example/docs", - "$referer": "https://search.example", - "section": "docs", + + [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 "private-" not in json.dumps(adapter.payloads) + assert set(batch[1]) == AUDIENCE_FIELDS + assert batch[1]["properties"] == {} assert events == original -@pytest.mark.parametrize( - "value", - [ - "not a URL?token=secret", - "javascript:secret", - "/relative?token=secret", - "https://[invalid", - "https://example.com:invalid/path", - None, - 42, - "https://example.com\\@private/path", - "https://bad host/private", - ], -) -def test_invalid_urls_are_discarded_in_singles_and_batches(audience, value): - client, adapter = audience - properties = {"$url": value, "$referer": value} - client.track("Single", options={"properties": properties}) - client.track([{"event": "Batch", "properties": properties}]) - for payload in [adapter.payloads[0], adapter.payloads[1][0]]: - assert payload["properties"] == {"$url": None, "$referer": None} - +def test_identify_and_alias_are_ignored_and_warn_once(): + client = make_client(mode="audience") -@pytest.mark.parametrize( - "url, expected", - [ - ("https://example.com?secret#hash", "https://example.com/"), - ( - "http://user:password@example.com:8080/path?q#hash", - "http://example.com:8080/path", - ), - ("https://[::1]:443/path?q#hash", "https://[::1]/path"), - ("https://éxample.com/path?q#hash", "https://xn--xample-9ua.com/path"), - ], -) -def test_url_origins_and_paths(audience, url, expected): - client, adapter = audience - client.track("Opened", options={"properties": {"$url": url}}) - assert adapter.payloads[0]["properties"]["$url"] == expected - - -def test_identity_calls_are_ignored_before_validation_and_warn_once(audience): - client, adapter = audience with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter("always") - assert client.identify("user", {"traits": {"email": "secret"}}) is None + 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": "secret"}]) is None - assert len(recorded) == 1 - assert "ignored in audience mode" in str(recorded[0].message) - assert not adapter.payloads - client.track("After identity calls") - assert_audience(adapter.payloads[0]) + assert client.alias([{"distinct_id": "user", "new_user_id": "other"}]) is None + assert [str(warning.message) for warning in recorded] == [ + "Altertable identify() and alias() calls are ignored in audience mode." + ] + client.session.post.assert_not_called() -def test_mode_is_fixed_for_client_lifecycle(audience): - client, adapter = audience - with pytest.raises(AttributeError): - client.mode = "product" + +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.track("Still active") - assert_audience(adapter.payloads[0]) - product = Altertable("key") - product.session.mount("https://", adapter) - product.track("Product", "user") - assert adapter.payloads[1]["distinct_id"] == "user" - assert "mode" not in adapter.payloads[1] - product.session.close() - - -def test_network_failure_is_not_queued_or_replayed_by_new_client(audience): - client, adapter = audience - adapter.error = requests.exceptions.ConnectionError("Offline") - with pytest.raises(NetworkError): - client.track("Offline") - adapter.error = None - other = Altertable("key", mode="audience") - other.session.mount("https://", adapter) - other.track("New client") - assert [payload["event"] for payload in adapter.payloads] == [ - "Offline", - "New client", - ] - for payload in adapter.payloads: - assert_audience(payload) - other.session.close() - - -def test_caller_retry_retains_audience_policy(audience): - client, adapter = audience - event = {"event": "Retry", "distinct_id": "private", "mode": "product"} - adapter.status = 503 - with pytest.raises(ApiError) as exc: - client.track([event]) - assert exc.value.status == 503 - assert len(adapter.payloads) == 1 # No implicit retry loop. - adapter.status = 200 - client.track([event]) - for batch in adapter.payloads: - assert_audience(batch[0]) - - -@pytest.mark.parametrize("mode", ["product", None]) -def test_product_tracking_preserves_context_and_requires_identity(mode): - client = Altertable( - "key", environment="staging", **({"mode": mode} if mode else {}) - ) - adapter = RecordingAdapter() - client.session.mount("https://", adapter) - with pytest.raises(TypeError, match="distinct_id is required"): - client.track("Missing identity") - properties = {"$url": "https://example.com/?secret#hash", "$viewport": "100x200"} - client.track( - "Product", - "user", - {"properties": properties, "anonymous_id": "anon", "device_id": "device"}, - ) - payload = adapter.payloads[0] - assert payload["distinct_id"] == "user" - assert payload["anonymous_id"] == "anon" - assert payload["device_id"] == "device" - assert payload["environment"] == "staging" - assert payload["properties"] == properties - assert "mode" not in payload - client.session.close() + 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_processing(): - client = Altertable("key") - adapter = RecordingAdapter() - client.session.mount("https://", adapter) +def test_product_batch_cannot_select_audience_mode(): + client = make_client() event = { - "event": "Product", "mode": "audience", + "event": "Product", "distinct_id": "user", - "environment": "staging", "properties": {"mode": "business-value"}, } + client.track([event]) - assert adapter.payloads == [ - [{key: value for key, value in event.items() if key != "mode"}] + + assert sent_payloads(client) == [ + [{"event": "Product", "distinct_id": "user", "properties": {"mode": "business-value"}}] ] assert event["mode"] == "audience" - client.session.close() From 0d59dac15e2e6d90e20ac84eafc0f3bdf7d8c51d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Mon, 9 Nov 2026 15:40:51 +0100 Subject: [PATCH 5/5] refactor: ignore audience identity calls without warnings --- src/altertable/client.py | 9 +-------- tests/test_audience.py | 9 +++------ 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/src/altertable/client.py b/src/altertable/client.py index 3647869..a80bbe6 100644 --- a/src/altertable/client.py +++ b/src/altertable/client.py @@ -1,5 +1,4 @@ import datetime -import warnings import requests from typing import Dict, Any, List, Literal, Optional, Union @@ -35,7 +34,6 @@ def __init__(self, api_key: str, server_url: str = "https://api.altertable.ai", if mode not in ("product", "audience"): raise ValueError('Invalid tracking mode. Use "product" or "audience".') self._mode: TrackingMode = mode - self._identity_warning_emitted = False self.api_key = api_key self.server_url = server_url.rstrip("/") self.environment = environment @@ -49,12 +47,7 @@ def mode(self) -> TrackingMode: return self._mode def _ignore_identity(self) -> bool: - if self._mode != "audience": - return False - if not self._identity_warning_emitted: - warnings.warn("Altertable identify() and alias() calls are ignored in audience mode.", RuntimeWarning, stacklevel=3) - self._identity_warning_emitted = True - return True + 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 diff --git a/tests/test_audience.py b/tests/test_audience.py index 19d61a0..ece98e2 100644 --- a/tests/test_audience.py +++ b/tests/test_audience.py @@ -95,19 +95,16 @@ def test_raw_batch_cannot_restore_identity_or_select_product_mode(): assert events == original -def test_identify_and_alias_are_ignored_and_warn_once(): +def test_identify_and_alias_are_ignored_silently(): client = make_client(mode="audience") - with warnings.catch_warnings(record=True) as recorded: - warnings.simplefilter("always") + 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 - assert [str(warning.message) for warning in recorded] == [ - "Altertable identify() and alias() calls are ignored in audience mode." - ] client.session.post.assert_not_called()