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.

fix(warehouse-sources): stop Shortcut stories sync importing nothing (#91212)

posthog[bot]69dcd8ddae13
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/api_inventory.md
index 2daa91f6a6ac..dd0213da0530 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/api_inventory.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/api_inventory.md
@@ -40,17 +40,31 @@ key) and `updated_at`.
There is **no top-level `GET /stories`** list endpoint. Stories are fetched via **`POST /stories/search`**
("Query Stories"), which accepts structured server-side filters including `created_at_start` /
-`updated_at_start` and returns a **plain JSON array of `StorySlim`** (no pagination wrapper, no documented
-result cap). We map the user's chosen incremental field to the matching `*_start` filter.
+`updated_at_start` and returns a **plain JSON array of `StorySlim`** (no pagination wrapper). We map the
+user's chosen incremental field to the matching `*_start` filter.
- Incremental field options: `updated_at` (default) and `created_at`.
- Partition key: `created_at`.
-**Revisit with a live token:** confirm that (a) `updated_at_start` actually filters server-side rather than
-being silently ignored, and (b) the accepted date format (we send RFC 3339 `...Z`). If the filter is
-ignored, the sync still produces correct data (merge dedupes on `id`) but every run refetches all stories.
-For very large workspaces, a future improvement is to window `POST /stories/search` by `created_at` ranges,
-since the endpoint exposes no pagination.
+**An empty body returns zero stories.** The request must carry at least one filter, so every request sets a
+`created_at_start` floor — an epoch floor (`1970-01-01T00:00:00Z`) on full refresh and the first incremental
+run, or the real cursor when the user picks `created_at` incremental.
+
+**`StorySlim` omits `description` unless asked.** The field is optional in the response schema, so every request
+sets `includes_description: true` to get the `description` column the canonical schema advertises.
+
+**The endpoint documents no result cap, no result order, and no pagination.**
+The v3 OpenAPI spec gives `POST /stories/search` (`queryStories`) an empty parameter list and a bare `StorySlim` array response.
+The "first 1000 matches" limit and the ranking-decay ordering note belong to the separate `GET /search/stories` endpoint, so neither is assumed here.
+We read stories in closed `created_at_start` / `created_at_end` windows instead, which relies only on filters the spec documents:
+a response with `STORY_SEARCH_SPLIT_THRESHOLD` or more stories is treated as possibly truncated and its window is split in half and fetched again;
+once every window is fetched, the largest accepted windows are fetched again in halves, and when the halves hold more distinct stories than the parent response did, the endpoint truncated at that count and the threshold drops to it.
+Row order never matters. Neighbouring windows overlap by a second or two, so no story is lost whether either bound is inclusive or exclusive, and `_dedupe_pages_by_id` drops stories read twice.
+A window under three seconds wide cannot split; if it still hits the threshold, the sync logs a warning that stories in those seconds may be missing.
+
+**Revisit with a live token:** confirm that (a) `updated_at_start` filters server-side rather than being
+silently ignored, (b) the accepted date format (we send RFC 3339 `...Z`), and (c) whether the `created_at_*`
+bounds are inclusive (the windows overlap either way, so this only affects request count).
## Webhooks (deferred)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/shortcut.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/shortcut.py
index 0374e8a98427..dbf41dfa0784 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/shortcut.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/shortcut.py
@@ -1,6 +1,12 @@
-from datetime import UTC, date, datetime
+import logging
+from collections.abc import Iterable, Iterator
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional, cast
+from requests import Request, Response
+
+from posthog.dataclasses import frozen
+
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 (
EndpointResource,
@@ -8,17 +14,36 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
rest_api_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
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
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.shortcut.settings import (
SHORTCUT_ENDPOINTS,
ShortcutEndpointConfig,
)
+logger = logging.getLogger(__name__)
+
SHORTCUT_BASE_URL = "https://api.app.shortcut.com/api/v3"
+# `POST /stories/search` returns nothing for an empty body, so full refresh and the first
+# incremental run send this created_at floor to match every story. It is also the start of the
+# first created_at window the paginator fetches.
+STORY_SEARCH_EPOCH_START = "1970-01-01T00:00:00Z"
+
+# `POST /stories/search` returns a bare array and documents no result cap, no result order, and no
+# pagination. The paginator therefore never trusts one response to be complete. A response with at
+# least this many stories is treated as possibly truncated, and its created_at window is split in
+# two and fetched again. The value only sets how eagerly windows split: completeness does not
+# depend on it, because the paginator also re-fetches the largest accepted windows in halves and
+# lowers this threshold when the halves hold more stories than the parent did.
+STORY_SEARCH_SPLIT_THRESHOLD = 1000
+
+_SEARCH_TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
+_EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
+
def _base_headers() -> dict[str, str]:
# The Shortcut-Token credential is supplied via the framework api_key auth (location="header"),
@@ -30,12 +55,23 @@ def _format_incremental_value(value: Any) -> str:
"""Format an incremental cursor value for Shortcut's `*_start` search filters (RFC 3339)."""
if isinstance(value, datetime):
utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
- return utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+ return utc_dt.strftime(_SEARCH_TIMESTAMP_FORMAT)
if isinstance(value, date):
return value.strftime("%Y-%m-%d")
return str(value)
+def _parse_search_timestamp(value: Any) -> datetime | None:
+ """Read a `created_at_start` filter back into an aware UTC datetime, or None if it is not one."""
+ if not isinstance(value, str):
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
+
+
def _build_search_body(
config: ShortcutEndpointConfig,
should_use_incremental_field: bool,
@@ -44,18 +80,232 @@ def _build_search_body(
) -> dict[str, Any]:
"""Build the JSON body for `POST /stories/search`.
- Maps the user-selected incremental field to the matching server-side filter param.
- An empty body returns the full collection (initial sync / full refresh).
+ Maps the user-selected incremental field to the matching server-side filter param, and
+ always sets a created_at floor so the body is never empty — an empty body makes the
+ endpoint return zero stories on full refresh and the first incremental run.
"""
body: dict[str, Any] = {}
+ # GET list endpoints carry no request body.
+ if config.method != "POST":
+ return body
if should_use_incremental_field and db_incremental_field_last_value is not None:
field_name = incremental_field or "updated_at"
param = config.incremental_params.get(field_name)
if param:
body[param] = _format_incremental_value(db_incremental_field_last_value)
+ # An epoch floor matches every story; a real created_at cursor above overrides it.
+ body.setdefault("created_at_start", STORY_SEARCH_EPOCH_START)
+ # StorySlim omits the description unless asked; the canonical schema advertises the column.
+ body["includes_description"] = True
return body
+class _SplitCheck:
+ """One verification split: the parent's story count, and what its two halves return."""
+
+ def __init__(self, parent_count: int) -> None:
+ self.parent_count = parent_count
+ self.ids: set[Any] = set()
+ self.halves: list[tuple[_CreatedAtWindow, int]] = []
+
+ @property
+ def complete(self) -> bool:
+ return len(self.halves) == 2
+
+ @property
+ def proves_truncation(self) -> bool:
+ # A complete parent response holds every story of both halves, so the halves cannot add
+ # up to more than it. Boundary re-reads are counted once through the id set.
+ return len(self.ids) > self.parent_count
+
+
+@frozen
+class _CreatedAtWindow:
+ """A closed `created_at` range sent as `created_at_start` / `created_at_end`."""
+
+ start: datetime
+ end: datetime
+ # Set when this window is one half of a verification split.
+ check: _SplitCheck | None = None
+
+ def halves(self, check: _SplitCheck | None = None) -> list["_CreatedAtWindow"] | None:
+ """Split around the midpoint second, or return None when the window is too narrow to split.
+
+ The halves overlap by one second on each side of the midpoint, so no story is lost whether
+ the endpoint treats either bound as inclusive or exclusive. Stories in the overlap are read
+ twice; `_dedupe_pages_by_id` drops the second copy.
+ """
+ span_seconds = int((self.end - self.start).total_seconds())
+ if span_seconds < 3:
+ return None
+ midpoint = self.start + timedelta(seconds=span_seconds // 2)
+ return [
+ _CreatedAtWindow(start=self.start, end=midpoint + timedelta(seconds=1), check=check),
+ _CreatedAtWindow(start=midpoint, end=self.end, check=check),
+ ]
+
+
+class StoriesSearchPaginator(BasePaginator):
+ """Read every story from `POST /stories/search` without trusting an undocumented cap or order.
+
+ The endpoint returns a bare array with no pagination. It documents neither how many stories a
+ response holds at most nor the order they come in, so this paginator only relies on the
+ `created_at_start` / `created_at_end` filters and on story ids:
+
+ - Each request covers one closed `created_at` window. The first window runs from the body's
+ `created_at_start` floor to the moment the sync started.
+ - A response with at least `split_threshold` stories may be truncated. Its window is split in
+ two and both halves are fetched. A window under three seconds wide cannot split; it is
+ kept and a warning is logged.
+ - Once every window is fetched, the accepted windows with the most stories are fetched again in
+ halves. If the halves hold more distinct stories than the parent response did, the endpoint
+ truncated at the parent's count. The threshold drops to that count and every accepted window
+ at or above it is split again. A half that returns as many stories as its parent is verified
+ in turn, so a truncated parent whose stories all sit in one half cannot pass.
+
+ Row order never matters, and the threshold only sets how many requests a large workspace costs.
+ Stories created after the sync started are picked up by the next run.
+ """
+
+ def __init__(
+ self,
+ primary_key: str = "id",
+ split_threshold: int = STORY_SEARCH_SPLIT_THRESHOLD,
+ now: datetime | None = None,
+ ) -> None:
+ super().__init__()
+ self._primary_key = primary_key
+ self._threshold = split_threshold
+ end = (now or datetime.now(UTC)).replace(microsecond=0)
+ self._current = _CreatedAtWindow(start=_EPOCH, end=max(_EPOCH, end))
+ self._pending: list[_CreatedAtWindow] = []
+ # Windows fetched in full with the distinct story count each returned. Only these can be
+ # split again when the threshold drops; unsplittable windows are not kept.
+ self._accepted: list[tuple[_CreatedAtWindow, int]] = []
+ self._verified_largest = False
+
+ def init_request(self, request: Request) -> None:
+ body = request.json if isinstance(request.json, dict) else {}
+ floor = _parse_search_timestamp(body.get("created_at_start")) or _EPOCH
+ self._current = _CreatedAtWindow(start=floor, end=max(floor, self._current.end))
+ self._apply_window(request, self._current)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ window = self._current
+ rows = data or []
+ ids = {row.get(self._primary_key) for row in rows if isinstance(row, dict)}
+ ids.discard(None)
+ count = len(ids)
+
+ if count >= self._threshold:
+ self._split(window)
+ else:
+ self._accepted.append((window, count))
+ if window.check is not None:
+ self._record_half(window, count, ids)
+ if not self._pending and not self._verified_largest:
+ self._verified_largest = True
+ self._verify_largest_windows()
+ self._has_next_page = bool(self._pending)
+
+ def update_request(self, request: Request) -> None:
+ if not self._pending:
+ return
+ self._current = self._pending.pop()
+ self._apply_window(request, self._current)
+
+ def _apply_window(self, request: Request, window: _CreatedAtWindow) -> None:
+ body = request.json if isinstance(request.json, dict) else {}
+ body["created_at_start"] = _format_incremental_value(window.start)
+ body["created_at_end"] = _format_incremental_value(window.end)
+ request.json = body
+
+ def _split(self, window: _CreatedAtWindow) -> None:
+ halves = window.halves()
+ if halves is None:
+ logger.warning(
+ "Shortcut stories/search returned at least %s stories created between %s and %s; the window cannot "
+ "be split further, so some stories in it may be missing",
+ self._threshold,
+ _format_incremental_value(window.start),
+ _format_incremental_value(window.end),
+ )
+ return
+ self._pending.extend(halves)
+
+ def _verify_window(self, window: _CreatedAtWindow, count: int) -> None:
+ halves = window.halves(check=_SplitCheck(count))
+ if halves is None:
+ logger.warning(
+ "Shortcut stories/search returned %s stories created between %s and %s; the window cannot be split "
+ "to confirm the response was complete",
+ count,
+ _format_incremental_value(window.start),
+ _format_incremental_value(window.end),
+ )
+ return
+ self._accepted = [(accepted, n) for accepted, n in self._accepted if accepted is not window]
+ self._pending.extend(halves)
+
+ def _verify_largest_windows(self) -> None:
+ largest = max((count for _, count in self._accepted), default=0)
+ if largest == 0:
+ return
+ for window, count in list(self._accepted):
+ if count == largest:
+ self._verify_window(window, count)
+
+ def _record_half(self, window: _CreatedAtWindow, count: int, ids: set[Any]) -> None:
+ check = window.check
+ if check is None:
+ return
+ check.ids |= ids
+ check.halves.append((window, count))
+ if not check.complete:
+ return
+ if check.proves_truncation:
+ self._lower_threshold(check.parent_count)
+ return
+ # A half that returned every story of its parent proves nothing yet. Verify it in turn,
+ # unless the threshold has since dropped and the rule above already split it.
+ for half, half_count in check.halves:
+ if half_count == check.parent_count and half_count < self._threshold:
+ self._verify_window(half, half_count)
+
+ def _lower_threshold(self, cap: int) -> None:
+ if cap >= self._threshold:
+ return
+ logger.info("Shortcut stories/search truncates responses at %s stories; splitting windows at that size", cap)
+ self._threshold = cap
+ truncated = [(window, count) for window, count in self._accepted if count >= cap]
+ self._accepted = [(window, count) for window, count in self._accepted if count < cap]
+ for window, _ in truncated:
+ self._split(window)
+
+
+def _dedupe_pages_by_id(pages: Iterable[Any], primary_key: str) -> Iterator[list[dict[str, Any]]]:
+ """Drop stories re-read across window boundaries so no id lands in the table twice.
+
+ Neighbouring `created_at` windows overlap by a second or two, and a window fetched again in
+ halves repeats every story of the parent response. Full refresh appends without the merge's
+ primary-key dedup (that runs only for incremental writes), so drop the re-read rows here. Keyed
+ on the unique story id, so it never drops a distinct story whatever order the endpoint returns
+ rows in. Holds the seen ids for one sync, bounded by the story count.
+ """
+ seen: set[Any] = set()
+ for page in pages:
+ fresh: list[dict[str, Any]] = []
+ for row in page:
+ key = row.get(primary_key)
+ if key is not None and key in seen:
+ continue
+ if key is not None:
+ seen.add(key)
+ fresh.append(row)
+ if fresh:
+ yield fresh
+
+
def shortcut_source(
api_token: str,
endpoint: str,
@@ -75,9 +325,8 @@ def shortcut_source(
"data_selector_required": True,
}
if config.method == "POST":
- # Shortcut's stories/search carries its server-side timestamp filter in the POST body (not the
- # query string), so the incremental value is baked into the static request body here. The value
- # is known up front (single un-paginated request), so no per-page cursor injection is needed.
+ # Shortcut's stories/search carries its server-side timestamp filters in the POST body (not the
+ # query string). This seeds the first window; the paginator sets the created_at bounds per request.
endpoint_config["json"] = _build_search_body(
config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
)
@@ -92,8 +341,13 @@ def shortcut_source(
"name": "Shortcut-Token",
"location": "header",
},
- # Each endpoint returns its whole collection in one un-paginated response.
- "paginator": SinglePagePaginator(),
+ # Flat list endpoints return the whole collection in one response; stories/search
+ # documents no cap or order, so it is read in created_at windows.
+ "paginator": StoriesSearchPaginator(
+ primary_key=config.primary_key, split_threshold=STORY_SEARCH_SPLIT_THRESHOLD
+ )
+ if config.method == "POST"
+ else SinglePagePaginator(),
},
"resource_defaults": {},
"resources": [
@@ -109,9 +363,22 @@ def shortcut_source(
resource = rest_api_resource(rest_config, team_id, job_id, None)
+ # stories/search windows share boundary seconds and verification re-reads whole windows, so
+ # dedupe on id before the rows reach the writer — the full-refresh append path never runs the
+ # merge's primary-key dedup. Flat GET endpoints return the whole collection in one page, no re-reads.
+ def items() -> Iterable[Any]:
+ if config.method == "POST":
+ return _dedupe_pages_by_id(resource, config.primary_key)
+ return resource
+
+ # stories/search windows arrive in no cursor order, so use desc for every cursor field: it
+ # advances the watermark once the run finishes rather than after each batch. A per-batch max on
+ # an unordered stream would skip unwritten lower rows on the next run's server-side filter.
+ sort_mode: SortMode = "desc"
+
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items,
primary_keys=[config.primary_key],
partition_count=1,
partition_size=1,
@@ -119,6 +386,7 @@ def shortcut_source(
partition_format="month" if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
column_hints=resource.column_hints,
+ sort_mode=sort_mode,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/tests/test_shortcut.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/tests/test_shortcut.py
index a2e037d89a3a..d759c3809263 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/tests/test_shortcut.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shortcut/tests/test_shortcut.py
@@ -1,11 +1,13 @@
import json
+import random
+from collections.abc import Callable
from datetime import UTC, date, datetime
from typing import Any
import pytest
from unittest import mock
-from requests import Response
+from requests import Request, Response
from requests.exceptions import HTTPError
from products.warehouse_sources.backend.temporal.data_imports.sources.shortcut.settings import (
@@ -14,6 +16,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.shortcut.s
)
from products.warehouse_sources.backend.temporal.data_imports.sources.shortcut.shortcut import (
SHORTCUT_BASE_URL,
+ STORY_SEARCH_EPOCH_START,
+ StoriesSearchPaginator,
_build_search_body,
_format_incremental_value,
shortcut_source,
@@ -37,11 +41,14 @@ def _response(body: Any, status_code: int = 200) -> Response:
return resp
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+def _wire(
+ session: mock.MagicMock, responses: list[Response] | Callable[[dict[str, Any]], Response]
+) -> list[dict[str, Any]]:
"""Wire a mock session and snapshot each request's method/url/json/auth AT SEND TIME.
The framework builds a single ``Request`` and mutates it in place across pages, so inspecting it
after the run shows only the final state — snapshot a copy when each request is prepared instead.
+ ``responses`` is either a list consumed in order, or a callable answering each request snapshot.
"""
session.headers = {}
snapshots: list[dict[str, Any]] = []
@@ -51,7 +58,7 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
{
"method": request.method,
"url": request.url,
- "json": request.json,
+ "json": dict(request.json) if isinstance(request.json, dict) else request.json,
"params": dict(request.params or {}),
"auth": request.auth,
}
@@ -61,10 +68,43 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
return prepared
session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
+ if callable(responses):
+ respond = responses
+ session.send.side_effect = lambda *args, **kwargs: respond(snapshots[-1])
+ else:
+ session.send.side_effect = responses
return snapshots
+def _story(story_id: int, created_at: str) -> dict[str, Any]:
+ return {"id": story_id, "created_at": created_at}
+
+
+def _stories_search_fake(
+ stories: list[dict[str, Any]], cap: int | None = None, order: str = "asc", exclusive_bounds: bool = False
+) -> Callable[[dict[str, Any]], Response]:
+ """Answer `POST /stories/search` the way the live endpoint might.
+
+ Filters on the created_at window in the body (inclusive bounds unless ``exclusive_bounds``),
+ returns rows in ``order`` (``asc``, ``desc``, or ``shuffled``), and cuts the response at ``cap``
+ rows without saying so.
+ """
+
+ def respond(snapshot: dict[str, Any]) -> Response:
+ body = snapshot["json"]
+ start, end = body["created_at_start"], body["created_at_end"]
+ if exclusive_bounds:
+ rows = [s for s in stories if start < s["created_at"] < end]
+ else:
+ rows = [s for s in stories if start <= s["created_at"] <= end]
+ rows.sort(key=lambda s: s["created_at"], reverse=order == "desc")
+ if order == "shuffled":
+ random.Random(len(rows)).shuffle(rows)
+ return _response(rows if cap is None else rows[:cap])
+
+ return respond
+
+
def _rows(source_response) -> list[dict[str, Any]]:
return [row for page in source_response.items() for row in page]
@@ -86,30 +126,48 @@ class TestFormatIncrementalValue:
class TestBuildSearchBody:
- def test_no_incremental_returns_empty_body(self) -> None:
+ def test_full_refresh_sends_created_at_floor(self) -> None:
+ # An empty body returns zero stories, so full refresh must still carry the epoch floor.
+ # includes_description asks the endpoint for the description column the schema advertises.
body = _build_search_body(SHORTCUT_ENDPOINTS["stories"], False, None, None)
- assert body == {}
+ assert body == {"created_at_start": STORY_SEARCH_EPOCH_START, "includes_description": True}
- def test_incremental_without_last_value_returns_empty_body(self) -> None:
+ def test_first_incremental_run_sends_created_at_floor(self) -> None:
body = _build_search_body(SHORTCUT_ENDPOINTS["stories"], True, None, "updated_at")
- assert body == {}
+ assert body == {"created_at_start": STORY_SEARCH_EPOCH_START, "includes_description": True}
@pytest.mark.parametrize(
- "incremental_field, expected_param",
+ "incremental_field, expected",
[
- ("updated_at", "updated_at_start"),
- ("created_at", "created_at_start"),
- (None, "updated_at_start"),
+ # A created_at cursor overrides the epoch floor; an updated_at cursor rides alongside it.
+ # Every story search asks for the description via includes_description.
+ ("created_at", {"created_at_start": "2026-01-02T03:04:05Z", "includes_description": True}),
+ (
+ "updated_at",
+ {
+ "updated_at_start": "2026-01-02T03:04:05Z",
+ "created_at_start": STORY_SEARCH_EPOCH_START,
+ "includes_description": True,
+ },
+ ),
+ (
+ None,
+ {
+ "updated_at_start": "2026-01-02T03:04:05Z",
+ "created_at_start": STORY_SEARCH_EPOCH_START,
+ "includes_description": True,
+ },
+ ),
],
)
- def test_maps_field_to_server_side_filter(self, incremental_field: str | None, expected_param: str) -> None:
+ def test_maps_field_to_server_side_filter(self, incremental_field: str | None, expected: dict) -> None:
body = _build_search_body(
SHORTCUT_ENDPOINTS["stories"], True, datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), incremental_field
)
- assert body == {expected_param: "2026-01-02T03:04:05Z"}
+ assert body == expected
- def test_full_refresh_endpoint_has_no_filter_params(self) -> None:
- # Flat list endpoints expose no incremental params, so even with a cursor we send nothing.
+ def test_non_search_endpoint_has_no_body(self) -> None:
+ # GET list endpoints carry no request body at all.
body = _build_search_body(SHORTCUT_ENDPOINTS["members"], True, datetime(2026, 1, 1, tzinfo=UTC), "updated_at")
assert body == {}
@@ -148,7 +206,8 @@ class TestRequests:
@mock.patch(CLIENT_SESSION_PATCH)
def test_stories_uses_post_with_incremental_body(self, MockSession) -> None:
session = MockSession.return_value
- snaps = _wire(session, [_response([{"id": 10}])])
+ story = _story(10, "2026-01-03T00:00:00Z")
+ snaps = _wire(session, _stories_search_fake([story]))
result = _rows(
shortcut_source(
@@ -162,22 +221,83 @@ class TestRequests:
)
)
- assert result == [{"id": 10}]
+ assert result == [story]
assert snaps[0]["method"] == "POST"
assert snaps[0]["url"] == f"{SHORTCUT_BASE_URL}/stories/search"
- # The server-side timestamp filter rides in the POST body, not the query string.
- assert snaps[0]["json"] == {"updated_at_start": "2026-01-02T03:04:05Z"}
+ # The server-side timestamp filter rides in the POST body, not the query string. The
+ # paginator closes the first created_at window at the moment the sync started.
+ body = snaps[0]["json"]
+ assert body["updated_at_start"] == "2026-01-02T03:04:05Z"
+ assert body["created_at_start"] == STORY_SEARCH_EPOCH_START
+ assert body["includes_description"] is True
+ assert datetime.strptime(body["created_at_end"], "%Y-%m-%dT%H:%M:%SZ") > datetime(2026, 1, 3)
assert snaps[0]["params"] == {}
@mock.patch(CLIENT_SESSION_PATCH)
- def test_stories_full_refresh_sends_empty_body(self, MockSession) -> None:
+ def test_stories_full_refresh_sends_non_empty_body(self, MockSession) -> None:
session = MockSession.return_value
- snaps = _wire(session, [_response([{"id": 10}])])
+ snaps = _wire(session, _stories_search_fake([_story(10, "2026-01-03T00:00:00Z")]))
_rows(shortcut_source("token", "stories", 1, "j"))
assert snaps[0]["method"] == "POST"
- assert snaps[0]["json"] == {}
+ # The outgoing body is never empty — an empty body returns zero stories.
+ assert snaps[0]["json"]["created_at_start"] == STORY_SEARCH_EPOCH_START
+ assert snaps[0]["json"]["includes_description"] is True
+
+ @pytest.mark.parametrize(
+ "cap, order, exclusive_bounds, split_threshold",
+ [
+ # No cap: the first window is complete and only gets confirmed.
+ (None, "asc", False, 1000),
+ # A cap below the split threshold, newest first: the paginator must notice the
+ # truncation itself, and the order of rows must not matter.
+ (3, "desc", False, 1000),
+ (3, "shuffled", False, 1000),
+ # The same cap with bounds the endpoint treats as exclusive: the window overlap must
+ # keep the stories on the midpoint seconds.
+ (3, "desc", True, 1000),
+ # A cap at the split threshold: every full response is split straight away.
+ (2, "asc", False, 2),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stories_reads_every_story_whatever_the_cap_and_order(
+ self, MockSession, cap: int | None, order: str, exclusive_bounds: bool, split_threshold: int
+ ) -> None:
+ session = MockSession.return_value
+ stories = [
+ _story(i, f"2025-{month:02d}-{day:02d}T0{day}:00:00Z")
+ for i, (month, day) in enumerate(
+ [(1, 1), (1, 1), (2, 3), (5, 7), (5, 7), (6, 8), (9, 1), (9, 2), (11, 4), (12, 9)], start=1
+ )
+ ]
+ _wire(session, _stories_search_fake(stories, cap=cap, order=order, exclusive_bounds=exclusive_bounds))
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.shortcut.shortcut.STORY_SEARCH_SPLIT_THRESHOLD",
+ split_threshold,
+ ):
+ rows = _rows(shortcut_source("token", "stories", 1, "j"))
+
+ # Every story lands exactly once, whatever the endpoint held back or how it ordered rows.
+ assert sorted(row["id"] for row in rows) == list(range(1, 11))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stories_past_the_cap_in_one_second_stop_with_a_warning(self, MockSession, caplog) -> None:
+ session = MockSession.return_value
+ # Three stories share one created_at second and the endpoint returns two at most, so no
+ # window can separate them. The sync must keep what it can get and say so, not loop.
+ stories = [_story(i, "2025-03-04T05:06:07Z") for i in range(1, 4)]
+ _wire(session, _stories_search_fake(stories, cap=2))
+
+ with caplog.at_level("WARNING"):
+ rows = _rows(shortcut_source("token", "stories", 1, "j"))
+
+ assert len({row["id"] for row in rows}) == 2
+ assert "cannot be split" in caplog.text
+ # Splitting from the epoch down to one second takes tens of requests, not thousands.
+ assert session.send.call_count < 200
@mock.patch(CLIENT_SESSION_PATCH)
def test_empty_list_yields_nothing(self, MockSession) -> None:
@@ -197,6 +317,39 @@ class TestRequests:
_rows(shortcut_source("token", "epics", 1, "j"))
+class TestStoriesSearchPaginator:
+ def _window(self, request: Request) -> tuple[str, str]:
+ return request.json["created_at_start"], request.json["created_at_end"]
+
+ def test_first_window_runs_from_the_floor_to_the_sync_start(self) -> None:
+ paginator = StoriesSearchPaginator(now=datetime(2026, 3, 1, 12, 0, 0, tzinfo=UTC))
+ request = Request(method="POST", url="x", json={"created_at_start": "2026-01-01T00:00:00Z"})
+
+ paginator.init_request(request)
+
+ assert self._window(request) == ("2026-01-01T00:00:00Z", "2026-03-01T12:00:00Z")
+
+ def test_full_response_splits_the_window_at_the_midpoint_second(self) -> None:
+ paginator = StoriesSearchPaginator(split_threshold=2, now=datetime(2026, 1, 1, 0, 0, 10, tzinfo=UTC))
+ request = Request(method="POST", url="x", json={"created_at_start": "2026-01-01T00:00:00Z"})
+ paginator.init_request(request)
+ rows = [_story(1, "2026-01-01T00:00:00Z"), _story(2, "2026-01-01T00:00:03Z")]
+
+ paginator.update_state(_response(rows), rows)
+ assert paginator.has_next_page is True
+ paginator.update_request(request)
+ first = self._window(request)
+ paginator.update_state(_response([]), [])
+ paginator.update_request(request)
+ second = self._window(request)
+
+ # The halves overlap around the midpoint second; which half is fetched first does not matter.
+ assert sorted([first, second]) == [
+ ("2026-01-01T00:00:00Z", "2026-01-01T00:00:06Z"),
+ ("2026-01-01T00:00:05Z", "2026-01-01T00:00:10Z"),
+ ]
+
+
class TestRetryAndErrorClassification:
@pytest.mark.parametrize("status_code", [429, 500, 502, 503])
@mock.patch(SLEEP_PATCH)
@@ -269,6 +422,15 @@ class TestShortcutSourceShape:
assert response.partition_keys == ["created_at"]
assert response.partition_format == "month"
+ @pytest.mark.parametrize("incremental_field", ["created_at", "updated_at", None])
+ def test_stories_sort_mode_is_desc_for_every_cursor(self, incremental_field: str | None) -> None:
+ # Windows arrive in no cursor order, so desc defers the watermark to the end of the run and a
+ # failed batch can't skip rows. None falls back to the updated_at cursor.
+ response = shortcut_source(
+ "token", "stories", 1, "j", should_use_incremental_field=True, incremental_field=incremental_field
+ )
+ assert response.sort_mode == "desc"
+
def test_stories_is_the_only_incremental_endpoint(self) -> None:
# Sanity check that mirrors the schema-level contract in the settings catalog.
incremental = {name for name, cfg in SHORTCUT_ENDPOINTS.items() if cfg.incremental_params}