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(data-warehouse): implement katana import source (#67834)

Tom Owersac986be6c487
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index f0b28e67a434..289f9ace7682 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -189,6 +189,7 @@ the row lists both.
| jira | HTTP | requests | ✅ |
| jotform | HTTP | requests | ✅ |
| justcall | HTTP | requests | ✅ |
+| katana | HTTP | requests | ✅ |
| klaviyo | HTTP | requests | ✅ |
| lago | HTTP | requests | ✅ |
| launchdarkly | HTTP | requests | ✅ |
@@ -494,7 +495,6 @@ doesn't conflict with concurrent PRs.
- justsift
- k6_cloud
- kafka
-- katana
- keka
- kisi
- kissmetrics
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 630adf5d96bf..a0b9f49a5a70 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1735,7 +1735,7 @@ class KafkaSourceConfig(config.Config):
@config.config
class KatanaSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/katana/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/canonical_descriptions.py
new file mode 100644
index 000000000000..ce2325be134a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/canonical_descriptions.py
@@ -0,0 +1,231 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS = "https://developer.katanamrp.com/reference"
+
+# Descriptions sourced from Katana's official API reference. Partial coverage is fine — any table or
+# column not listed here falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "products": {
+ "description": "Sellable/producible items in the factory, each with one or more variants.",
+ "docs_url": f"{_DOCS}/getallproducts",
+ "columns": {
+ "id": "Unique identifier for the product.",
+ "name": "Product name.",
+ "uom": "Unit of measure for the product.",
+ "category_name": "Category the product belongs to.",
+ "is_sellable": "Whether the product can be sold.",
+ "is_producible": "Whether the product can be manufactured.",
+ "is_purchasable": "Whether the product can be purchased.",
+ "created_at": "Timestamp when the product was created.",
+ "updated_at": "Timestamp when the product was last updated.",
+ },
+ },
+ "materials": {
+ "description": "Raw materials and ingredients consumed by manufacturing orders.",
+ "docs_url": f"{_DOCS}/getallmaterials",
+ "columns": {
+ "id": "Unique identifier for the material.",
+ "name": "Material name.",
+ "uom": "Unit of measure for the material.",
+ "category_name": "Category the material belongs to.",
+ "default_supplier_id": "Default supplier for purchasing this material.",
+ "created_at": "Timestamp when the material was created.",
+ "updated_at": "Timestamp when the material was last updated.",
+ },
+ },
+ "variants": {
+ "description": "Individual SKUs of a product or material, carrying sales/purchase prices and barcodes.",
+ "docs_url": f"{_DOCS}/getallvariants",
+ "columns": {
+ "id": "Unique identifier for the variant.",
+ "product_id": "Parent product id (null for material variants).",
+ "material_id": "Parent material id (null for product variants).",
+ "sku": "Stock keeping unit.",
+ "sales_price": "Default sales price.",
+ "purchase_price": "Default purchase price.",
+ "created_at": "Timestamp when the variant was created.",
+ "updated_at": "Timestamp when the variant was last updated.",
+ },
+ },
+ "services": {
+ "description": "Sellable services offered alongside physical products.",
+ "docs_url": f"{_DOCS}/getallservices",
+ "columns": {
+ "id": "Unique identifier for the service.",
+ "name": "Service name.",
+ "uom": "Unit of measure for the service.",
+ "is_sellable": "Whether the service can be sold.",
+ },
+ },
+ "customers": {
+ "description": "Customers you sell to, including contact and billing details.",
+ "docs_url": f"{_DOCS}/list-all-customers",
+ "columns": {
+ "id": "Unique identifier for the customer.",
+ "name": "Customer display name.",
+ "email": "Primary email address.",
+ "phone": "Primary phone number.",
+ "currency": "Default currency for the customer.",
+ "reference_id": "External reference id for the customer.",
+ "created_at": "Timestamp when the customer was created.",
+ "updated_at": "Timestamp when the customer was last updated.",
+ },
+ },
+ "suppliers": {
+ "description": "Suppliers you purchase materials and products from.",
+ "docs_url": f"{_DOCS}/getallsuppliers",
+ "columns": {
+ "id": "Unique identifier for the supplier.",
+ "name": "Supplier display name.",
+ "email": "Primary email address.",
+ "phone": "Primary phone number.",
+ "created_at": "Timestamp when the supplier was created.",
+ "updated_at": "Timestamp when the supplier was last updated.",
+ },
+ },
+ "sales_orders": {
+ "description": "Customer sales orders, including status, fulfillment and invoicing state.",
+ "docs_url": f"{_DOCS}/getallsalesorders",
+ "columns": {
+ "id": "Unique identifier for the sales order.",
+ "order_no": "Human-readable sales order number.",
+ "customer_id": "Customer the order belongs to.",
+ "location_id": "Location fulfilling the order.",
+ "status": "Overall order status.",
+ "invoicing_status": "Invoicing status of the order.",
+ "currency": "Currency of the order.",
+ "created_at": "Timestamp when the order was created.",
+ "updated_at": "Timestamp when the order was last updated.",
+ },
+ },
+ "purchase_orders": {
+ "description": "Purchase orders raised to suppliers for materials and products.",
+ "docs_url": f"{_DOCS}/getallpurchaseorders",
+ "columns": {
+ "id": "Unique identifier for the purchase order.",
+ "order_no": "Human-readable purchase order number.",
+ "supplier_id": "Supplier the order is placed with.",
+ "location_id": "Location receiving the order.",
+ "status": "Overall purchase order status.",
+ "billing_status": "Billing status of the order.",
+ "currency": "Currency of the order.",
+ "created_at": "Timestamp when the order was created.",
+ "updated_at": "Timestamp when the order was last updated.",
+ },
+ },
+ "manufacturing_orders": {
+ "description": "Production orders that manufacture products from materials.",
+ "docs_url": f"{_DOCS}/getallmanufacturingorders",
+ "columns": {
+ "id": "Unique identifier for the manufacturing order.",
+ "order_no": "Human-readable manufacturing order number.",
+ "status": "Production status of the order.",
+ "location_id": "Location where production happens.",
+ "is_linked_to_sales_order": "Whether the order was created to fulfil a sales order.",
+ "created_at": "Timestamp when the order was created.",
+ "updated_at": "Timestamp when the order was last updated.",
+ },
+ },
+ "sales_returns": {
+ "description": "Returns raised against sales orders, with refund and restock status.",
+ "docs_url": f"{_DOCS}/getallsalesreturns",
+ "columns": {
+ "id": "Unique identifier for the sales return.",
+ "order_no": "Return order number.",
+ "sales_order_no": "Originating sales order number.",
+ "status": "Return status.",
+ "refund_status": "Refund status of the return.",
+ "return_location_id": "Location the goods are returned to.",
+ },
+ },
+ "stock_adjustments": {
+ "description": "Manual stock corrections that increase or decrease on-hand quantities.",
+ "docs_url": f"{_DOCS}/getallstockadjustments",
+ "columns": {
+ "id": "Unique identifier for the stock adjustment.",
+ "stock_adjustment_number": "Human-readable adjustment number.",
+ "location_id": "Location the adjustment applies to.",
+ "created_at": "Timestamp when the adjustment was created.",
+ "updated_at": "Timestamp when the adjustment was last updated.",
+ },
+ },
+ "stock_transfers": {
+ "description": "Movements of stock between two locations.",
+ "docs_url": f"{_DOCS}/getallstocktransfers",
+ "columns": {
+ "id": "Unique identifier for the stock transfer.",
+ "stock_transfer_number": "Human-readable transfer number.",
+ "source_location_id": "Location stock is transferred from.",
+ "target_location_id": "Location stock is transferred to.",
+ "created_at": "Timestamp when the transfer was created.",
+ "updated_at": "Timestamp when the transfer was last updated.",
+ },
+ },
+ "stocktakes": {
+ "description": "Physical inventory counts and the adjustments they produce.",
+ "docs_url": f"{_DOCS}/getallstocktakes",
+ "columns": {
+ "id": "Unique identifier for the stocktake.",
+ "stocktake_number": "Human-readable stocktake number.",
+ "status": "Stocktake status.",
+ "location_id": "Location being counted.",
+ "created_at": "Timestamp when the stocktake was created.",
+ "updated_at": "Timestamp when the stocktake was last updated.",
+ },
+ },
+ "inventory_movements": {
+ "description": "Append-only log of every inventory movement created by Katana resources.",
+ "docs_url": f"{_DOCS}/list-all-inventory-movements",
+ "columns": {
+ "id": "Unique identifier for the inventory movement.",
+ "variant_id": "Variant whose stock moved.",
+ "location_id": "Location where the movement occurred.",
+ "resource_type": "Type of resource that caused the movement.",
+ "resource_id": "Id of the resource that caused the movement.",
+ "created_at": "Timestamp when the movement was recorded.",
+ },
+ },
+ "inventory": {
+ "description": "Current on-hand, committed and expected stock per variant and location. Full refresh only.",
+ "docs_url": f"{_DOCS}/getinventories",
+ "columns": {
+ "variant_id": "Variant the stock balance is for.",
+ "location_id": "Location the stock balance is for.",
+ "quantity_in_stock": "Quantity currently in stock.",
+ "quantity_committed": "Quantity committed to orders.",
+ "quantity_expected": "Quantity expected from incoming orders.",
+ },
+ },
+ "price_lists": {
+ "description": "Named price lists used for customer-specific pricing. Full refresh only.",
+ "docs_url": f"{_DOCS}/getallpricelists",
+ "columns": {
+ "id": "Unique identifier for the price list.",
+ "name": "Price list name.",
+ "is_active": "Whether the price list is active.",
+ },
+ },
+ "locations": {
+ "description": "Warehouses and factories where stock is held and orders are fulfilled.",
+ "docs_url": f"{_DOCS}/list-all-locations",
+ "columns": {
+ "id": "Unique identifier for the location.",
+ "name": "Location name.",
+ "legal_name": "Legal name of the location.",
+ "is_primary": "Whether this is the primary location.",
+ },
+ },
+ "tax_rates": {
+ "description": "Tax rates applied to sales and purchase orders.",
+ "docs_url": f"{_DOCS}/getalltaxrates",
+ "columns": {
+ "id": "Unique identifier for the tax rate.",
+ "name": "Tax rate name.",
+ "rate": "Tax rate percentage.",
+ "is_default_sales": "Whether this is the default sales tax rate.",
+ "is_default_purchases": "Whether this is the default purchases tax rate.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/katana/katana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/katana.py
new file mode 100644
index 000000000000..dad2846bf04f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/katana.py
@@ -0,0 +1,298 @@
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlsplit, urlunsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana.settings import (
+ KATANA_ENDPOINTS,
+ KatanaEndpointConfig,
+)
+
+KATANA_BASE_URL = "https://api.katanamrp.com/v1"
+# Katana caps list pages at 250 rows; use the max to minimise request count against the 60 req/min limit.
+PAGE_SIZE = 250
+# Katana allows 60 requests per 60 seconds. Space requests ~1/s so a large backfill stays under the
+# limit instead of relying on 429 backoff for every page.
+REQUEST_INTERVAL_SECONDS = 1.1
+MAX_ATTEMPTS = 6
+MAX_BACKOFF_SECONDS = 60.0
+
+
+class KatanaRetryableError(Exception):
+ """Transient server-side failure (5xx) that should be retried."""
+
+
+class KatanaRateLimitError(Exception):
+ """429 response. Carries the server's Retry-After hint (seconds) when present."""
+
+ def __init__(self, retry_after: float | None) -> None:
+ super().__init__("Katana rate limit exceeded")
+ self.retry_after = retry_after
+
+
+class KatanaResumeConfig:
+ # Next page to fetch. On resume we re-fetch this page in full — a batch may be yielded mid-page,
+ # so re-reading the whole page recovers any un-yielded tail; the delta merge dedupes the overlap.
+ page: int = 1
+
+
+class _Throttle:
+ """Spaces outbound requests to honour Katana's 60 req/min budget without per-request 429s."""
+
+ def __init__(self, interval_seconds: float) -> None:
+ self._interval = interval_seconds
+ self._last_request_at: float | None = None
+
+ def wait(self) -> None:
+ if self._last_request_at is not None:
+ elapsed = time.monotonic() - self._last_request_at
+ if elapsed < self._interval:
+ time.sleep(self._interval - elapsed)
+ self._last_request_at = time.monotonic()
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _safe_error_url(url: str) -> str:
+ """Scheme + host + path only — drop query and any userinfo so a redirected, credential-bearing
+ final URL never lands in a persisted error message (the Katana key rides in the Authorization
+ header, but a redirect could echo credentials into the URL)."""
+ try:
+ parts = urlsplit(url)
+ except ValueError:
+ return ""
+ netloc = parts.hostname or ""
+ if parts.port:
+ netloc = f"{netloc}:{parts.port}"
+ return urlunsplit((parts.scheme, netloc, parts.path, "", ""))
+
+
+def _format_datetime_z(dt: datetime) -> str:
+ """ISO 8601 with millisecond precision and a Z suffix (Katana filters expect ISO 8601)."""
+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+
+def _format_incremental_value(value: Any) -> str:
+ if isinstance(value, datetime):
+ return _format_datetime_z(value)
+ if isinstance(value, date):
+ return _format_datetime_z(datetime.combine(value, datetime.min.time(), tzinfo=UTC))
+ return str(value)
+
+
+def _clamp_future_value_to_now(value: Any) -> Any:
+ """Cap a future cursor at now so we never send a future `<field>_min` filter (a no-op that could
+ otherwise wedge the sync if the source has future-dated rows)."""
+ now = datetime.now(UTC)
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return now if aware > now else value
+ if isinstance(value, date):
+ return now.date() if value > now.date() else value
+ return value
+
+
+def _build_base_params(
+ config: KatanaEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ """Query params shared by every page of a sync (the server-side timestamp filter)."""
+ params: dict[str, Any] = {}
+
+ if should_use_incremental_field and db_incremental_field_last_value and config.incremental_fields:
+ field_name = incremental_field or config.default_incremental_field
+ clamped = _clamp_future_value_to_now(db_incremental_field_last_value)
+ params[f"{field_name}_min"] = _format_incremental_value(clamped)
+
+ return params
+
+
+def _wait_katana(retry_state: RetryCallState) -> float:
+ """Honour the server's Retry-After on 429; otherwise exponential backoff."""
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, KatanaRateLimitError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_BACKOFF_SECONDS)
+ return min(2.0**retry_state.attempt_number, MAX_BACKOFF_SECONDS)
+
+
+def _request_page(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any],
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ throttle: _Throttle,
+) -> dict:
+ """Single throttled request. Raises the retryable/terminal errors `_fetch_page` retries on."""
+ throttle.wait()
+ response = session.get(url, params=params, headers=headers, timeout=60)
+
+ if response.status_code == 429:
+ retry_after_header = response.headers.get("Retry-After")
+ retry_after = float(retry_after_header) if retry_after_header else None
+ raise KatanaRateLimitError(retry_after)
+
+ if response.status_code >= 500:
+ raise KatanaRetryableError(f"Katana API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Surface 4xx as an HTTPError so `get_non_retryable_errors` can match and stop the sync. Build the
+ # message from a scrubbed URL rather than `raise_for_status()`, whose default text embeds the raw
+ # final URL — a redirect could carry the credential there, and the error is persisted to job logs.
+ # The scrubbed `... for url: https://api.katanamrp.com/...` prefix stays matchable.
+ safe_url = _safe_error_url(response.url or url)
+ logger.error(f"Katana API error: status={response.status_code}, url={safe_url}")
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {safe_url}",
+ response=response,
+ )
+
+ body = response.json()
+ # Every Katana list endpoint wraps results as {"data": [...]}, returning {"data": []} when empty.
+ # A 2xx body missing the `data` key (maintenance page, changed envelope) would otherwise read as an
+ # empty page and silently end pagination mid-sync, so treat it as retryable rather than lose data.
+ if not isinstance(body, dict) or "data" not in body:
+ raise KatanaRetryableError(f"Unexpected Katana response envelope (no 'data' key): url={url}")
+
+ return body
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ KatanaRetryableError,
+ KatanaRateLimitError,
+ requests.ConnectionError,
+ requests.ReadTimeout,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ wait=_wait_katana,
+ stop=stop_after_attempt(MAX_ATTEMPTS),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any],
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ throttle: _Throttle,
+) -> dict:
+ return _request_page(session, url, params, headers, logger, throttle)
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Cheap token probe: `/user_info` returns 200 for a valid key regardless of resource scopes."""
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ f"{KATANA_BASE_URL}/user_info", headers=_get_headers(api_key), timeout=15
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KatanaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = KATANA_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ session = make_tracked_session(redact_values=(api_key,))
+ throttle = _Throttle(REQUEST_INTERVAL_SECONDS)
+ batcher = Batcher(logger=logger, chunk_size=5000, chunk_size_bytes=200 * 1024 * 1024)
+
+ base_params = _build_base_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume else 1
+ if resume:
+ logger.debug(f"Katana: resuming {endpoint} from page {page}")
+
+ url = f"{KATANA_BASE_URL}{config.path}"
+
+ while True:
+ params = {**base_params, "page": page, "limit": PAGE_SIZE}
+ data = _fetch_page(session, url, params, headers, logger, throttle)
+ # `_request_page` already guaranteed the `data` key is present (it raises otherwise), so read it
+ # directly — a `.get(..., [])` fallback here would silently mask a regression in that guard.
+ items = data["data"]
+
+ for item in items:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Save AFTER yielding, pointing at the CURRENT page: a crash re-reads this page in full
+ # (recovering its un-yielded tail) and the merge dedupes the already-written prefix.
+ resumable_source_manager.save_state(KatanaResumeConfig(page=page))
+
+ # A short (or empty) page is the last one — Katana has no next-page cursor to follow.
+ if len(items) < PAGE_SIZE:
+ break
+
+ page += 1
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def katana_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KatanaResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = KATANA_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ 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,
+ # Katana list endpoints always return newest-first by created_at and expose no sort override,
+ # so rows arrive descending. The pipeline finalises the incremental watermark (max cursor) only
+ # at the end for desc sources, which keeps it correct despite the fixed order.
+ sort_mode="desc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/katana/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/settings.py
new file mode 100644
index 000000000000..b1ee6015359d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/settings.py
@@ -0,0 +1,93 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _timestamp_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+# Katana mutable resources expose both created_at and updated_at; updated_at is the default cursor
+# so incremental syncs also pick up edits to existing rows.
+_UPDATED_AND_CREATED: list[IncrementalField] = [_timestamp_field("updated_at"), _timestamp_field("created_at")]
+# Append-only logs (inventory movements) are immutable, so created_at is the only stable cursor.
+_CREATED_ONLY: list[IncrementalField] = [_timestamp_field("created_at")]
+
+
+@dataclass
+class KatanaEndpointConfig:
+ name: str
+ path: str
+ # Katana ids are globally unique per resource, so a single-column key is enough for most tables.
+ # Inventory has no id (it's a per-(variant, location) balance), so it uses a composite key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time column to partition on. Never updated_at — partitions must not move.
+ partition_key: str | None = "created_at"
+ default_incremental_field: str = "updated_at"
+
+
+KATANA_ENDPOINTS: dict[str, KatanaEndpointConfig] = {
+ # --- Catalog ---
+ "products": KatanaEndpointConfig(name="products", path="/products", incremental_fields=_UPDATED_AND_CREATED),
+ "materials": KatanaEndpointConfig(name="materials", path="/materials", incremental_fields=_UPDATED_AND_CREATED),
+ "variants": KatanaEndpointConfig(name="variants", path="/variants", incremental_fields=_UPDATED_AND_CREATED),
+ "services": KatanaEndpointConfig(name="services", path="/services", incremental_fields=_UPDATED_AND_CREATED),
+ # --- Partners ---
+ "customers": KatanaEndpointConfig(name="customers", path="/customers", incremental_fields=_UPDATED_AND_CREATED),
+ "suppliers": KatanaEndpointConfig(name="suppliers", path="/suppliers", incremental_fields=_UPDATED_AND_CREATED),
+ # --- Orders ---
+ "sales_orders": KatanaEndpointConfig(
+ name="sales_orders", path="/sales_orders", incremental_fields=_UPDATED_AND_CREATED
+ ),
+ "purchase_orders": KatanaEndpointConfig(
+ name="purchase_orders", path="/purchase_orders", incremental_fields=_UPDATED_AND_CREATED
+ ),
+ "manufacturing_orders": KatanaEndpointConfig(
+ name="manufacturing_orders", path="/manufacturing_orders", incremental_fields=_UPDATED_AND_CREATED
+ ),
+ "sales_returns": KatanaEndpointConfig(
+ name="sales_returns", path="/sales_returns", incremental_fields=_UPDATED_AND_CREATED
+ ),
+ # --- Stock movements ---
+ "stock_adjustments": KatanaEndpointConfig(
+ name="stock_adjustments", path="/stock_adjustments", incremental_fields=_UPDATED_AND_CREATED
+ ),
+ "stock_transfers": KatanaEndpointConfig(
+ name="stock_transfers", path="/stock_transfers", incremental_fields=_UPDATED_AND_CREATED
+ ),
+ "stocktakes": KatanaEndpointConfig(name="stocktakes", path="/stocktakes", incremental_fields=_UPDATED_AND_CREATED),
+ "inventory_movements": KatanaEndpointConfig(
+ name="inventory_movements",
+ path="/inventory_movements",
+ incremental_fields=_CREATED_ONLY,
+ default_incremental_field="created_at",
+ ),
+ # --- Full refresh only ---
+ # /inventory has no created_at/updated_at filter (it's a live per-(variant, location) balance),
+ # so there is no server-side cursor to sync incrementally.
+ "inventory": KatanaEndpointConfig(
+ name="inventory",
+ path="/inventory",
+ primary_keys=["variant_id", "location_id"],
+ incremental_fields=[],
+ partition_key=None,
+ ),
+ # /price_lists exposes no timestamp filter, and these config tables are small, so full refresh.
+ "price_lists": KatanaEndpointConfig(
+ name="price_lists", path="/price_lists", incremental_fields=[], partition_key=None
+ ),
+ "locations": KatanaEndpointConfig(name="locations", path="/locations", incremental_fields=[], partition_key=None),
+ "tax_rates": KatanaEndpointConfig(name="tax_rates", path="/tax_rates", incremental_fields=[], partition_key=None),
+}
+
+ENDPOINTS = tuple(KATANA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in KATANA_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/katana/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/source.py
index 5d07d65698a8..cc0fd4c45784 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/katana/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/source.py
@@ -1,19 +1,42 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KatanaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana.katana import (
+ KatanaResumeConfig,
+ katana_source,
+ validate_credentials as validate_katana_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class KatanaSource(SimpleSource[KatanaSourceConfig]):
+class KatanaSource(ResumableSource[KatanaSourceConfig, KatanaResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.KATANA
@@ -22,9 +45,95 @@ class KatanaSource(SimpleSource[KatanaSourceConfig]):
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.KATANA,
- category=DataWarehouseSourceCategory.E_COMMERCE,
+ category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="Katana",
- iconPath="/static/services/katana.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ keywords=["katana", "mrp", "erp", "inventory", "manufacturing"],
+ caption="""Enter your Katana API key to sync your Katana Cloud Inventory (MRP) data into the PostHog Data warehouse.
+
+Generate an API key in Katana under **Settings > API** (an active API access add-on / Professional plan is required). The key is sent as a Bearer token and has read access to your factory's data.""",
+ iconPath="/static/services/katana.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/katana",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Your Katana API key",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.katana.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A revoked/invalid key surfaces as a requests HTTPError raised by `_request_page` with a
+ # scrubbed URL. Retrying can't fix a credential problem, so stop the sync. Match the stable
+ # status + base host (the scrubbed URL keeps this prefix free of the key).
+ "401 Client Error: Unauthorized for url: https://api.katanamrp.com": "Your Katana API key is invalid or has been revoked. Generate a new key under Settings > API in Katana, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.katanamrp.com": "Your Katana API key is missing access to this data. Check the key's permissions in Katana, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: KatanaSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ supports_append=has_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: KatanaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_katana_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Katana API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KatanaResumeConfig]:
+ return ResumableSourceManager[KatanaResumeConfig](inputs, KatanaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: KatanaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[KatanaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return katana_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/katana/tests/test_katana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/tests/test_katana.py
new file mode 100644
index 000000000000..7b0dbb0969c8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/tests/test_katana.py
@@ -0,0 +1,322 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana import katana
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana.katana import (
+ KatanaRateLimitError,
+ KatanaResumeConfig,
+ KatanaRetryableError,
+ _build_base_params,
+ _clamp_future_value_to_now,
+ _format_incremental_value,
+ _request_page,
+ _wait_katana,
+ get_rows,
+ katana_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana.settings import KATANA_ENDPOINTS
+
+# A stand-in API key long enough to be caught by the transport's value-based redaction.
+_SECRET_KEY = "katana-secret-key-abcdef123456"
+
+
+def _fake_response(status_code: int = 200, body: Any = None, headers: dict[str, str] | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.headers = headers or {}
+ response.json.return_value = body if body is not None else {}
+ response.text = "" if body is None else str(body)
+ return response
+
+
+def _fake_manager(resume: KatanaResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+class TestFormatIncrementalValue:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("string_passthrough", "cursor-value", "cursor-value"),
+ ]
+ )
+ def test_format(self, _name: str, value: object, expected: str) -> None:
+ assert _format_incremental_value(value) == expected
+
+ def test_no_plus_offset(self) -> None:
+ assert "+00:00" not in _format_incremental_value(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))
+
+
+class TestClampFutureValue:
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_future_datetime_clamped_to_now(self) -> None:
+ clamped = _clamp_future_value_to_now(datetime(2027, 1, 1, tzinfo=UTC))
+ assert clamped == datetime(2026, 6, 15, 12, 0, 0, tzinfo=UTC)
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_past_datetime_untouched(self) -> None:
+ past = datetime(2026, 1, 1, tzinfo=UTC)
+ assert _clamp_future_value_to_now(past) == past
+
+
+class TestBuildBaseParams:
+ def test_incremental_filter_uses_min_suffix(self) -> None:
+ params = _build_base_params(
+ KATANA_ENDPOINTS["customers"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ assert params == {"updated_at_min": "2026-03-04T02:58:14.000Z"}
+
+ def test_respects_user_chosen_incremental_field(self) -> None:
+ params = _build_base_params(
+ KATANA_ENDPOINTS["customers"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+ assert "created_at_min" in params
+ assert "updated_at_min" not in params
+
+ def test_falls_back_to_default_incremental_field(self) -> None:
+ params = _build_base_params(
+ KATANA_ENDPOINTS["inventory_movements"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field=None,
+ )
+ assert "created_at_min" in params
+
+ def test_first_sync_has_no_filter(self) -> None:
+ params = _build_base_params(
+ KATANA_ENDPOINTS["customers"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="updated_at",
+ )
+ assert params == {}
+
+ def test_full_refresh_endpoint_never_filters(self) -> None:
+ params = _build_base_params(
+ KATANA_ENDPOINTS["inventory"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ assert params == {}
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_future_cursor_clamped(self) -> None:
+ params = _build_base_params(
+ KATANA_ENDPOINTS["customers"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2027, 1, 1, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ assert params == {"updated_at_min": "2026-06-15T12:00:00.000Z"}
+
+
+class TestRequestPage:
+ def test_429_raises_rate_limit_with_retry_after(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _fake_response(429, headers={"Retry-After": "12"})
+ with pytest.raises(KatanaRateLimitError) as exc:
+ _request_page(session, "url", {}, {}, MagicMock(), MagicMock())
+ assert exc.value.retry_after == 12.0
+
+ def test_5xx_raises_retryable(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _fake_response(503)
+ with pytest.raises(KatanaRetryableError):
+ _request_page(session, "url", {}, {}, MagicMock(), MagicMock())
+
+ @parameterized.expand([("unauthorized", 401, "Unauthorized"), ("forbidden", 403, "Forbidden")])
+ def test_4xx_raises_matchable_http_error_without_leaking_key(self, _name: str, status: int, reason: str) -> None:
+ # A credential-bearing final URL (redirect echoing the key) must never reach the exception text,
+ # but the stable `<status> Client Error: <reason> for url: https://api.katanamrp.com...` prefix
+ # that `KatanaSource.get_non_retryable_errors()` matches on must survive scrubbing.
+ response = _fake_response(status)
+ response.reason = reason
+ response.url = f"https://api.katanamrp.com/v1/customers?token={_SECRET_KEY}"
+ session = MagicMock()
+ session.get.return_value = response
+ with pytest.raises(requests.HTTPError) as exc:
+ _request_page(session, "https://api.katanamrp.com/v1/customers", {}, {}, MagicMock(), MagicMock())
+ message = str(exc.value)
+ assert _SECRET_KEY not in message
+ assert message.startswith(f"{status} Client Error: {reason} for url: https://api.katanamrp.com/v1/customers")
+
+ def test_200_returns_body(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _fake_response(200, {"data": [{"id": 1}]})
+ result = _request_page(session, "url", {}, {}, MagicMock(), MagicMock())
+ assert result == {"data": [{"id": 1}]}
+
+ def test_empty_data_list_is_accepted(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _fake_response(200, {"data": []})
+ assert _request_page(session, "url", {}, {}, MagicMock(), MagicMock()) == {"data": []}
+
+ @parameterized.expand([("missing_data_key", {"items": []}), ("not_a_dict", [1, 2, 3])])
+ def test_malformed_envelope_is_retryable(self, _name: str, body: Any) -> None:
+ # A 2xx body without a `data` key must fail loudly (retryable), not silently end the sync.
+ session = MagicMock()
+ session.get.return_value = _fake_response(200, body)
+ with pytest.raises(KatanaRetryableError):
+ _request_page(session, "url", {}, {}, MagicMock(), MagicMock())
+
+
+class TestWaitKatana:
+ def test_honours_retry_after(self) -> None:
+ state = MagicMock()
+ state.outcome.exception.return_value = KatanaRateLimitError(retry_after=7.0)
+ assert _wait_katana(state) == 7.0
+
+ def test_backoff_when_no_retry_after(self) -> None:
+ state = MagicMock()
+ state.outcome.exception.return_value = KatanaRetryableError("boom")
+ state.attempt_number = 3
+ assert _wait_katana(state) == 8.0
+
+
+class TestGetRows:
+ @patch.object(katana.time, "sleep", lambda *_: None)
+ @patch.object(katana, "make_tracked_session")
+ def test_paginates_until_short_page(self, mock_session_factory: MagicMock) -> None:
+ # Two full pages then a short page terminates pagination.
+ full_page = {"data": [{"id": i} for i in range(katana.PAGE_SIZE)]}
+ short_page = {"data": [{"id": 9001}]}
+ session = MagicMock()
+ session.get.side_effect = [
+ _fake_response(200, full_page),
+ _fake_response(200, full_page),
+ _fake_response(200, short_page),
+ ]
+ mock_session_factory.return_value = session
+
+ tables = list(
+ get_rows(api_key="k", endpoint="customers", logger=MagicMock(), resumable_source_manager=_fake_manager())
+ )
+ rows = [row for table in tables for row in table.to_pylist()]
+ assert len(rows) == 2 * katana.PAGE_SIZE + 1
+ assert session.get.call_count == 3
+ # The key must be registered with the tracked transport so it's masked in logged URLs / samples.
+ mock_session_factory.assert_called_once_with(redact_values=("k",))
+
+ @patch.object(katana.time, "sleep", lambda *_: None)
+ @patch.object(katana, "make_tracked_session")
+ def test_empty_first_page_yields_nothing(self, mock_session_factory: MagicMock) -> None:
+ session = MagicMock()
+ session.get.return_value = _fake_response(200, {"data": []})
+ mock_session_factory.return_value = session
+
+ tables = list(
+ get_rows(api_key="k", endpoint="customers", logger=MagicMock(), resumable_source_manager=_fake_manager())
+ )
+ assert tables == []
+ assert session.get.call_count == 1
+
+ @patch.object(katana.time, "sleep", lambda *_: None)
+ @patch.object(katana, "make_tracked_session")
+ def test_resumes_from_saved_page(self, mock_session_factory: MagicMock) -> None:
+ session = MagicMock()
+ session.get.return_value = _fake_response(200, {"data": [{"id": 1}]})
+ mock_session_factory.return_value = session
+
+ list(
+ get_rows(
+ api_key="k",
+ endpoint="customers",
+ logger=MagicMock(),
+ resumable_source_manager=_fake_manager(KatanaResumeConfig(page=4)),
+ )
+ )
+ # The first (and only) request must start at the resumed page, not page 1.
+ _, kwargs = session.get.call_args_list[0]
+ assert kwargs["params"]["page"] == 4
+
+ @patch.object(katana.time, "sleep", lambda *_: None)
+ @patch.object(katana, "make_tracked_session")
+ def test_incremental_filter_sent_on_every_page(self, mock_session_factory: MagicMock) -> None:
+ full_page = {"data": [{"id": i} for i in range(katana.PAGE_SIZE)]}
+ session = MagicMock()
+ session.get.side_effect = [_fake_response(200, full_page), _fake_response(200, {"data": []})]
+ mock_session_factory.return_value = session
+
+ list(
+ get_rows(
+ api_key="k",
+ endpoint="customers",
+ logger=MagicMock(),
+ resumable_source_manager=_fake_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ )
+ for call in session.get.call_args_list:
+ assert call.kwargs["params"]["updated_at_min"] == "2026-01-01T00:00:00.000Z"
+
+
+class TestKatanaSource:
+ @parameterized.expand(
+ [
+ ("customers", ["id"], "created_at"),
+ ("inventory", ["variant_id", "location_id"], None),
+ ("price_lists", ["id"], None),
+ ("inventory_movements", ["id"], "created_at"),
+ ]
+ )
+ def test_source_response_shape(self, endpoint: str, expected_pk: list[str], partition_key: str | None) -> None:
+ response = katana_source(
+ api_key="k", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == expected_pk
+ assert response.sort_mode == "desc"
+ if partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+
+class TestValidateCredentials:
+ @patch.object(katana, "make_tracked_session")
+ def test_valid_key(self, mock_session_factory: MagicMock) -> None:
+ session = MagicMock()
+ session.get.return_value = _fake_response(200)
+ mock_session_factory.return_value = session
+ assert katana.validate_credentials("good-key") is True
+ # The key must be registered with the tracked transport so it's masked in logged URLs / samples.
+ mock_session_factory.assert_called_once_with(redact_values=("good-key",))
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ @patch.object(katana, "make_tracked_session")
+ def test_invalid_key(self, _name: str, status: int, mock_session_factory: MagicMock) -> None:
+ session = MagicMock()
+ session.get.return_value = _fake_response(status)
+ mock_session_factory.return_value = session
+ assert katana.validate_credentials("bad-key") is False
+
+ @patch.object(katana, "make_tracked_session")
+ def test_network_error_is_false(self, mock_session_factory: MagicMock) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("no network")
+ mock_session_factory.return_value = session
+ assert katana.validate_credentials("key") is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/katana/tests/test_katana_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/tests/test_katana_source.py
new file mode 100644
index 000000000000..4953af02aa57
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/katana/tests/test_katana_source.py
@@ -0,0 +1,121 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KatanaSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana.katana import KatanaResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana.settings import ENDPOINTS, KATANA_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.katana.source import KatanaSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_INCREMENTAL_ENDPOINTS = [name for name, cfg in KATANA_ENDPOINTS.items() if cfg.incremental_fields]
+_FULL_REFRESH_ENDPOINTS = [name for name, cfg in KATANA_ENDPOINTS.items() if not cfg.incremental_fields]
+
+
+class TestKatanaSourceClass:
+ def test_source_type(self) -> None:
+ assert KatanaSource().source_type == ExternalDataSourceType.KATANA
+
+ def test_source_config(self) -> None:
+ config = KatanaSource().get_source_config
+ assert config.label == "Katana"
+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/katana"
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["api_key"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static catalog with no I/O, so the public docs table list must render.
+ assert KatanaSource.lists_tables_without_credentials is True
+
+ def test_non_retryable_errors_cover_auth(self) -> None:
+ errors = KatanaSource().get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = KatanaSource().get_schemas(KatanaSourceConfig(api_key="k"), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @parameterized.expand([(name,) for name in _INCREMENTAL_ENDPOINTS])
+ def test_incremental_endpoints_support_incremental(self, endpoint: str) -> None:
+ schemas = KatanaSource().get_schemas(KatanaSourceConfig(api_key="k"), team_id=1, names=[endpoint])
+ assert schemas[0].supports_incremental is True
+ assert len(schemas[0].incremental_fields) >= 1
+
+ @parameterized.expand([(name,) for name in _FULL_REFRESH_ENDPOINTS])
+ def test_full_refresh_endpoints_do_not_support_incremental(self, endpoint: str) -> None:
+ schemas = KatanaSource().get_schemas(KatanaSourceConfig(api_key="k"), team_id=1, names=[endpoint])
+ assert schemas[0].supports_incremental is False
+ assert schemas[0].incremental_fields == []
+
+ def test_get_schemas_name_filter(self) -> None:
+ schemas = KatanaSource().get_schemas(KatanaSourceConfig(api_key="k"), team_id=1, names=["products"])
+ assert [s.name for s in schemas] == ["products"]
+
+ @patch.object(source_module, "validate_katana_credentials")
+ def test_validate_credentials_success(self, mock_validate: MagicMock) -> None:
+ mock_validate.return_value = True
+ ok, error = KatanaSource().validate_credentials(KatanaSourceConfig(api_key="k"), team_id=1)
+ assert ok is True
+ assert error is None
+
+ @patch.object(source_module, "validate_katana_credentials")
+ def test_validate_credentials_failure(self, mock_validate: MagicMock) -> None:
+ mock_validate.return_value = False
+ ok, error = KatanaSource().validate_credentials(KatanaSourceConfig(api_key="bad"), team_id=1)
+ assert ok is False
+ assert error is not None
+
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = KatanaSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is KatanaResumeConfig
+
+ @patch.object(source_module, "katana_source")
+ def test_source_for_pipeline_plumbs_inputs(self, mock_katana_source: MagicMock) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "sales_orders"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01"
+ inputs.incremental_field = "updated_at"
+ manager = MagicMock()
+
+ KatanaSource().source_for_pipeline(KatanaSourceConfig(api_key="key"), manager, inputs)
+
+ mock_katana_source.assert_called_once()
+ kwargs = mock_katana_source.call_args.kwargs
+ assert kwargs["api_key"] == "key"
+ assert kwargs["endpoint"] == "sales_orders"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01"
+ assert kwargs["incremental_field"] == "updated_at"
+
+ @patch.object(source_module, "katana_source")
+ def test_source_for_pipeline_drops_cursor_on_full_refresh(self, mock_katana_source: MagicMock) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "inventory"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01"
+ inputs.incremental_field = None
+
+ KatanaSource().source_for_pipeline(KatanaSourceConfig(api_key="key"), MagicMock(), inputs)
+
+ assert mock_katana_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_keys_match_endpoints(self) -> None:
+ descriptions = KatanaSource().get_canonical_descriptions()
+ assert descriptions is CANONICAL_DESCRIPTIONS
+ # Every documented table must be a real endpoint (no stale keys).
+ assert set(descriptions).issubset(set(ENDPOINTS))