Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(browserbase): sync agents, agent runs, project usage and session logs (#100159)

Tom Owers877cd22eab0b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index fd1b12750977..70ea2441a1ec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -980,14 +980,14 @@ Note: developer.brex.com serves an SPA (the openapi.json URLs return HTML), but
## Browserbase — **thin**
-Today (2): `projects`, `sessions`
+Today (6): `agent_runs`, `agents`, `project_usage`, `projects`, `session_logs`, `sessions`
Diffed against: <https://docs.browserbase.com/reference/api/openapi.v1.yaml>
-- [ ] `GET /v1/projects/{id}/usage` — browser minutes and proxy bytes per project — the vendor's headline consumption metric and the basis for cost analysis (high)
-- [ ] `GET /v1/sessions/{id}/logs` — per-session request/action log lines; the event-grain data behind every session (high)
-- [ ] `GET /v1/agents/runs` — agent run outcomes, status and duration — the core analytical object of the agent platform (high)
-- [ ] `GET /v1/agents` — lookup resolving the agentId referenced by every run (high)
+- [x] `GET /v1/projects/{id}/usage` — browser minutes and proxy bytes per project — the vendor's headline consumption metric and the basis for cost analysis (high)
+- [x] `GET /v1/sessions/{id}/logs` — per-session request/action log lines; the event-grain data behind every session (high)
+- [x] `GET /v1/agents/runs` — agent run outcomes, status and duration — the core analytical object of the agent platform (high)
+- [x] `GET /v1/agents` — lookup resolving the agentId referenced by every run (high)
- [ ] `GET /v1/agents/runs/{runId}/messages` — per-run message transcript, the step-level detail under a run (medium)
- [ ] `GET /v1/contexts` — lookup resolving the contextId (persistent browser profile) attached to sessions (medium)
- [ ] `GET /v1/functions and GET /v1/functions/versions/{id}/invocations` — deployed function inventory plus per-invocation records for reliability and cost analysis (medium)
@@ -996,7 +996,7 @@ Diffed against: <https://docs.browserbase.com/reference/api/openapi.v1.yaml>
- [ ] `GET /v1/functions/builds and /v1/functions/builds/{id}/logs` — build history and failure diagnostics for deployed functions (low)
- [ ] `GET /v1/sessions/{id}/uploads` — files pushed into a session, completing the session artifact picture (low)
-Note: Fetched the official OpenAPI v1 spec (124KB, 38 paths). The connector exposes only /v1/projects and /v1/sessions — two of roughly a dozen queryable resources. Browserbase has since expanded well beyond sessions into agents/runs and functions/invocations, none of which are represented.
+Note: Fetched the official OpenAPI v1 spec (124KB, 38 paths). The agent platform (/v1/agents and /v1/agents/runs), per-project usage and per-session logs are now synced. What remains is the functions control plane, session artifacts (downloads, uploads, replays) and the contexts lookup. Every Browserbase endpoint is full refresh: only the agent endpoints accept a time filter, and it filters on creation time while the rows keep changing afterwards.
## BrowserUse — adequate
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/browserbase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/browserbase.py
index a0fc45c7cea7..96827235fb40 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/browserbase.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/browserbase.py
@@ -1,11 +1,30 @@
+from collections.abc import Callable, Iterable
+from typing import Any, cast
+
import requests
-from products.warehouse_sources.backend.temporal.data_imports.sources.browserbase.settings import BROWSERBASE_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.browserbase.settings import (
+ BROWSERBASE_ENDPOINTS,
+ CURSOR_PARAM,
+ CURSOR_PATH,
+ MAX_PAGE_SIZE,
+ BrowserbaseEndpointConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ BasePaginator,
+ ClientConfig,
+ Endpoint,
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+ SinglePagePaginator,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -13,10 +32,10 @@ BROWSERBASE_BASE_URL = "https://api.browserbase.com/v1"
def _make_session(api_key: str) -> requests.Session:
- # `redact_values` masks the key in tracked logs/samples. `capture=False` keeps response bodies out
- # of HTTP sample storage — session objects carry arbitrary `userMetadata` (and projects can carry
- # other customer-defined fields) that the name-based sample scrubbers can't recognise. Requests
- # are still metered and logged (status + url).
+ # `redact_values` masks the key in tracked logs/samples. `capture=False` keeps response bodies
+ # out of HTTP sample storage — session objects carry arbitrary `userMetadata` (and session logs
+ # carry the raw CDP request/response bodies of whatever the browser did) that the name-based
+ # sample scrubbers can't recognise. Requests are still metered and logged (status + url).
return make_tracked_session(redact_values=(api_key,), capture=False)
@@ -31,42 +50,91 @@ def validate_credentials(api_key: str) -> bool:
return ok
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": BROWSERBASE_BASE_URL,
+ "headers": {"Accept": "application/json"},
+ # Framework auth (not a hand-built header) so the key is redacted wherever it surfaces.
+ "auth": {"type": "api_key", "name": "X-BB-API-Key", "api_key": api_key, "location": "header"},
+ "session": _make_session(api_key),
+ }
+
+
+def _paginator_for(config: BrowserbaseEndpointConfig) -> BasePaginator:
+ if config.paginated:
+ return JSONResponseCursorPaginator(cursor_path=CURSOR_PATH, cursor_param=CURSOR_PARAM)
+ # The rest of Browserbase's list endpoints take no pagination, page, or cursor params, so a
+ # single request yields the whole collection.
+ return SinglePagePaginator()
+
+
+def _endpoint_extra(config: BrowserbaseEndpointConfig) -> Endpoint:
+ extra: Endpoint = {
+ "paginator": _paginator_for(config),
+ # The row list is the whole body (or the envelope's `data` key); anything else is an
+ # unexpected/error shape. Fail loud instead of finishing "successfully" with zero rows.
+ # An endpoint that answers with a single object has no list to check.
+ "data_selector_required": not config.returns_object,
+ }
+ if config.data_selector:
+ extra["data_selector"] = config.data_selector
+ return extra
+
+
+def _make_source_response(config: BrowserbaseEndpointConfig, items: Callable[[], Iterable[Any]]) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=items,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
def browserbase_source(api_key: str, endpoint: str, team_id: int, job_id: str) -> SourceResponse:
endpoint_config = BROWSERBASE_ENDPOINTS[endpoint]
+ if endpoint_config.fanout:
+ parent_config = BROWSERBASE_ENDPOINTS[endpoint_config.fanout.parent_name]
+ dependent_resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=BROWSERBASE_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=endpoint_config.fanout,
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ # Neither the fan-out parents nor their children accept a page-size param.
+ page_size_param=None,
+ parent_endpoint_extra=_endpoint_extra(parent_config),
+ child_endpoint_extra=_endpoint_extra(endpoint_config),
+ ),
+ )
+ return _make_source_response(endpoint_config, lambda: dependent_resource)
+
+ resource_endpoint: Endpoint = {
+ "path": endpoint_config.path,
+ **_endpoint_extra(endpoint_config),
+ }
+ if endpoint_config.paginated:
+ resource_endpoint["params"] = {"limit": MAX_PAGE_SIZE}
+
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": BROWSERBASE_BASE_URL,
- "headers": {"Accept": "application/json"},
- # Framework auth (not a hand-built header) so the key is redacted wherever it surfaces.
- "auth": {"type": "api_key", "name": "X-BB-API-Key", "api_key": api_key, "location": "header"},
- # Browserbase list endpoints return a plain JSON array with no pagination, page, or cursor
- # params, so a single request yields the whole collection.
- "paginator": "single_page",
- "session": _make_session(api_key),
- },
+ "client": _client_config(api_key),
"resources": [
{
"name": endpoint,
- "endpoint": {
- "path": endpoint_config.path,
- # The whole body is the row list; a non-list success body is an unexpected/error
- # shape. Fail loud instead of finishing "successfully" with zero rows.
- "data_selector_required": True,
- },
+ "endpoint": resource_endpoint,
}
],
}
resource = rest_api_resource(rest_config, team_id, job_id, None)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- primary_keys=endpoint_config.primary_keys,
- partition_count=1,
- partition_size=1,
- partition_mode="datetime" if endpoint_config.partition_key else None,
- partition_format="month" if endpoint_config.partition_key else None,
- partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
- )
+ return _make_source_response(endpoint_config, lambda: resource)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/canonical_descriptions.py
index 70d7a487df0e..c95a8ee57faa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/canonical_descriptions.py
@@ -39,4 +39,59 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"concurrency": "Maximum number of concurrent sessions allowed for the project.",
},
},
+ "agents": {
+ "description": "A reusable agent definition, referenced by `agentId` to apply a system prompt "
+ "to every run that uses it.",
+ "docs_url": "https://docs.browserbase.com/reference/api/list-agents",
+ "columns": {
+ "agentId": "Unique identifier for the agent. Used as `agentId` when creating an agent run.",
+ "name": "Human-readable name for the agent.",
+ "systemPrompt": "System prompt applied to every run that uses this agent.",
+ "resultSchema": "JSON Schema that runs referencing this agent aim to conform their result to.",
+ "createdAt": "Timestamp when the agent was created.",
+ "updatedAt": "Timestamp when the agent was last updated.",
+ },
+ },
+ "agent_runs": {
+ "description": "One execution of an agent against a task, transitioned through its statuses by the runner.",
+ "docs_url": "https://docs.browserbase.com/reference/api/list-runs",
+ "columns": {
+ "runId": "Unique identifier for the run.",
+ "agentId": "Identifier of the agent applied to this run. Omitted for ad-hoc runs.",
+ "task": "The original task description the run was given.",
+ "status": "Current status of the run (PENDING, RUNNING, COMPLETED, FAILED, STOPPED, or TIMED_OUT).",
+ "sessionId": "Identifier of the Browserbase session powering this run.",
+ "sandboxId": "External sandbox identifier assigned by the runner.",
+ "resultSchema": "Per-run JSON Schema override for the result shape.",
+ "result": "The agent's structured result, present once the run has finished with output.",
+ "cause": "Structured failure code and human-readable detail for a run that did not succeed.",
+ "startedAt": "Timestamp when the run started.",
+ "endedAt": "Timestamp when the run ended.",
+ "createdAt": "Timestamp when the run was created.",
+ "updatedAt": "Timestamp when the run was last updated.",
+ },
+ },
+ "project_usage": {
+ "description": "Consumption totals for a project, read once per project at sync time.",
+ "docs_url": "https://docs.browserbase.com/reference/api/get-project-usage",
+ "columns": {
+ "projectId": "Identifier of the project the totals were read for.",
+ "browserMinutes": "Total browser minutes consumed by the project.",
+ "proxyBytes": "Total number of bytes transferred through the Browserbase proxy by the project.",
+ },
+ },
+ "session_logs": {
+ "description": "A single Chrome DevTools Protocol message recorded during a browser session.",
+ "docs_url": "https://docs.browserbase.com/reference/api/get-session-logs",
+ "columns": {
+ "sessionId": "Identifier of the session the log line belongs to.",
+ "pageId": "Identifier of the page within the session that produced the log line.",
+ "method": "Name of the DevTools Protocol method that was called.",
+ "timestamp": "Milliseconds since the Unix epoch when the log line was recorded.",
+ "frameId": "Identifier of the frame the method ran against.",
+ "loaderId": "Identifier of the page load the method ran under.",
+ "request": "The outgoing message: its timestamp, params, and raw body.",
+ "response": "The returned message: its timestamp, result, and raw body.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/settings.py
index 61842d2ee9dd..ab78b3fd662a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/settings.py
@@ -1,21 +1,49 @@
from dataclasses import dataclass, field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField
+# The agent endpoints wrap their rows in `data` and hand back the next page token in
+# `nextCursor`, which is fed back as `cursor`.
+CURSOR_PATH = "nextCursor"
+CURSOR_PARAM = "cursor"
-@dataclass
+# Largest `limit` those endpoints accept, so a sync makes as few round trips as it can.
+MAX_PAGE_SIZE = 1000
+
+
+@dataclass(frozen=True)
class BrowserbaseEndpointConfig:
name: str
path: str
# Field to partition Delta files by. Must be a stable creation-time timestamp so a row never
# moves between partitions (Browserbase mutates `updatedAt`/`endedAt`, so those are unsafe).
partition_key: str | None = None
- # Incremental cursor candidates. Left empty for every Browserbase endpoint: the list endpoints
- # expose no server-side timestamp filter (only `status`/`q` on sessions), so an "incremental"
- # sync would still fetch the whole collection each run. Full refresh is the honest strategy.
+ # Incremental cursor candidates. Left empty for every Browserbase endpoint. The session,
+ # project and log endpoints expose no server-side timestamp filter at all. The agent
+ # endpoints do accept `startAt`/`endAt`, but both filter on *creation* time while the rows
+ # keep changing after creation — a run walks PENDING to RUNNING to COMPLETED, and an agent's
+ # prompt can be edited — so a creation-time cursor would freeze every row at the state it
+ # had when it was first seen. Full refresh is the honest strategy.
incremental_fields: list[IncrementalField] = field(default_factory=list)
primary_keys: list[str] = field(default_factory=lambda: ["id"])
should_sync_default: bool = True
+ # jsonpath to the row list, for the endpoints that wrap rows in an envelope. None where the
+ # whole response body is the rows.
+ data_selector: str | None = None
+ # True for the endpoints that take `cursor`/`limit`. The rest return the whole collection in
+ # one response and accept no paging params.
+ paginated: bool = False
+ # `/projects/{id}/usage` answers with a single object rather than a row list, so the
+ # fail-loud list-shape check does not apply to it.
+ returns_object: bool = False
+ # Read only by the fan-out helper's protocol. Browserbase's fan-out parents and children take
+ # no page-size param, so no request ever sends it.
+ page_size: int = MAX_PAGE_SIZE
+ default_incremental_field: str | None = None
+ fanout: DependentEndpointConfig | None = None
BROWSERBASE_ENDPOINTS: dict[str, BrowserbaseEndpointConfig] = {
@@ -31,6 +59,58 @@ BROWSERBASE_ENDPOINTS: dict[str, BrowserbaseEndpointConfig] = {
partition_key="createdAt",
primary_keys=["id"],
),
+ "agents": BrowserbaseEndpointConfig(
+ name="agents",
+ path="/agents",
+ partition_key="createdAt",
+ primary_keys=["agentId"],
+ data_selector="data",
+ paginated=True,
+ ),
+ "agent_runs": BrowserbaseEndpointConfig(
+ name="agent_runs",
+ path="/agents/runs",
+ partition_key="createdAt",
+ primary_keys=["runId"],
+ data_selector="data",
+ paginated=True,
+ ),
+ "project_usage": BrowserbaseEndpointConfig(
+ name="project_usage",
+ path="/projects/{project_id}/usage",
+ # The usage body is a bare {browserMinutes, proxyBytes} object with no id and no
+ # timestamp: the project it was read for is the whole key, and there is nothing stable
+ # to partition on.
+ primary_keys=["projectId"],
+ returns_object=True,
+ fanout=DependentEndpointConfig(
+ parent_name="projects",
+ resolve_param="project_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "projectId"},
+ ),
+ ),
+ "session_logs": BrowserbaseEndpointConfig(
+ name="session_logs",
+ path="/sessions/{session_id}/logs",
+ # Log lines carry no id of their own, so a CDP message is identified by the session and
+ # page it ran on, its method, and when it fired. `timestamp` is epoch milliseconds rather
+ # than a datetime, so it cannot serve as a partition key.
+ primary_keys=["sessionId", "pageId", "method", "timestamp"],
+ # One request per session, over a session list the API returns unpaginated, with the raw
+ # CDP request and response bodies in every row. Too heavy to turn on for everyone.
+ should_sync_default=False,
+ fanout=DependentEndpointConfig(
+ parent_name="sessions",
+ resolve_param="session_id",
+ resolve_field="id",
+ # Log rows already carry `sessionId`, but copying the parent id down under the same
+ # name keeps the primary key intact even for a row that omits it.
+ include_from_parent=["id"],
+ parent_field_renames={"id": "sessionId"},
+ ),
+ ),
}
ENDPOINTS = tuple(BROWSERBASE_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/source.py
index e1eb29ab5ae0..b648c0115097 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/source.py
@@ -98,8 +98,9 @@ You can find your project API key in your [Browserbase dashboard](https://www.br
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Every Browserbase list endpoint is full refresh: there is no server-side timestamp filter,
- # so nothing can be synced incrementally (see settings.py).
+ # Every Browserbase endpoint is full refresh: either no server-side timestamp filter exists,
+ # or the only one on offer filters on creation time over rows that keep changing after they
+ # are created (see settings.py).
return build_endpoint_schemas(
ENDPOINTS,
INCREMENTAL_FIELDS,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/tests/test_browserbase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/tests/test_browserbase.py
index 7f9b208da5e1..5d870250f2eb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/tests/test_browserbase.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/tests/test_browserbase.py
@@ -13,7 +13,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.browserbas
browserbase_source,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.browserbase.settings import ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClient,
RESTClientRetryableError,
@@ -84,15 +83,22 @@ class TestGetRows:
assert _rows(browserbase_source("bb_key", "sessions", team_id=1, job_id="j")) == []
+ @parameterized.expand(
+ [
+ ("bare_list_endpoint", "sessions", "Required a list response body"),
+ ("enveloped_endpoint", "agents", "matched nothing in the response"),
+ ]
+ )
@mock.patch(SESSION_PATCH)
- def test_non_list_response_raises(self, MockSession) -> None:
- # Browserbase list endpoints return arrays; a dict means an unexpected/error shape. Raise so
- # the sync fails loudly instead of finishing "successfully" with zero rows.
+ def test_unexpected_response_shape_raises(self, _name: str, endpoint: str, message: str, MockSession) -> None:
+ # Browserbase answers either with a bare array or with rows under `data`; neither shape is
+ # present here. Raise so the sync fails loudly instead of finishing "successfully" with
+ # zero rows.
session = MockSession.return_value
_wire(session, [_response(200, {"statusCode": 500})])
- with pytest.raises(ValueError, match="Required a list response body"):
- _rows(browserbase_source("bb_key", "sessions", team_id=1, job_id="j"))
+ with pytest.raises(ValueError, match=message):
+ _rows(browserbase_source("bb_key", endpoint, team_id=1, job_id="j"))
@mock.patch(SESSION_PATCH)
def test_requests_the_endpoint_path(self, MockSession) -> None:
@@ -205,14 +211,90 @@ class TestValidateCredentials:
assert validate_credentials("bb_key") is False
+class TestCursorPagination:
+ @mock.patch(SESSION_PATCH)
+ def test_follows_next_cursor_until_it_is_null(self, MockSession) -> None:
+ # Without the cursor wired to `nextCursor`/`cursor` a sync silently stops after one page.
+ session = MockSession.return_value
+ prepared = _wire(
+ session,
+ [
+ _response(200, {"data": [{"runId": "run_1"}], "limit": 1000, "nextCursor": "cur_2"}),
+ _response(200, {"data": [{"runId": "run_2"}], "limit": 1000, "nextCursor": None}),
+ ],
+ )
+
+ rows = _rows(browserbase_source("bb_key", "agent_runs", team_id=1, job_id="j"))
+
+ assert rows == [{"runId": "run_1"}, {"runId": "run_2"}]
+ assert session.send.call_count == 2
+ assert "cursor=" not in (prepared[0].url or "")
+ assert "cursor=cur_2" in (prepared[1].url or "")
+ # Ask for the largest page the endpoint allows, so a sync makes as few round trips as it can.
+ assert "limit=1000" in (prepared[0].url or "")
+
+
+class TestFanout:
+ @mock.patch(SESSION_PATCH)
+ def test_project_usage_yields_one_row_per_project_keyed_by_project(self, MockSession) -> None:
+ # The usage body is a bare object with no id of its own, so without the parent id copied
+ # down the table has no key and no way to tell whose usage a row is.
+ session = MockSession.return_value
+ prepared = _wire(
+ session,
+ [
+ _response(200, [{"id": "proj_1"}, {"id": "proj_2"}]),
+ _response(200, {"browserMinutes": 12, "proxyBytes": 345}),
+ _response(200, {"browserMinutes": 67, "proxyBytes": 890}),
+ ],
+ )
+
+ rows = _rows(browserbase_source("bb_key", "project_usage", team_id=1, job_id="j"))
+
+ assert rows == [
+ {"browserMinutes": 12, "proxyBytes": 345, "projectId": "proj_1"},
+ {"browserMinutes": 67, "proxyBytes": 890, "projectId": "proj_2"},
+ ]
+ assert prepared[1].url == f"{BROWSERBASE_BASE_URL}/projects/proj_1/usage"
+ assert prepared[2].url == f"{BROWSERBASE_BASE_URL}/projects/proj_2/usage"
+
+ @mock.patch(SESSION_PATCH)
+ def test_session_logs_fan_out_binds_the_session_id(self, MockSession) -> None:
+ session = MockSession.return_value
+ prepared = _wire(
+ session,
+ [
+ _response(200, [{"id": "sess_1"}]),
+ _response(200, [{"sessionId": "sess_1", "pageId": 1, "method": "Page.navigate"}]),
+ ],
+ )
+
+ rows = _rows(browserbase_source("bb_key", "session_logs", team_id=1, job_id="j"))
+
+ assert rows == [{"sessionId": "sess_1", "pageId": 1, "method": "Page.navigate"}]
+ assert prepared[1].url == f"{BROWSERBASE_BASE_URL}/sessions/sess_1/logs"
+
+
class TestBrowserbaseSource:
- @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
+ @parameterized.expand(
+ [
+ ("sessions", ["id"], "createdAt"),
+ ("projects", ["id"], "createdAt"),
+ ("agents", ["agentId"], "createdAt"),
+ ("agent_runs", ["runId"], "createdAt"),
+ # Fan-out children carry no id of their own, so the parent id is part of the key.
+ ("project_usage", ["projectId"], None),
+ ("session_logs", ["sessionId", "pageId", "method", "timestamp"], None),
+ ]
+ )
@mock.patch(SESSION_PATCH)
- def test_source_response_shape(self, endpoint: str, MockSession) -> None:
+ def test_source_response_shape(
+ self, endpoint: str, primary_keys: list[str], partition_key: str | None, MockSession
+ ) -> None:
response = browserbase_source("bb_key", endpoint, team_id=1, job_id="j")
assert response.name == endpoint
- assert response.primary_keys == ["id"]
+ assert response.primary_keys == primary_keys
# Partition on the stable creation timestamp, never updatedAt.
- assert response.partition_keys == ["createdAt"]
- assert response.partition_mode == "datetime"
+ assert response.partition_keys == ([partition_key] if partition_key else None)
+ assert response.partition_mode == ("datetime" if partition_key else None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/tests/test_browserbase_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/tests/test_browserbase_source.py
index 010adc0aa1de..d87b10ff04dd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/tests/test_browserbase_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browserbase/tests/test_browserbase_source.py
@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.browserbas
browserbase,
source as source_module,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.browserbase.settings import ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.browserbase.source import BrowserbaseSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.browserbase import (
BrowserbaseSourceConfig,
@@ -47,22 +48,31 @@ class TestBrowserbaseSourceConfig:
class TestBrowserbaseSchemas:
- @parameterized.expand([("sessions",), ("projects",)])
+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
def test_every_endpoint_is_full_refresh_only(self, endpoint: str) -> None:
- # No Browserbase list endpoint exposes a server-side timestamp filter, so nothing can sync
- # incrementally - guarding against a future edit flipping this on without a real filter.
+ # No Browserbase endpoint exposes a usable incremental cursor: most have no server-side
+ # timestamp filter at all, and the agent endpoints only filter on creation time over rows
+ # that keep changing afterwards. Guards against a future edit flipping this on.
schema = next(s for s in BrowserbaseSource().get_schemas(_config(), team_id=1) if s.name == endpoint)
assert schema.supports_incremental is False
assert schema.supports_append is False
assert schema.incremental_fields == []
+ def test_session_logs_is_not_enabled_by_default(self) -> None:
+ # One request per session over an unpaginated session list, carrying raw CDP bodies - it
+ # must not be force-enabled by one-shot source creation.
+ by_name = {s.name: s for s in BrowserbaseSource().get_schemas(_config(), team_id=1)}
+
+ assert by_name["session_logs"].should_sync_default is False
+ assert by_name["sessions"].should_sync_default is True
+
def test_documented_tables_render_for_public_docs(self) -> None:
# lists_tables_without_credentials=True means the public docs <SourceTables /> is fed here.
tables = BrowserbaseSource().get_documented_tables()
by_name = {t["name"]: t for t in tables}
- assert set(by_name) == {"sessions", "projects"}
+ assert set(by_name) == set(ENDPOINTS)
assert by_name["sessions"]["description"]
assert by_name["sessions"]["sync_methods"] == ["Full refresh"]