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 Alguna credit-note, wallet, and version tables (#98110)

Tom Owerse038ccd4a467
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 5807e53a49b4..3492f2c9b909 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
@@ -217,14 +217,14 @@ Note: Static schema list, no dynamic index discovery. The headline Analytics tab
## Alguna — gaps
-Today (8): `billable_metrics`, `customers`, `invoices`, `payments`, `plans`, `products`, `refunds`, `subscriptions`
+Today (12): `billable_metrics`, `credit_notes`, `customers`, `invoices`, `payments`, `plans`, `products`, `refunds`, `subscription_versions`, `subscriptions`, `wallet_grants`, `wallets`
Diffed against: <https://alguna.com/docs/api-reference/v2/specs/2026-04-01.json>
-- [ ] `GET /subscriptions/{id}/versions (and /versions/current)` — subscription change history - the state-transition table behind MRR movement (high)
-- [ ] `GET /credit-notes` — credit-note transactions that offset the invoices already synced (high)
-- [ ] `GET /wallets and /wallets/{id}/balance` — prepaid wallet balances per customer (high)
-- [ ] `GET /wallet-grants and /wallets/{id}/grants` — credit grant ledger - drawdown and expiry analysis (high)
+- [x] `GET /subscriptions/{id}/versions (and /versions/current)` — subscription change history - the state-transition table behind MRR movement (high). Added as `subscription_versions` (fan-out over `subscriptions`). `/versions/current` skipped: it returns one version already present in the list.
+- [x] `GET /credit-notes` — credit-note transactions that offset the invoices already synced (high). Added as `credit_notes` (fan-out over `customers`, since `customer_id` is a required query param).
+- [x] `GET /wallets and /wallets/{id}/balance` — prepaid wallet balances per customer (high). Added as `wallets`. `/wallets/{id}/balance` skipped: the wallet list row already carries `current_balance`.
+- [x] `GET /wallet-grants and /wallets/{id}/grants` — credit grant ledger - drawdown and expiry analysis (high). Added as `wallet_grants` (the global `/wallet-grants` list). `/wallets/{id}/grants` skipped: it returns the same rows filtered per wallet.
- [ ] `GET /bundles` — product bundle lookup resolving bundle IDs carried on plans and subscription items (medium)
- [ ] `GET /customers/{id}/entitlements and /subscriptions/{id}/entitlements` — what each customer is currently entitled to, for feature-usage joins (medium)
- [ ] `GET /revenue-schedules (plus /customer/{id}, /subscription/{id}, /legal-entity/{id})` — revenue recognition schedule rows for rev-rec reporting (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py
index d6296d0e553f..8f5ac2a3a8e2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py
@@ -1,15 +1,27 @@
import dataclasses
-from typing import Any, Optional
+from collections.abc import Iterable, Iterator
+from typing import Any, Optional, cast
-from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.settings import ALGUNA_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.settings import (
+ ALGUNA_ENDPOINTS,
+ PAGE_LIMIT,
+ AlgunaEndpointConfig,
+)
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 (
RESTAPIConfig,
+ RESTClient,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth
+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 (
OffsetPaginator,
+ SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
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
@@ -17,7 +29,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
ALGUNA_BASE_URL = "https://api.alguna.io"
# Alguna's API is date-versioned; every request must send this header or calls fail.
ALGUNA_API_VERSION = "2026-04-01"
-PAGE_LIMIT = 100
@dataclasses.dataclass
@@ -32,36 +43,63 @@ def _version_headers() -> dict[str, str]:
return {"Alguna-Version": ALGUNA_API_VERSION, "Accept": "application/json"}
-def alguna_source(
- api_key: str,
- endpoint: str,
- team_id: int,
- job_id: str,
- resumable_source_manager: ResumableSourceManager[AlgunaResumeConfig],
- db_incremental_field_last_value: Optional[Any] = None,
-) -> SourceResponse:
- config = ALGUNA_ENDPOINTS[endpoint]
+def _offset_paginator() -> OffsetPaginator:
+ # Alguna has no top-level `total`; termination is a short/empty page (OffsetPaginator default).
+ return OffsetPaginator(limit=PAGE_LIMIT, total_path=None)
+
+def _list_params(config: AlgunaEndpointConfig) -> dict[str, Any]:
params: dict[str, Any] = {"limit": PAGE_LIMIT}
if config.sort is not None:
params["sort"] = config.sort
+ return params
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": ALGUNA_BASE_URL,
+ "headers": _version_headers(),
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": _offset_paginator(),
+ }
+
+def _source_response(
+ config: AlgunaEndpointConfig,
+ items_fn: Any,
+ column_hints: Any = None,
+) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=items_fn,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ column_hints=column_hints,
+ )
+
+
+def _top_level_source(
+ api_key: str,
+ config: AlgunaEndpointConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[AlgunaResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": ALGUNA_BASE_URL,
- "headers": _version_headers(),
- "auth": {"type": "bearer", "token": api_key},
- # Alguna has no top-level `total`; termination is short/empty page (OffsetPaginator default).
- "paginator": OffsetPaginator(limit=PAGE_LIMIT, total_path=None),
- },
+ "client": _client_config(api_key),
# Per-resource settings are fully specified below, so no shared defaults are needed.
"resource_defaults": {},
"resources": [
{
- "name": endpoint,
+ "name": config.name,
"endpoint": {
"path": config.path,
- "params": params,
+ "params": _list_params(config),
"data_selector": "data",
# A 200 body without `data` means the response shape changed — fail loud
# instead of silently syncing 0 rows.
@@ -92,16 +130,106 @@ def alguna_source(
initial_paginator_state=initial_paginator_state,
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- primary_keys=config.primary_keys,
- partition_count=1,
- partition_size=1,
- partition_mode="datetime",
- partition_format="month",
- partition_keys=[config.partition_key],
- column_hints=resource.column_hints,
+ return _source_response(config, lambda: resource, column_hints=resource.column_hints)
+
+
+def _declarative_fanout_source(
+ api_key: str,
+ config: AlgunaEndpointConfig,
+ team_id: int,
+ job_id: str,
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
+ # Path-based fan-out (e.g. /subscriptions/{subscription_id}/versions) via the shared helper.
+ # Fan-out endpoints don't resume: a retry re-syncs from scratch and the merge dedupes.
+ assert config.fanout is not None
+ parent_config = ALGUNA_ENDPOINTS[config.fanout.parent_name]
+ dependent_resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=ALGUNA_ENDPOINTS,
+ child_endpoint=config.name,
+ # The child path takes no page-size param, so the parent's limit rides parent_params.
+ fanout=dataclasses.replace(config.fanout, parent_params=_list_params(parent_config)),
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ page_size_param=None,
+ parent_endpoint_extra={
+ "paginator": _offset_paginator(),
+ "data_selector": "data",
+ "data_selector_required": True,
+ },
+ child_endpoint_extra={
+ "paginator": SinglePagePaginator(),
+ "data_selector": "data",
+ "data_selector_required": True,
+ },
+ ),
+ )
+ return _source_response(config, lambda: dependent_resource)
+
+
+def _query_fanout_pages(
+ client: RESTClient,
+ config: AlgunaEndpointConfig,
+ parent_config: AlgunaEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ fanout = config.query_fanout
+ assert fanout is not None
+ for parent_page in client.paginate(
+ path=parent_config.path,
+ params=_list_params(parent_config),
+ paginator=_offset_paginator(),
+ data_selector="data",
+ data_selector_required=True,
+ ):
+ for parent in parent_page:
+ parent_id = parent.get(fanout.parent_field)
+ if parent_id is None:
+ continue
+ yield from client.paginate(
+ path=config.path,
+ params={fanout.query_param: parent_id, "limit": PAGE_LIMIT},
+ paginator=_offset_paginator(),
+ data_selector="data",
+ data_selector_required=True,
+ )
+
+
+def _query_fanout_source(api_key: str, config: AlgunaEndpointConfig) -> SourceResponse:
+ # Fan-out where the parent id is a required query param on the child (e.g.
+ # /credit-notes?customer_id=...). Fan-out endpoints don't resume: a retry re-syncs from
+ # scratch and the merge dedupes.
+ assert config.query_fanout is not None
+ parent_config = ALGUNA_ENDPOINTS[config.query_fanout.parent_name]
+ client = RESTClient(
+ base_url=ALGUNA_BASE_URL,
+ headers=_version_headers(),
+ auth=BearerTokenAuth(api_key),
+ paginator=_offset_paginator(),
+ )
+ return _source_response(config, lambda: _query_fanout_pages(client, config, parent_config))
+
+
+def alguna_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[AlgunaResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = ALGUNA_ENDPOINTS[endpoint]
+
+ if config.fanout is not None:
+ return _declarative_fanout_source(api_key, config, team_id, job_id, db_incremental_field_last_value)
+ if config.query_fanout is not None:
+ return _query_fanout_source(api_key, config)
+ return _top_level_source(
+ api_key, config, team_id, job_id, resumable_source_manager, db_incremental_field_last_value
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/canonical_descriptions.py
index 659e9a08236b..6d26615abe3d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/canonical_descriptions.py
@@ -21,6 +21,41 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "Timestamp when the metric was last updated.",
},
},
+ "credit_notes": {
+ "description": "A credit note that reduces or offsets what a customer owes, optionally tied to an invoice.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/credit-notes/list-credit-notes",
+ "columns": {
+ "accounting_credit_note_id": "Credit note ID in the connected accounting system.",
+ "accounting_credit_note_url": "URL to the credit note in the accounting system.",
+ "accounting_integration_id": "Accounting integration ID.",
+ "accounting_provider": "Accounting provider name.",
+ "apply_date": "Date the credit note was applied.",
+ "attachments": "Attachments on this credit note.",
+ "billing_period_end": "End of the billing period.",
+ "billing_period_start": "Start of the billing period.",
+ "created_at": "Timestamp when the credit note was created.",
+ "credit_date": "Date of the credit.",
+ "currency": "ISO 4217 currency code.",
+ "customer_id": "Customer this credit note belongs to.",
+ "description": "Description of the credit note.",
+ "external_reference": "External reference identifier.",
+ "id": "Unique identifier for the credit note.",
+ "invoice_id": "Associated invoice ID.",
+ "is_pdf_available": "Whether a PDF is available for download.",
+ "last_refund_date": "Date of the last refund.",
+ "last_refund_id": "ID of the last refund.",
+ "legal_entity_id": "Legal entity ID.",
+ "line_items": "Line items on this credit note.",
+ "merchant_id": "Sub-merchant the credited invoice was issued for.",
+ "purchase_order_number": "Purchase order number.",
+ "status": "Current status of the credit note.",
+ "subtotal": "Subtotal before tax.",
+ "sync_enabled": "Whether accounting sync is enabled.",
+ "tax": "Tax amount.",
+ "total": "Total amount including tax.",
+ "updated_at": "Timestamp when the credit note was last updated.",
+ },
+ },
"customers": {
"description": "A customer account you bill in Alguna, including currency and tax configuration.",
"docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/customers/list-customers",
@@ -155,4 +190,50 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "When the subscription was last updated.",
},
},
+ "subscription_versions": {
+ "description": "A version (phase) of a subscription's history — the state-transition record behind each change to its terms.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/subscriptions/list-subscription-versions",
+ "columns": {
+ "created_at": "When the version was created.",
+ "description": "Change description for this version.",
+ "end_date": "Version end date.",
+ "id": "Unique identifier for the version.",
+ "plan_id": "Plan this version is based on.",
+ "start_date": "Version start date.",
+ "status": "Version status.",
+ "subscription_id": "Subscription this version belongs to.",
+ "updated_at": "When the version was last updated.",
+ },
+ },
+ "wallets": {
+ "description": "A prepaid wallet holding a customer's credit balance that can be drawn down against usage.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/wallets/list-wallets",
+ "columns": {
+ "active": "Whether the wallet is active.",
+ "created_at": "Timestamp when the wallet was created.",
+ "currency": "ISO 4217 currency code.",
+ "current_balance": "Current balance of the wallet.",
+ "customer_id": "Identifier of the customer that owns this wallet.",
+ "id": "Unique identifier for the wallet.",
+ "name": "Name of the wallet.",
+ "product_ids": "Product IDs that can be purchased with this wallet.",
+ "updated_at": "Timestamp when the wallet was last updated.",
+ },
+ },
+ "wallet_grants": {
+ "description": "A credit grant added to a wallet, with its amount, status, and expiry — the grant ledger behind wallet balances.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/wallets/list-wallet-grants",
+ "columns": {
+ "amount": "Amount of the grant.",
+ "created_at": "Timestamp when the grant was created.",
+ "description": "Description of the grant.",
+ "expires_at": "When the grant expires.",
+ "id": "Unique identifier for the wallet grant.",
+ "invoice_id": "Associated invoice identifier.",
+ "payment_id": "Associated payment identifier.",
+ "status": "Status of the grant.",
+ "updated_at": "Timestamp when the grant was last updated.",
+ "wallet_id": "Identifier of the wallet this grant belongs to.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py
index 828a367bc93f..3034fdd4b260 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py
@@ -1,27 +1,62 @@
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
+# Alguna list endpoints paginate with limit/offset.
+PAGE_LIMIT = 100
+
# Every stream is full refresh. Alguna's list endpoints expose no created_at/updated_at server-side
# filters, and while /invoices supports issue/paid/due/invoicing date-range filters, the invoice
# *list* payload (InvoiceListItemResponse) doesn't include those date fields — so the pipeline
# can't track a watermark from synced rows. Billing data is low-cardinality, so full refresh is fine.
-@dataclass
+@dataclass(frozen=True)
+class AlgunaQueryFanout:
+ # Fan-out where the parent id rides a required *query* param on the child list endpoint (e.g.
+ # /credit-notes?customer_id=...). The shared rest_source fan-out only binds resolve params in
+ # the *path*, so these route through a hand-rolled iterator in alguna.py instead.
+ parent_name: str
+ query_param: str
+ parent_field: str = "id"
+
+
+@dataclass(frozen=True)
class AlgunaEndpointConfig:
name: str
path: str
# Alguna requires `sort` (format "field:order") on most list endpoints; None for the endpoints
- # that don't accept it (payments, products). All entities carry created_at, and the API docs use
- # it in sort examples, so it's the stable pagination order for the endpoints that sort.
+ # that don't accept it (payments, products, wallets, wallet-grants). All entities carry
+ # created_at, and the API docs use it in sort examples, so it's the stable pagination order for
+ # the endpoints that sort.
sort: str | None = "created_at:asc"
primary_keys: list[str] = field(default_factory=lambda: ["id"])
partition_key: str = "created_at"
+ # Whether the endpoint offset-paginates. False for a fan-out child that returns its whole
+ # collection in one response (e.g. /subscriptions/{id}/versions).
+ paginated: bool = True
+ page_size: int = PAGE_LIMIT
+ # Full refresh only — kept so the config satisfies the fan-out helper's protocol.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ # Path-based fan-out driven by the shared rest_source helper (parent id in a {placeholder}).
+ fanout: DependentEndpointConfig | None = None
+ # Query-param fan-out driven by the hand-rolled iterator in alguna.py.
+ query_fanout: AlgunaQueryFanout | None = None
ALGUNA_ENDPOINTS: dict[str, AlgunaEndpointConfig] = {
"billable_metrics": AlgunaEndpointConfig(name="billable_metrics", path="/metrics"),
+ "credit_notes": AlgunaEndpointConfig(
+ name="credit_notes",
+ path="/credit-notes",
+ sort=None,
+ # /credit-notes requires a customer_id query param, so list per customer.
+ query_fanout=AlgunaQueryFanout(parent_name="customers", query_param="customer_id"),
+ ),
"customers": AlgunaEndpointConfig(name="customers", path="/customers"),
"invoices": AlgunaEndpointConfig(name="invoices", path="/invoices"),
"payments": AlgunaEndpointConfig(name="payments", path="/payments", sort=None),
@@ -29,6 +64,24 @@ ALGUNA_ENDPOINTS: dict[str, AlgunaEndpointConfig] = {
"products": AlgunaEndpointConfig(name="products", path="/products", sort=None),
"refunds": AlgunaEndpointConfig(name="refunds", path="/refunds"),
"subscriptions": AlgunaEndpointConfig(name="subscriptions", path="/subscriptions"),
+ "subscription_versions": AlgunaEndpointConfig(
+ name="subscription_versions",
+ path="/subscriptions/{subscription_id}/versions",
+ sort=None,
+ # Version id is unique within its subscription; scope it with the parent to be safe.
+ primary_keys=["subscription_id", "id"],
+ # The versions endpoint returns the whole list in one response — no limit/offset.
+ paginated=False,
+ fanout=DependentEndpointConfig(
+ parent_name="subscriptions",
+ resolve_param="subscription_id",
+ resolve_field="id",
+ # The version payload already carries subscription_id; nothing to copy down.
+ include_from_parent=[],
+ ),
+ ),
+ "wallets": AlgunaEndpointConfig(name="wallets", path="/wallets", sort=None),
+ "wallet_grants": AlgunaEndpointConfig(name="wallet_grants", path="/wallet-grants", sort=None),
}
ENDPOINTS = tuple(ALGUNA_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
index 18ae6139ab23..92a3bb8cb973 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
@@ -56,6 +56,21 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
return param_snapshots
+def _wire_urls(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, dict[str, Any]]]:
+ """Like `_wire`, but capture each request's URL alongside its params so fan-out tests can tell
+ a parent request from a per-parent child request."""
+ session.headers = {}
+ captured: list[tuple[str, dict[str, Any]]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ captured.append((request.url or "", dict(request.params or {})))
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return captured
+
+
def _rows(source_response) -> list[dict[str, Any]]:
return [row for page in source_response.items() for row in page]
@@ -134,6 +149,78 @@ class TestPagination:
_rows(alguna_source("key", "customers", team_id=1, job_id="j", resumable_source_manager=_make_manager()))
+class TestFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_credit_notes_fan_out_over_customers_and_paginate_child(self, MockSession) -> None:
+ session = MockSession.return_value
+ cust1_full = [{"id": f"cn1_{i}", "customer_id": "cust_1"} for i in range(100)]
+ reqs = _wire_urls(
+ session,
+ [
+ _response([{"id": "cust_1"}, {"id": "cust_2"}]), # parent: short page ends parent walk
+ _response(cust1_full), # cust_1 credit-notes page 1 (full → another page)
+ _response([{"id": "cn1_last", "customer_id": "cust_1"}]), # cust_1 page 2 (short)
+ _response([{"id": "cn2_1", "customer_id": "cust_2"}]), # cust_2 (short)
+ ],
+ )
+
+ rows = _rows(
+ alguna_source("key", "credit_notes", team_id=1, job_id="j", resumable_source_manager=_make_manager())
+ )
+
+ assert [r["id"] for r in rows] == [*(f"cn1_{i}" for i in range(100)), "cn1_last", "cn2_1"]
+ assert reqs[0][0].endswith("/customers")
+ # Each customer's credit-notes are fetched with its id, and a full page advances the offset.
+ child = [(url, params) for url, params in reqs if url.endswith("/credit-notes")]
+ assert [params["customer_id"] for _url, params in child] == ["cust_1", "cust_1", "cust_2"]
+ assert [params["offset"] for _url, params in child] == [0, 100, 0]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_credit_notes_skips_parent_without_id(self, MockSession) -> None:
+ session = MockSession.return_value
+ reqs = _wire_urls(
+ session,
+ [
+ _response([{"name": "no-id"}, {"id": "cust_2"}]),
+ _response([{"id": "cn2_1", "customer_id": "cust_2"}]),
+ ],
+ )
+
+ rows = _rows(
+ alguna_source("key", "credit_notes", team_id=1, job_id="j", resumable_source_manager=_make_manager())
+ )
+
+ assert [r["id"] for r in rows] == ["cn2_1"]
+ # The id-less parent yields no child request.
+ assert [params["customer_id"] for url, params in reqs if url.endswith("/credit-notes")] == ["cust_2"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_subscription_versions_fan_out_omits_child_page_size(self, MockSession) -> None:
+ session = MockSession.return_value
+ reqs = _wire_urls(
+ session,
+ [
+ _response([{"id": "sub_1"}, {"id": "sub_2"}]), # parent subscriptions
+ _response([{"id": "v_1", "subscription_id": "sub_1"}]),
+ _response([{"id": "v_2", "subscription_id": "sub_2"}]),
+ ],
+ )
+
+ rows = _rows(
+ alguna_source(
+ "key", "subscription_versions", team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ )
+ )
+
+ assert {r["id"] for r in rows} == {"v_1", "v_2"}
+ parent = next(params for url, params in reqs if url.endswith("/subscriptions"))
+ assert parent["limit"] == 100 # parent paginates with an explicit page size
+ child = [(url, params) for url, params in reqs if url.endswith("/versions")]
+ assert {url.split("/subscriptions/")[1].split("/")[0] for url, _params in child} == {"sub_1", "sub_2"}
+ # The versions endpoint takes no page-size param; a leaked `limit` would be an undocumented param.
+ assert all("limit" not in params for _url, params in child)
+
+
class TestValidateCredentials:
@mock.patch(ALGUNA_SESSION_PATCH)
def test_ok(self, mock_session) -> None: