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(warehouse-sources): add honeycomb board views and slo counts history (#111305)

Tom Owers9cfd0d343b49
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 1c9b131e358c..41c081778341 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
@@ -4099,14 +4099,14 @@ Note: Static endpoint list; source dir products/warehouse_sources/backend/tempor
## Honeycomb — gaps
-Today (9): `boards`, `burn_alerts`, `columns`, `datasets`, `derived_columns`, `markers`, `recipients`, `slos`, `triggers`
+Today (11): `board_views`, `boards`, `burn_alerts`, `columns`, `datasets`, `derived_columns`, `markers`, `recipients`, `slo_counts_history`, `slos`, `triggers`
Diffed against: <https://api-docs.honeycomb.io/api/openapi-public.yaml>
-- [ ] `/1/slos/{datasetSlug}/{sloId}/counts/history` — hourly SLI good/bad event counts - the data behind SLO compliance and burn, and we already sync slos (high)
-- [ ] `/1/slos/{datasetSlug}/{sloId}/counts` — current SLO budget/compliance counts, Honeycomb's headline reliability metric (high)
-- [ ] `/2/teams/{teamSlug}/environments` — lookup table for the environments that own the datasets we already sync (high)
-- [ ] `/1/boards/{boardId}/views` — the views that make up each board we sync - board content is otherwise opaque (medium)
+- [x] `/1/slos/{datasetSlug}/{sloId}/counts/history` — hourly SLI good/bad event counts - the data behind SLO compliance and burn, and we already sync slos (high). Added as `slo_counts_history` (incremental on `start_time`; Enterprise plan only, off by default).
+- [ ] `/1/slos/{datasetSlug}/{sloId}/counts` — current SLO budget/compliance counts, Honeycomb's headline reliability metric (high). Skipped: it returns per-minute deltas for the current clock hour only, a realtime feed rather than a table; `slo_counts_history` holds the same counts per hour.
+- [ ] `/2/teams/{teamSlug}/environments` — lookup table for the environments that own the datasets we already sync (high). Skipped: it is a v2 Management API endpoint that needs a management key and a team slug, and the source authenticates with an environment-scoped configuration key.
+- [x] `/1/boards/{boardId}/views` — the views that make up each board we sync - board content is otherwise opaque (medium). Added as `board_views` (fan-out over `boards`).
- [ ] `/1/dataset_definitions/{datasetSlug}` — lookup mapping dataset definition types (duration, trace id, span kind) to actual column names (medium)
- [ ] `/1/recipients/{recipientId}/triggers` — join table between recipients and triggers, both of which we already sync (medium)
- [ ] `/1/reporting/slos/historical` — weekly historical SLO breakdown across multiple SLOs in one call (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/canonical_descriptions.py
index 9a1d954858e8..838f7b434239 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/canonical_descriptions.py
@@ -125,4 +125,27 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "When the recipient was last modified.",
},
},
+ "board_views": {
+ "description": "A saved view on a board: a named set of filters applied to every query on the board.",
+ "docs_url": "https://api-docs.honeycomb.io/api/boards",
+ "columns": {
+ "id": "Unique identifier for the board view.",
+ "board_id": "ID of the board the view belongs to (added by PostHog during sync).",
+ "name": "Name of the view.",
+ "filters": "The filters the view applies, each with a column, an operation, and an optional value.",
+ },
+ },
+ "slo_counts_history": {
+ "description": "Hourly total and error event counts for an SLO, the data behind its compliance and budget burn.",
+ "docs_url": "https://api-docs.honeycomb.io/api/slos",
+ "columns": {
+ "slo_id": "ID of the SLO the counts belong to (added by PostHog during sync).",
+ "dataset_slug": "Slug of the dataset the SLO was listed under (added by PostHog during sync).",
+ "start_time": "Start of the hour as a Unix timestamp in seconds.",
+ "end_time": "End of the hour as a Unix timestamp in seconds.",
+ "total_count": "Total number of events (good and bad) in the hour.",
+ "error_count": "Number of failed (bad) events in the hour.",
+ "is_partial": "Whether the bucket covers the in-progress hour; its counts keep growing until the hour completes.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/honeycomb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/honeycomb.py
index 858419f4565f..f4fd66f86a1e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/honeycomb.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/honeycomb.py
@@ -1,6 +1,8 @@
import dataclasses
from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
from typing import Any
+from urllib.parse import urlencode
import requests
from structlog.types import FilteringBoundLogger
@@ -38,12 +40,22 @@ SAFE_RECIPIENT_TARGET_TYPES = frozenset({"email", "slack"})
ENDPOINTS_WITH_CREDENTIAL_PAYLOADS = frozenset({"recipients", "triggers", "burn_alerts"})
REDACTED_VALUE = "[REDACTED]"
+# How far back a full refresh (or the first incremental sync) reads SLO hourly counts.
+SLO_COUNTS_HISTORY_LOOKBACK = timedelta(days=90)
+# Each counts-history request covers one window per SLO; a week is 168 hourly buckets.
+SLO_COUNTS_HISTORY_WINDOW = timedelta(days=7)
+SECONDS_PER_HOUR = 3600
+
class HoneycombRetryableError(Exception):
pass
+class HoneycombSloCountsUnavailableError(Exception):
+ pass
+
+
[email protected](frozen=True)
class HoneycombResumeConfig:
# The fan-out dataset currently being processed, bookmarked by its stable slug (not a
# positional index) so datasets created/deleted between a crash and the retry can't resume
@@ -51,6 +63,8 @@ class HoneycombResumeConfig:
# rows may not have been durably flushed — and merge dedupes on the primary key. None for
# environment-level endpoints, which are a single request with nothing to resume.
dataset_slug: str | None = None
+ # The same bookmark for the board views fan-out, which walks boards instead of datasets.
+ board_id: str | None = None
def _get_headers(api_key: str) -> dict[str, str]:
@@ -120,6 +134,41 @@ def _fetch_list_skipping_missing(
raise
+def _fetch_slo_counts_buckets(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> list[dict[str, Any]] | None:
+ """Fetch one SLO's hourly count buckets, or None on 404 (SLO deleted, or feature off)."""
+ try:
+ data = _fetch_page(session, url, headers, logger).json()
+ except requests.HTTPError as exc:
+ if exc.response is not None and exc.response.status_code == 404:
+ return None
+ raise
+ buckets = data.get("buckets") if isinstance(data, dict) else None
+ return buckets if isinstance(buckets, list) else []
+
+
+def _to_epoch_seconds(value: Any) -> int | None:
+ """Normalise a persisted watermark (int epoch, datetime, or string) to epoch seconds."""
+ if value is None or isinstance(value, bool):
+ return None
+ if isinstance(value, int | float):
+ return int(value)
+ if isinstance(value, datetime):
+ return int((value if value.tzinfo else value.replace(tzinfo=UTC)).timestamp())
+ if isinstance(value, str):
+ try:
+ return int(value)
+ except ValueError:
+ pass
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return int((parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)).timestamp())
+ return None
+
+
def _sanitize_recipient(recipient: dict[str, Any]) -> dict[str, Any]:
"""Redact credential-bearing fields from a recipient object (full or embedded form)."""
sanitized = dict(recipient)
@@ -214,12 +263,91 @@ def _iter_fan_out(
manager.save_state(HoneycombResumeConfig(dataset_slug=dataset_slug))
+def _iter_board_views(
+ session: requests.Session,
+ base_url: str,
+ headers: dict[str, str],
+ config: HoneycombEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[HoneycombResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk every board and emit its views as one batch, bookmarking progress by board id."""
+ board_ids = [board["id"] for board in _fetch_list(session, f"{base_url}/1/boards", headers, logger)]
+
+ resume = manager.load_state() if manager.can_resume() else None
+ start_index = 0
+ if resume is not None and resume.board_id is not None and resume.board_id in board_ids:
+ start_index = board_ids.index(resume.board_id)
+ logger.debug(f"Honeycomb: resuming {config.name} fan-out from board={resume.board_id}")
+
+ for board_id in board_ids[start_index:]:
+ url = f"{base_url}{config.path.format(board_id=board_id)}"
+ items = _fetch_list_skipping_missing(session, url, headers, logger)
+ if not items:
+ continue
+ yield [{**item, "board_id": board_id} for item in items]
+ manager.save_state(HoneycombResumeConfig(board_id=board_id))
+
+
+def _iter_slo_counts_history(
+ session: requests.Session,
+ base_url: str,
+ headers: dict[str, str],
+ config: HoneycombEndpointConfig,
+ logger: FilteringBoundLogger,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Emit hourly SLO count buckets, one batch per time window across every SLO.
+
+ Windows are the outer loop so each batch's max `start_time` never goes backwards, which
+ keeps the ascending incremental watermark safe to checkpoint after every batch. The
+ watermark hour itself is re-read: the latest bucket is often `is_partial` and keeps
+ growing until the hour completes, and merge on the primary key replaces it."""
+ now = int(datetime.now(UTC).timestamp())
+ floor = now - int(SLO_COUNTS_HISTORY_LOOKBACK.total_seconds())
+ watermark = _to_epoch_seconds(db_incremental_field_last_value)
+ # The lookback also floors the watermark: a non-epoch value (e.g. a user-picked count
+ # column) would otherwise walk decades of empty windows, one request per SLO each.
+ start = floor if watermark is None else max(watermark, floor)
+ start -= start % SECONDS_PER_HOUR
+
+ slos: list[tuple[str, str]] = []
+ for dataset_slug in _list_dataset_slugs(session, base_url, headers, logger):
+ for slo in _fetch_list_skipping_missing(session, f"{base_url}/1/slos/{dataset_slug}", headers, logger):
+ slos.append((dataset_slug, slo["id"]))
+
+ window_seconds = int(SLO_COUNTS_HISTORY_WINDOW.total_seconds())
+ window_start = start
+ while window_start < now:
+ window_end = min(window_start + window_seconds, now)
+ query = urlencode({"start_time": window_start, "end_time": window_end})
+ rows: list[dict[str, Any]] = []
+ found_any = False
+ for dataset_slug, slo_id in slos:
+ url = f"{base_url}{config.path.format(dataset_slug=dataset_slug, slo_id=slo_id)}?{query}"
+ buckets = _fetch_slo_counts_buckets(session, url, headers, logger)
+ if buckets is None:
+ continue
+ found_any = True
+ rows.extend({**bucket, "dataset_slug": dataset_slug, "slo_id": slo_id} for bucket in buckets)
+ # One deleted SLO 404s on its own; every SLO 404ing means the endpoint is off for this
+ # team, which must fail loudly rather than finish as an empty sync.
+ if slos and not found_any and window_start == start:
+ raise HoneycombSloCountsUnavailableError(
+ "Honeycomb SLO counts history is unavailable for this API key: every SLO returned 404"
+ )
+ if rows:
+ yield rows
+ window_start = window_end
+
+
def get_rows(
api_key: str,
region: str,
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[HoneycombResumeConfig],
+ db_incremental_field_last_value: Any = None,
) -> Iterator[list[dict[str, Any]]]:
config = HONEYCOMB_ENDPOINTS[endpoint]
base_url = _base_url(region)
@@ -237,6 +365,14 @@ def get_rows(
yield [_sanitize_row(config.name, row) for row in rows]
return
+ if config.scope == HoneycombScope.PER_BOARD:
+ yield from _iter_board_views(session, base_url, headers, config, logger, resumable_source_manager)
+ return
+
+ if config.scope == HoneycombScope.PER_SLO_TIME_WINDOW:
+ yield from _iter_slo_counts_history(session, base_url, headers, config, logger, db_incremental_field_last_value)
+ return
+
yield from _iter_fan_out(session, base_url, headers, config, logger, resumable_source_manager)
@@ -246,6 +382,7 @@ def honeycomb_source(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[HoneycombResumeConfig],
+ db_incremental_field_last_value: Any = None,
) -> SourceResponse:
endpoint_config = HONEYCOMB_ENDPOINTS[endpoint]
@@ -257,6 +394,7 @@ def honeycomb_source(
endpoint=endpoint,
logger=logger,
resumable_source_manager=resumable_source_manager,
+ db_incremental_field_last_value=db_incremental_field_last_value,
),
primary_keys=endpoint_config.primary_keys,
partition_count=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/settings.py
index 1c732d7ba314..f1f3c14597c1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/settings.py
@@ -2,7 +2,7 @@ from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
-from products.warehouse_sources.backend.types import IncrementalField
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
class HoneycombScope(Enum):
@@ -12,7 +12,8 @@ class HoneycombScope(Enum):
environment-wide collections returned in a single request (datasets, boards, recipients);
most are addressed per dataset (columns, triggers, SLOs, markers, …), so fetching those
tables means fanning out one request per dataset. Burn alerts go one level deeper: they
- are listed per SLO, so the fan-out walks datasets -> SLOs -> burn alerts.
+ are listed per SLO, so the fan-out walks datasets -> SLOs -> burn alerts. Board views are
+ listed per board.
"""
# Environment-wide collection returned by a single static path (GET /1/datasets).
@@ -21,14 +22,19 @@ class HoneycombScope(Enum):
PER_DATASET = "per_dataset"
# Fan out over every SLO in every dataset (GET /1/burn_alerts/{dataset_slug}?slo_id=…).
PER_SLO = "per_slo"
+ # Fan out over every SLO in every dataset, one request per SLO per time window
+ # (GET /1/slos/{dataset_slug}/{slo_id}/counts/history?start_time=…&end_time=…).
+ PER_SLO_TIME_WINDOW = "per_slo_time_window"
+ # Fan out over every board in the environment (GET /1/boards/{board_id}/views).
+ PER_BOARD = "per_board"
-@dataclass
+@dataclass(frozen=False)
class HoneycombEndpointConfig:
name: str
scope: HoneycombScope
- # Path template. PER_DATASET and PER_SLO paths contain ``{dataset_slug}``; ENVIRONMENT
- # paths are static.
+ # Path template. Dataset fan-out paths contain ``{dataset_slug}`` (and ``{slo_id}`` for
+ # PER_SLO_TIME_WINDOW), PER_BOARD paths contain ``{board_id}``; ENVIRONMENT paths are static.
path: str
# Primary key columns used for merge dedup. For fan-out children the dataset slug is
# included (and injected into every row) so the key stays unique across the whole table —
@@ -43,7 +49,8 @@ class HoneycombEndpointConfig:
# than any real dataset, so skipping it would silently drop them.
include_environment_wide: bool = False
# The menu of incremental cursor candidates advertised to the user. Empty = full refresh
- # only — none of Honeycomb's v1 config endpoints expose a server-side timestamp filter.
+ # only — Honeycomb's v1 config endpoints expose no server-side timestamp filter; only the
+ # SLO counts history takes a start_time/end_time range.
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Whether the table is selected for sync by default in the connection wizard.
should_sync_default: bool = True
@@ -116,6 +123,33 @@ HONEYCOMB_ENDPOINTS: dict[str, HoneycombEndpointConfig] = {
primary_keys=["id"],
partition_key="created_at",
),
+ "board_views": HoneycombEndpointConfig(
+ name="board_views",
+ scope=HoneycombScope.PER_BOARD,
+ path="/1/boards/{board_id}/views",
+ # View ids are only documented per board, so the injected board id is part of the key.
+ # Views carry no creation timestamp, so the table is unpartitioned.
+ primary_keys=["id", "board_id"],
+ ),
+ "slo_counts_history": HoneycombEndpointConfig(
+ name="slo_counts_history",
+ scope=HoneycombScope.PER_SLO_TIME_WINDOW,
+ path="/1/slos/{dataset_slug}/{slo_id}/counts/history",
+ # One bucket per SLO per hour. `start_time` is a Unix epoch integer; the pipeline
+ # partitions on integer epochs directly.
+ primary_keys=["slo_id", "dataset_slug", "start_time"],
+ partition_key="start_time",
+ incremental_fields=[
+ {
+ "label": "start_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "start_time",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ # Enterprise-only and enabled per team on request, so most keys get a 403/404 here.
+ should_sync_default=False,
+ ),
}
ENDPOINTS = tuple(HONEYCOMB_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/source.py
index fa37ca385d18..0e87c655dabb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/source.py
@@ -95,6 +95,7 @@ Keys are region-specific — pick the region that matches your Honeycomb account
"401 Client Error: Unauthorized for url: https://api.eu1.honeycomb.io": "Your Honeycomb API key is invalid, revoked, or for a different region. Create a configuration key in your Honeycomb environment settings, then reconnect.",
"403 Client Error: Forbidden for url: https://api.honeycomb.io": "Your Honeycomb API key is missing a permission needed to sync this data. Grant the matching access (e.g. Manage SLOs, Manage Triggers) on the key, then reconnect.",
"403 Client Error: Forbidden for url: https://api.eu1.honeycomb.io": "Your Honeycomb API key is missing a permission needed to sync this data. Grant the matching access (e.g. Manage SLOs, Manage Triggers) on the key, then reconnect.",
+ "Honeycomb SLO counts history is unavailable": "Honeycomb SLO counts history needs the Enterprise plan, with the feature turned on for your team by Honeycomb. Ask your Honeycomb account team to turn it on, or stop syncing the slo_counts_history table.",
}
def get_canonical_descriptions(self) -> CanonicalDescriptions:
@@ -122,17 +123,23 @@ Keys are region-specific — pick the region that matches your Honeycomb account
)
if endpoint_config.scope is HoneycombScope.PER_SLO:
return "One row per burn alert per dataset, fetched by walking every dataset's SLOs."
+ if endpoint_config.scope is HoneycombScope.PER_SLO_TIME_WINDOW:
+ return (
+ "Hourly good and bad event counts per SLO. Requires the Honeycomb Enterprise plan "
+ "with SLO counts history enabled for your team."
+ )
if endpoint_config.include_environment_wide:
return "Includes environment-wide rows under the __all__ dataset slug alongside per-dataset rows."
return None
def _build_schema(endpoint: str) -> SourceSchema:
endpoint_config = HONEYCOMB_ENDPOINTS[endpoint]
- # Full refresh only: Honeycomb's v1 config endpoints expose no server-side
- # timestamp filter, so a client-side cursor would still walk every row each run.
+ # Only endpoints with a server-side time filter advertise incremental fields; the
+ # config endpoints have none, so a client-side cursor would still walk every row.
+ # Append stays off: the latest SLO counts bucket is partial and must be merged.
return SourceSchema(
name=endpoint,
- supports_incremental=False,
+ supports_incremental=bool(endpoint_config.incremental_fields),
supports_append=False,
incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
should_sync_default=endpoint_config.should_sync_default,
@@ -169,4 +176,7 @@ Keys are region-specific — pick the region that matches your Honeycomb account
endpoint=inputs.schema_name,
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
+ db_incremental_field_last_value=(
+ inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb.py
index 713cad9d34c6..89864667ee6d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb.py
@@ -3,6 +3,7 @@ from collections.abc import Mapping
from typing import Any
import pytest
+import time_machine
from unittest.mock import MagicMock
import requests
@@ -13,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb
from products.warehouse_sources.backend.temporal.data_imports.sources.honeycomb.honeycomb import (
HoneycombResumeConfig,
HoneycombRetryableError,
+ HoneycombSloCountsUnavailableError,
_base_url,
_get_headers,
get_rows,
@@ -239,6 +241,159 @@ class TestBurnAlertFanOut:
assert rows == [{"id": "ba1", "dataset_slug": "prod", "slo_id": "slo1"}]
+class TestBoardViewFanOut:
+ def test_walks_boards_injects_board_id_and_skips_deleted_board(self, monkeypatch: Any) -> None:
+ lists: dict[str, Any] = {
+ f"{US}/1/boards": [{"id": "b1"}, {"id": "gone"}, {"id": "b2"}],
+ f"{US}/1/boards/b1/views": [{"id": "v1", "name": "Errors"}],
+ f"{US}/1/boards/gone/views": _not_found(f"{US}/1/boards/gone/views"),
+ f"{US}/1/boards/b2/views": [{"id": "v1", "name": "Slow"}],
+ }
+ manager = _FakeResumableManager()
+ rows = _collect("board_views", lists, manager, monkeypatch)
+ assert rows == [
+ {"id": "v1", "name": "Errors", "board_id": "b1"},
+ {"id": "v1", "name": "Slow", "board_id": "b2"},
+ ]
+ assert [state.board_id for state in manager.saved] == ["b1", "b2"]
+
+ def test_resume_refetches_bookmarked_board_and_skips_earlier(self, monkeypatch: Any) -> None:
+ lists = {
+ f"{US}/1/boards": [{"id": "b1"}, {"id": "b2"}],
+ f"{US}/1/boards/b2/views": [{"id": "v2"}],
+ }
+ manager = _FakeResumableManager(HoneycombResumeConfig(board_id="b2"))
+ rows = _collect("board_views", lists, manager, monkeypatch)
+ assert rows == [{"id": "v2", "board_id": "b2"}]
+
+
+class _UrlSession:
+ """Serves canned JSON bodies (or a status code) per URL, recording the URLs requested."""
+
+ def __init__(self, responses: Mapping[str, Any]) -> None:
+ self._responses = responses
+ self.requested_urls: list[str] = []
+
+ def get(self, url: str, headers: dict[str, str] | None = None, timeout: int | None = None) -> requests.Response:
+ self.requested_urls.append(url)
+ if url not in self._responses:
+ raise AssertionError(f"unexpected URL requested: {url}")
+ result = self._responses[url]
+ if isinstance(result, int):
+ return _make_response(result, body={"error": "not found"})
+ return _make_response(200, body=result)
+
+
+# 2026-01-15T12:30:00Z — mid-hour, so the hour alignment of the window start is exercised.
+NOW = 1768480200
+HOUR = 3600
+DAY = 24 * HOUR
+
+
+def _bucket(start: int, **extra: Any) -> dict[str, Any]:
+ return {"start_time": start, "end_time": start + HOUR, "total_count": 10, "error_count": 1, **extra}
+
+
+def _collect_counts_history(
+ responses: Mapping[str, Any], last_value: Any, monkeypatch: Any
+) -> tuple[list[list[dict]], _UrlSession]:
+ session = _UrlSession(responses)
+ monkeypatch.setattr(honeycomb, "make_tracked_session", lambda *args, **kwargs: session)
+ with time_machine.travel(NOW, tick=False):
+ batches = list(
+ get_rows(
+ api_key="key",
+ region="us",
+ endpoint="slo_counts_history",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ db_incremental_field_last_value=last_value,
+ )
+ )
+ return batches, session
+
+
+def _history_url(dataset_slug: str, slo_id: str, start: int, end: int) -> str:
+ return f"{US}/1/slos/{dataset_slug}/{slo_id}/counts/history?start_time={start}&end_time={end}"
+
+
+class TestSloCountsHistory:
+ @parameterized.expand(
+ [
+ ("no_watermark", None),
+ # A watermark from a non-epoch column must not walk back to 1970.
+ ("watermark_older_than_lookback", 84513),
+ ]
+ )
+ def test_walks_lookback_in_weekly_windows_across_every_slo(self, _name: str, last_value: Any) -> None:
+ aligned_now = NOW - NOW % HOUR
+ first_start = aligned_now - 90 * DAY
+ window_starts = list(range(first_start, NOW, 7 * DAY))
+ responses: dict[str, Any] = {
+ f"{US}/1/datasets": [{"slug": "prod"}, {"slug": "gone"}],
+ f"{US}/1/slos/prod": [{"id": "slo1"}, {"id": "slo2"}],
+ f"{US}/1/slos/gone": 404,
+ }
+ for start in window_starts:
+ end = min(start + 7 * DAY, NOW)
+ responses[_history_url("prod", "slo1", start, end)] = {"slo_id": "slo1", "buckets": [_bucket(start)]}
+ # A deleted SLO 404s; that must drop its rows, not fail the sync.
+ responses[_history_url("prod", "slo2", start, end)] = 404
+
+ # parameterized.expand can't also receive the `monkeypatch` fixture, so manage our own.
+ with pytest.MonkeyPatch.context() as mp:
+ batches, session = _collect_counts_history(responses, last_value, mp)
+
+ assert len(batches) == len(window_starts)
+ assert batches[0] == [{**_bucket(first_start), "dataset_slug": "prod", "slo_id": "slo1"}]
+ # Every window is requested, and the last one ends at "now" rather than in the future.
+ assert session.requested_urls[-1] == _history_url("prod", "slo2", window_starts[-1], NOW)
+
+ @parameterized.expand(
+ [
+ ("int_epoch", NOW - 2 * HOUR - 600),
+ ("iso_string", "2026-01-15T10:20:00+00:00"),
+ ]
+ )
+ def test_incremental_rereads_watermark_hour_and_batches_all_slos_per_window(
+ self, _name: str, last_value: Any
+ ) -> None:
+ watermark_hour = NOW - NOW % HOUR - 2 * HOUR
+ responses: dict[str, Any] = {
+ f"{US}/1/datasets": [{"slug": "prod"}, {"slug": "api"}],
+ f"{US}/1/slos/prod": [{"id": "slo1"}],
+ f"{US}/1/slos/api": [{"id": "slo2"}],
+ _history_url("prod", "slo1", watermark_hour, NOW): {
+ "buckets": [_bucket(watermark_hour), _bucket(watermark_hour + HOUR, is_partial=True)]
+ },
+ _history_url("api", "slo2", watermark_hour, NOW): {"buckets": [_bucket(watermark_hour)]},
+ }
+ # parameterized.expand can't also receive the `monkeypatch` fixture, so manage our own.
+ with pytest.MonkeyPatch.context() as mp:
+ batches, _ = _collect_counts_history(responses, last_value, mp)
+
+ # One batch per window holding every SLO, so the batch max start_time never regresses
+ # and the ascending watermark can be checkpointed after each batch.
+ assert batches == [
+ [
+ {**_bucket(watermark_hour), "dataset_slug": "prod", "slo_id": "slo1"},
+ {**_bucket(watermark_hour + HOUR, is_partial=True), "dataset_slug": "prod", "slo_id": "slo1"},
+ {**_bucket(watermark_hour), "dataset_slug": "api", "slo_id": "slo2"},
+ ]
+ ]
+
+ def test_every_slo_404ing_fails_instead_of_syncing_empty(self, monkeypatch: Any) -> None:
+ watermark_hour = NOW - NOW % HOUR
+ responses: dict[str, Any] = {
+ f"{US}/1/datasets": [{"slug": "prod"}],
+ f"{US}/1/slos/prod": [{"id": "slo1"}, {"id": "slo2"}],
+ _history_url("prod", "slo1", watermark_hour, NOW): 404,
+ _history_url("prod", "slo2", watermark_hour, NOW): 404,
+ }
+ with pytest.raises(HoneycombSloCountsUnavailableError):
+ _collect_counts_history(responses, watermark_hour, monkeypatch)
+
+
class TestRecipientCredentialScrubbing:
"""Recipient payloads carry live credentials (PagerDuty integration keys, webhook signing
secrets, webhook / MS Teams capability URLs). Dropping the sanitization would hand those to
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb_source.py
index 63b8b89bed92..79435c178d21 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/honeycomb/tests/test_honeycomb_source.py
@@ -50,11 +50,12 @@ class TestHoneycombSource:
schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id)
assert {s.name for s in schemas} == set(ENDPOINTS)
- def test_all_schemas_are_full_refresh(self) -> None:
+ def test_only_slo_counts_history_is_incremental(self) -> None:
# Honeycomb's v1 config endpoints have no server-side timestamp filter, so advertising
# incremental would silently re-walk history every run while claiming a delta sync.
+ # Append stays off everywhere: the latest SLO counts bucket is partial and must merge.
for schema in self.source.get_schemas(MagicMock(), team_id=self.team_id):
- assert schema.supports_incremental is False, schema.name
+ assert schema.supports_incremental is (schema.name == "slo_counts_history"), schema.name
assert schema.supports_append is False, schema.name
def test_get_schemas_filters_by_names(self) -> None:
@@ -122,6 +123,10 @@ class TestHoneycombSource:
non_retryable = self.source.get_non_retryable_errors()
assert any(key in observed_error for key in non_retryable)
+ def test_unavailable_slo_counts_history_is_non_retryable(self) -> None:
+ observed = "Honeycomb SLO counts history is unavailable for this API key: every SLO returned 404"
+ assert any(key in observed for key in self.source.get_non_retryable_errors())
+
@parameterized.expand(
[
("rate_limited", "429 Client Error: Too Many Requests for url: https://api.honeycomb.io/1/datasets"),