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 concord import source (#66742)

Tom Owersfe36c7f3cef1
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 f0e2a783a144..83f4c5e2edb6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -98,6 +98,7 @@ the row lists both.
| coingecko | HTTP | requests | ✅ |
| coinmarketcap | HTTP | requests + `rest_source.RESTClient` | ✅ |
| commercetools | HTTP | requests | ✅ |
+| concord | HTTP | requests | ✅ |
| confluence | HTTP | requests | ✅ |
| chartmogul | HTTP | requests | ✅ |
| circleci | HTTP | requests | ✅ |
@@ -358,7 +359,6 @@ doesn't conflict with concurrent PRs.
- cloudbeds
- coassemble
- cockroachdb
-- concord
- configcat
- constant_contact
- copper
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/canonical_descriptions.py
new file mode 100644
index 000000000000..8ba2d883c442
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/canonical_descriptions.py
@@ -0,0 +1,112 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions taken from Concord's public API docs (https://api.doc.concordnow.com). Keyed by the
+# endpoint names ConcordSource.get_schemas returns. Partial coverage is fine — anything omitted
+# falls back to LLM enrichment.
+_DOCS_URL = "https://api.doc.concordnow.com"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "organizations": {
+ "description": "Organizations (companies/workspaces) the API key can access.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the organization.",
+ "name": "Organization name.",
+ "createdAt": "Creation date as a Unix timestamp in milliseconds.",
+ },
+ },
+ "agreements": {
+ "description": "Contracts and templates in the organization, with stage, parties, tags and key dates.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "uuid": "Unique agreement identifier (Concord agreement UID).",
+ "title": "Agreement title.",
+ "status": "Lifecycle stage (e.g. DRAFT, NEGOTIATION, SIGNING, CURRENT_CONTRACT, TRASHED).",
+ "createdAt": "Creation date as a Unix timestamp in milliseconds.",
+ "modifiedAt": "Last modification date as a Unix timestamp in milliseconds.",
+ "createdBy": "User id of the creator.",
+ "organizationId": "Id of the organization that owns the agreement.",
+ "folderId": "Id of the folder containing the agreement.",
+ "signatureDate": "Signature date as a Unix timestamp in milliseconds.",
+ "endDate": "End/expiry date as a Unix timestamp in milliseconds.",
+ "tags": "Tags applied to the agreement.",
+ "parties": "Parties to the agreement.",
+ },
+ },
+ "members": {
+ "description": "Members of the organization, including their role and group memberships.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "userOrganizationId": "Stable identifier of the member within the organization (primary key).",
+ "user": "The underlying user account.",
+ "role": "The member's organization role.",
+ "groups": "Groups the member belongs to.",
+ "isActive": "Whether the member account is active.",
+ "createdAt": "When the member joined, as a Unix timestamp in milliseconds.",
+ },
+ },
+ "groups": {
+ "description": "User groups (teams) defined in the organization.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the group.",
+ "name": "Group name.",
+ },
+ },
+ "folders": {
+ "description": "Folder tree of the organization, flattened to one row per folder.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the folder.",
+ "name": "Folder name.",
+ "parentId": "Id of the parent folder (null for the root).",
+ "documentCount": "Number of documents in the folder.",
+ },
+ },
+ "clauses": {
+ "description": "Active clauses in the organization's clause library.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the clause.",
+ "title": "Clause title.",
+ "createdAt": "Creation date as a Unix timestamp in milliseconds.",
+ },
+ },
+ "tags": {
+ "description": "Tags defined in the organization for classifying agreements.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the tag.",
+ "name": "Tag name.",
+ },
+ },
+ "reports": {
+ "description": "Saved reports in the organization.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the report.",
+ "name": "Report name.",
+ "lastUpdatedAt": "Last modification date as a Unix timestamp in milliseconds.",
+ },
+ },
+ "approvals": {
+ "description": "Company-level approval workflows configured in the organization.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the approval.",
+ },
+ },
+ "events": {
+ "description": "Organization audit log of lifecycle actions. Requires the Administrator role.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the event.",
+ "createdAt": "When the event occurred, as a Unix timestamp in milliseconds.",
+ "type": "Event type (e.g. AGREEMENT_CREATE, AGREEMENT_SIGN, ORGANIZATION_ADD_USER).",
+ "actor": "The user or system that triggered the event.",
+ "event": "The object the event relates to (e.g. the agreement).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.posthog.com.md b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.posthog.com.md
new file mode 100644
index 000000000000..594ef9aa96c3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.posthog.com.md
@@ -0,0 +1,77 @@
+---
+title: Linking Concord as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Concord
+beta: true
+---
+
+import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"
+import SyncModes from "../\_snippets/sync-modes.mdx"
+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"
+import AlphaRelease from "../\_snippets/alpha-release.mdx"
+
+<AlphaRelease />
+
+[Concord](https://www.concord.app/) is a contract lifecycle management (CLM) platform for
+e-signatures, contract storage, negotiation, and approvals. This source syncs your agreements,
+folders, clauses, tags, reports, organization members, and audit events into the PostHog data
+warehouse so you can join contract data with your product and revenue data.
+
+## Prerequisites
+
+- A Concord account on a paid plan (API key generation is only available on paid plans).
+- A Concord API key, generated from your account settings. It is sent as an `X-API-KEY` header.
+- For the **events** (audit log) table, the API key must belong to a user with the **Administrator**
+ role.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+You'll need:
+
+- **API key** – generate one in your Concord account settings. Concord sends it as the `X-API-KEY`
+ header on every request.
+- **Environment** – choose **Production** (`api.concordnow.com`) or **Sandbox**
+ (`uat.concordnow.com`). The API key is environment-specific, so make sure it matches.
+- **Organization ID** (optional) – leave blank to use the first organization your API key can
+ access. Set it explicitly if your key has access to multiple organizations and you want a specific
+ one.
+
+## Sync modes
+
+<SyncModes />
+
+Agreements expose Concord's server-side `modifiedAt`/`createdAt` timestamp filters, so they support
+**incremental** syncs. The audit **events** log is immutable and supports **append**-only syncing.
+Every other table is **full refresh** only, since Concord does not expose a server-side change
+filter for them.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **401 Unauthorized** – the API key is invalid, revoked, or for the wrong environment. Generate a
+ new key in Concord and confirm the Production/Sandbox selection matches.
+- **403 Forbidden on the events table** – the audit log requires the Administrator role. Either use
+ a key for an admin user or deselect the **events** table.
+- **No organizations accessible** – the API key can't see any organization. Confirm the key is valid
+ and, if you set an Organization ID, that the key has access to it.
+
+<TroubleshootingLink />
+
+<!--
+DRAFT — this user-facing doc belongs in the posthog.com repo at
+contents/docs/cdp/sources/concord.md (served at /docs/cdp/sources/concord). No posthog.com checkout
+was available when this was written, so it is committed alongside the source to travel with the PR.
+Copy it to posthog.com (dropping this comment) and run
+`python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`.
+-->
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py
new file mode 100644
index 000000000000..8b7544fc20a7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py
@@ -0,0 +1,461 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+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.concord.settings import (
+ AGREEMENT_STATUSES,
+ CONCORD_ENDPOINTS,
+ ConcordEndpointConfig,
+)
+
+# Concord exposes the same REST surface on two hosts; the API key is environment-specific.
+CONCORD_BASE_URLS = {
+ "production": "https://api.concordnow.com/api/rest/1",
+ "sandbox": "https://uat.concordnow.com/api/rest/1",
+}
+
+REQUEST_TIMEOUT_SECONDS = 60
+# The events audit endpoint rejects ranges longer than 7 days, so walk it a week at a time.
+EVENTS_WINDOW_DAYS = 7
+
+
+class ConcordRetryableError(Exception):
+ pass
+
+
+class ConcordResumeConfig:
+ # Page index to fetch on resume (page-number pagination). 0-based, matching Concord.
+ page: Optional[int] = None
+ # Row offset to fetch on resume (offset pagination).
+ offset: Optional[int] = None
+ # Rows of `page`/`offset` already emitted, so a resume skips them rather than re-walking the
+ # whole page. Advances on every mid-page flush so progress is monotonic even across crashes.
+ row_offset: Optional[int] = None
+ # Start of the next audit-log window as a Unix ms timestamp (events_window pagination).
+ window_start_ms: Optional[int] = None
+
+
+def base_url_for_environment(environment: str | None) -> str:
+ return CONCORD_BASE_URLS.get(environment or "production", CONCORD_BASE_URLS["production"])
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"X-API-KEY": api_key, "Accept": "application/json"}
+
+
+def _to_epoch_ms(value: Any) -> int | None:
+ """Coerce an incremental cursor value into a Unix millisecond timestamp.
+
+ Concord's date filters are all Unix epoch milliseconds. The pipeline may hand us a datetime
+ (first parse) or an int/float (already-stored cursor), so normalize both.
+ """
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return int(aware.timestamp() * 1000)
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
+ if isinstance(value, int | float):
+ return int(value)
+ return None
+
+
+def _epoch_ms_to_date(value: int) -> date:
+ return datetime.fromtimestamp(value / 1000, tz=UTC).date()
+
+
+def _build_url(base_url: str, path: str, params: dict[str, Any] | None = None) -> str:
+ url = f"{base_url}{path}"
+ if not params:
+ return url
+ # doseq=True so list-valued params (e.g. repeated `statuses`) expand to repeated keys.
+ return f"{url}?{urlencode(params, doseq=True)}"
+
+
+@retry(
+ retry=retry_if_exception_type((ConcordRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ConcordRetryableError(f"Concord API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Don't log the response body: Concord error payloads can echo contract/member/audit data
+ # back, and these logs are readable internally. Status + URL is enough to triage.
+ logger.error(f"Concord API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def resolve_organization_id(
+ session: requests.Session, base_url: str, api_key: str, configured_org_id: str | None, logger: FilteringBoundLogger
+) -> str:
+ """Return the organization id to scope requests under.
+
+ Uses the user-provided id when set, otherwise resolves the first organization the API key can
+ see. Every data endpoint is scoped under /organizations/{id}/, so this must succeed before any
+ org-scoped sync runs.
+ """
+ if configured_org_id and configured_org_id.strip():
+ return configured_org_id.strip()
+
+ data = _fetch(session, f"{base_url}/user/me/organizations", _headers(api_key), logger)
+ organizations = data.get("organizations") or []
+ if not organizations:
+ raise ValueError("No Concord organizations are accessible with this API key.")
+ return str(organizations[0]["id"])
+
+
+def validate_credentials(api_key: str, environment: str | None) -> bool:
+ base_url = base_url_for_environment(environment)
+ try:
+ # Concord auth is a custom `X-API-KEY` header the name-based scrubber can't recognise, so
+ # redact the key by value from logged URLs and captured HTTP samples.
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ f"{base_url}/user/me/organizations", headers=_headers(api_key), timeout=10
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _select_rows(
+ payload: Any, selector: str | None, logger: FilteringBoundLogger | None = None
+) -> list[dict[str, Any]]:
+ if selector is None:
+ return []
+ if isinstance(payload, dict):
+ # A non-empty body that lacks the expected key usually means Concord changed its response
+ # shape — surface it so the sync doesn't silently complete with zero rows.
+ if selector not in payload and payload and logger is not None:
+ logger.warning(f"Concord response missing expected key '{selector}'; got keys={list(payload.keys())}")
+ rows = payload.get(selector)
+ else:
+ rows = None
+ return rows or []
+
+
+def _scope_organizations_to_org(rows: list[dict[str, Any]], configured_org_id: str | None) -> list[dict[str, Any]]:
+ """Restrict the organizations listing to the single org this source syncs.
+
+ /user/me/organizations returns every org the API key can reach, so without this filter a source
+ configured for one organization would still expose every other accessible org's name/id in the
+ warehouse table. Mirror resolve_organization_id: keep the configured org, else the first one.
+ """
+ if not rows:
+ return rows
+ if configured_org_id and configured_org_id.strip():
+ target = configured_org_id.strip()
+ return [row for row in rows if str(row.get("id")) == target]
+ return rows[:1]
+
+
+def _flatten_folder_tree(node: Any) -> Iterator[dict[str, Any]]:
+ """Flatten Concord's nested folder tree into one row per folder.
+
+ Each row keeps the folder's own fields (id, name, parentId, …) but drops the nested `children`
+ array so the warehouse table stays flat; hierarchy is still recoverable via `parentId`.
+ """
+ if not isinstance(node, dict):
+ return
+ children = node.get("children") or []
+ row = {key: value for key, value in node.items() if key != "children"}
+ if "id" in row:
+ yield row
+ for child in children:
+ yield from _flatten_folder_tree(child)
+
+
+def _agreement_incremental_params(
+ incremental_field: str | None,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ last_ms = _to_epoch_ms(db_incremental_field_last_value)
+ if last_ms is None:
+ return {}
+ # `modifiedAt`/`createdAt` are the only fields the schema advertises; default to modifiedAt.
+ field = incremental_field if incremental_field in ("modifiedAt", "createdAt") else "modifiedAt"
+ return {f"{field}.from": last_ms}
+
+
+def _iter_page(
+ session: requests.Session,
+ base_url: str,
+ path: str,
+ headers: dict[str, str],
+ config: ConcordEndpointConfig,
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ manager: ResumableSourceManager[ConcordResumeConfig],
+ base_params: dict[str, Any],
+ start_page: int,
+ start_row_offset: int = 0,
+) -> Iterator[Any]:
+ page = start_page
+ # Rows of the first page already emitted in a prior run; skip them so a resume doesn't re-walk
+ # the whole page. Only the page we resume on carries a non-zero skip.
+ skip = start_row_offset
+ while True:
+ params = {**base_params, "page": page, "numberOfItemsByPage": config.page_size}
+ payload = _fetch(session, _build_url(base_url, path, params), headers, logger)
+ rows = _select_rows(payload, config.data_selector, logger)
+ for local_index, row in enumerate(rows):
+ if local_index < skip:
+ continue
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # A byte-limit flush can fire mid-page. Checkpoint this page plus how many of its
+ # rows are now committed, so a resume skips them instead of re-emitting from the
+ # page start. row_offset advances on every flush, so progress is monotonic and a
+ # crash can't pin the import to replaying the same rows forever.
+ manager.save_state(ConcordResumeConfig(page=page, row_offset=local_index + 1))
+ skip = 0
+ if len(rows) < config.page_size:
+ break
+ page += 1
+
+
+def _iter_offset(
+ session: requests.Session,
+ base_url: str,
+ path: str,
+ headers: dict[str, str],
+ config: ConcordEndpointConfig,
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ manager: ResumableSourceManager[ConcordResumeConfig],
+ base_params: dict[str, Any],
+ start_offset: int,
+ start_row_offset: int = 0,
+) -> Iterator[Any]:
+ offset = start_offset
+ # Rows of the first window already emitted in a prior run; skip them so a resume doesn't re-walk
+ # the whole window. Only the offset we resume on carries a non-zero skip.
+ skip = start_row_offset
+ while True:
+ params = {**base_params, config.offset_param: offset, "limit": config.page_size}
+ payload = _fetch(session, _build_url(base_url, path, params), headers, logger)
+ rows = _select_rows(payload, config.data_selector, logger)
+ for local_index, row in enumerate(rows):
+ if local_index < skip:
+ continue
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # A byte-limit flush can fire mid-window. Checkpoint this offset plus how many of
+ # its rows are now committed, so a resume skips them instead of re-emitting from the
+ # window start. row_offset advances on every flush, so progress is monotonic and a
+ # crash can't pin the import to replaying the same rows forever.
+ manager.save_state(ConcordResumeConfig(offset=offset, row_offset=local_index + 1))
+ skip = 0
+ if len(rows) < config.page_size:
+ break
+ offset += config.page_size
+
+
+def _iter_events_windows(
+ session: requests.Session,
+ base_url: str,
+ path: str,
+ headers: dict[str, str],
+ config: ConcordEndpointConfig,
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ manager: ResumableSourceManager[ConcordResumeConfig],
+ start_ms: int,
+ start_row_offset: int = 0,
+) -> Iterator[Any]:
+ window_start = _epoch_ms_to_date(start_ms)
+ today = datetime.now(UTC).date()
+ # Rows of the first window already emitted in a prior run; skip them so a resume doesn't re-walk
+ # the whole (up to 7-day) window. Only the window we resume on carries a non-zero skip.
+ skip = start_row_offset
+ while window_start <= today:
+ window_end = min(window_start + timedelta(days=EVENTS_WINDOW_DAYS), today)
+ params = {"start": window_start.isoformat(), "end": window_end.isoformat()}
+ window_start_ms = int(datetime.combine(window_start, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
+ payload = _fetch(session, _build_url(base_url, path, params), headers, logger)
+ for local_index, row in enumerate(_select_rows(payload, config.data_selector, logger)):
+ if local_index < skip:
+ continue
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # A byte-limit flush can fire mid-window. Checkpoint this window plus how many of
+ # its rows are now committed, so a resume skips them instead of re-walking the whole
+ # window. row_offset advances on every flush, so progress is monotonic and a crash
+ # can't pin the import to replaying the same window forever.
+ manager.save_state(ConcordResumeConfig(window_start_ms=window_start_ms, row_offset=local_index + 1))
+ skip = 0
+ if window_end >= today:
+ break
+ # Start the next window on the boundary day we just queried, so the windows overlap by one
+ # day. We don't know whether Concord's `end` is inclusive or exclusive, and the overlap is
+ # free: merge dedupes on the event id primary key, so no event can fall through the seam.
+ next_start = window_end
+ manager.save_state(
+ ConcordResumeConfig(
+ window_start_ms=int(datetime.combine(next_start, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
+ )
+ )
+ window_start = next_start
+
+
+def get_rows(
+ api_key: str,
+ environment: str | None,
+ organization_id: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[ConcordResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = CONCORD_ENDPOINTS[endpoint]
+ base_url = base_url_for_environment(environment)
+ headers = _headers(api_key)
+ # Concord auth is a custom `X-API-KEY` header the name-based scrubber can't recognise, so redact
+ # the key by value from logged URLs and captured HTTP samples.
+ session = make_tracked_session(redact_values=(api_key,))
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+
+ org_id = resolve_organization_id(session, base_url, api_key, organization_id, logger) if config.org_scoped else None
+ path = config.path.format(organization_id=org_id) if org_id else config.path
+
+ base_params: dict[str, Any] = {}
+ if config.org_in_query and org_id:
+ base_params["organizationId"] = org_id
+
+ resume = manager.load_state() if manager.can_resume() else None
+
+ if config.pagination == "single":
+ payload = _fetch(session, _build_url(base_url, path, base_params), headers, logger)
+ rows = _select_rows(payload, config.data_selector, logger)
+ if config.scope_to_org:
+ rows = _scope_organizations_to_org(rows, organization_id)
+ for row in rows:
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ elif config.pagination == "folders_tree":
+ payload = _fetch(session, _build_url(base_url, path, base_params), headers, logger)
+ nodes = payload if isinstance(payload, list) else [payload]
+ for node in nodes:
+ for row in _flatten_folder_tree(node):
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ elif config.pagination == "page":
+ if should_use_incremental_field and config.supports_incremental:
+ base_params.update(_agreement_incremental_params(incremental_field, db_incremental_field_last_value))
+ if endpoint == "agreements":
+ base_params["statuses"] = AGREEMENT_STATUSES
+ start_page = resume.page if resume and resume.page is not None else 0
+ start_row_offset = resume.row_offset if resume and resume.row_offset is not None else 0
+ yield from _iter_page(
+ session,
+ base_url,
+ path,
+ headers,
+ config,
+ logger,
+ batcher,
+ manager,
+ base_params,
+ start_page,
+ start_row_offset,
+ )
+
+ elif config.pagination == "offset":
+ start_offset = resume.offset if resume and resume.offset is not None else 0
+ start_row_offset = resume.row_offset if resume and resume.row_offset is not None else 0
+ yield from _iter_offset(
+ session,
+ base_url,
+ path,
+ headers,
+ config,
+ logger,
+ batcher,
+ manager,
+ base_params,
+ start_offset,
+ start_row_offset,
+ )
+
+ elif config.pagination == "events_window":
+ if resume and resume.window_start_ms is not None:
+ start_ms = resume.window_start_ms
+ else:
+ last_ms = _to_epoch_ms(db_incremental_field_last_value) if should_use_incremental_field else None
+ if last_ms is None and config.default_lookback_days is not None:
+ last_ms = int((datetime.now(UTC) - timedelta(days=config.default_lookback_days)).timestamp() * 1000)
+ start_ms = last_ms if last_ms is not None else int(datetime.now(UTC).timestamp() * 1000)
+ start_row_offset = resume.row_offset if resume and resume.row_offset is not None else 0
+ yield from _iter_events_windows(
+ session, base_url, path, headers, config, logger, batcher, manager, start_ms, start_row_offset
+ )
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def concord_source(
+ api_key: str,
+ environment: str | None,
+ organization_id: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[ConcordResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = CONCORD_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ environment=environment,
+ organization_id=organization_id,
+ endpoint=endpoint,
+ logger=logger,
+ manager=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,
+ # Concord's list endpoints don't guarantee an order we can pass reliably, so we walk the
+ # entire (optionally server-filtered) result set every sync. The pipeline's incremental
+ # watermark takes the running max, so ascending is the correct, safe declaration here.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/settings.py
new file mode 100644
index 000000000000..4d8d37c8a70f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/settings.py
@@ -0,0 +1,195 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# How a list endpoint is paginated:
+# - "page": page-number pagination (page + numberOfItemsByPage), page index starts at 0.
+# - "offset": offset pagination (start/offset + limit).
+# - "single": one request, the whole collection comes back in a wrapper object.
+# - "folders_tree": single request returning a nested folder tree we flatten into rows.
+# - "events_window": audit log capped at 7-day windows, walked one week at a time.
+PaginationStyle = Literal["page", "offset", "single", "folders_tree", "events_window"]
+
+# Concord returns the full agreement list only when at least one stage filter is supplied, so we
+# request every documented stage. Keeping this explicit (rather than relying on a default) means a
+# new stage Concord adds later is a visible diff here, not a silent gap in synced data.
+AGREEMENT_STATUSES = [
+ "DRAFT",
+ "VALIDATION",
+ "NEGOTIATION",
+ "SIGNING",
+ "UNKNOWN_CONTRACT",
+ "FUTURE_CONTRACT",
+ "CURRENT_CONTRACT",
+ "COMPLETED_CONTRACT",
+ "COMPLETED_CANCEL_CONTRACT",
+ "COMPLETED_CONTRACT_RENEWABLE",
+ "BROKEN",
+ "TRASHED",
+ "NEGO_INVITE",
+ "TEMPLATE",
+ "TEMPLATE_AUTO",
+]
+
+
+@dataclass
+class ConcordEndpointConfig:
+ name: str
+ path: str # may contain a `{organization_id}` placeholder
+ pagination: PaginationStyle
+ # Key inside the JSON response holding the row array (e.g. "items", "members"). None for
+ # endpoints whose body is itself the collection wrapper handled specially (folders tree).
+ data_selector: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Partition key — must be a STABLE creation-style field, never updated_at/modifiedAt.
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Only true where Concord exposes a genuine server-side timestamp filter for this resource.
+ supports_incremental: bool = False
+ # Immutable, append-only resources (the audit event log) set this so the UI offers append sync.
+ supports_append: bool = False
+ should_sync_default: bool = True
+ # `/tags` takes the organization as a query param rather than a path segment.
+ org_in_query: bool = False
+ # Endpoints scoped under /organizations/{id}/ need the resolved org id; /user/me/organizations
+ # does not.
+ org_scoped: bool = True
+ # /user/me/organizations lists every org the API key can reach. Set this so the synced rows are
+ # filtered down to the single org this source is scoped to, rather than leaking every accessible
+ # org's name/id into the warehouse table.
+ scope_to_org: bool = False
+ page_size: int = 100
+ # Offset pagination uses different query param names per resource (`start` vs `offset`).
+ offset_param: str = "offset"
+ requires_admin: bool = False
+ # Limit the first sync of an unbounded append-only resource to the last N days.
+ default_lookback_days: Optional[int] = None
+ description: Optional[str] = None
+
+
+_AGREEMENT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "modifiedAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "modifiedAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "createdAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+_EVENT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "createdAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+CONCORD_ENDPOINTS: dict[str, ConcordEndpointConfig] = {
+ "organizations": ConcordEndpointConfig(
+ name="organizations",
+ path="/user/me/organizations",
+ pagination="single",
+ data_selector="organizations",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ org_scoped=False,
+ scope_to_org=True,
+ ),
+ "agreements": ConcordEndpointConfig(
+ name="agreements",
+ path="/user/me/organizations/{organization_id}/agreements",
+ pagination="page",
+ data_selector="items",
+ primary_keys=["uuid"],
+ partition_key="createdAt",
+ incremental_fields=_AGREEMENT_INCREMENTAL_FIELDS,
+ supports_incremental=True,
+ page_size=100,
+ ),
+ "members": ConcordEndpointConfig(
+ name="members",
+ path="/organizations/{organization_id}/members",
+ pagination="offset",
+ data_selector="members",
+ # MemberDto has no `id`; `userOrganizationId` is the stable per-org member identifier.
+ primary_keys=["userOrganizationId"],
+ partition_key="createdAt",
+ page_size=100,
+ offset_param="start",
+ ),
+ "groups": ConcordEndpointConfig(
+ name="groups",
+ path="/organizations/{organization_id}/groups",
+ pagination="single",
+ data_selector="groups",
+ primary_keys=["id"],
+ ),
+ "folders": ConcordEndpointConfig(
+ name="folders",
+ path="/organizations/{organization_id}/folders",
+ pagination="folders_tree",
+ primary_keys=["id"],
+ ),
+ "clauses": ConcordEndpointConfig(
+ name="clauses",
+ path="/organizations/{organization_id}/clauses",
+ pagination="offset",
+ data_selector="organizationClauses",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ page_size=100,
+ ),
+ "tags": ConcordEndpointConfig(
+ name="tags",
+ path="/tags",
+ pagination="single",
+ data_selector="tags",
+ primary_keys=["id"],
+ org_in_query=True,
+ ),
+ "reports": ConcordEndpointConfig(
+ name="reports",
+ path="/organizations/{organization_id}/reports",
+ pagination="page",
+ data_selector="reports",
+ primary_keys=["id"],
+ page_size=100,
+ ),
+ "approvals": ConcordEndpointConfig(
+ name="approvals",
+ path="/organizations/{organization_id}/approvals",
+ pagination="single",
+ data_selector="approvals",
+ primary_keys=["id"],
+ ),
+ "events": ConcordEndpointConfig(
+ name="events",
+ path="/organizations/{organization_id}/events",
+ pagination="events_window",
+ data_selector="events",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ incremental_fields=_EVENT_INCREMENTAL_FIELDS,
+ supports_incremental=True,
+ supports_append=True,
+ should_sync_default=False, # admin-only endpoint; off by default so non-admins aren't blocked
+ requires_admin=True,
+ default_lookback_days=365,
+ description="Organization audit log. Requires the Administrator role. Append only.",
+ ),
+}
+
+ENDPOINTS = tuple(CONCORD_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in CONCORD_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/source.py
index 74cf5bf595fa..5542628ceb86 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/source.py
@@ -1,19 +1,53 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-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.concord.concord import (
+ ConcordResumeConfig,
+ concord_source,
+ validate_credentials as validate_concord_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.concord.settings import (
+ CONCORD_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ConcordSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ConcordSource(SimpleSource[ConcordSourceConfig]):
+class ConcordSource(ResumableSource[ConcordSourceConfig, ConcordResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `environment` selects which Concord host the stored API key is sent to, and
+ # `organization_id` scopes which organization's data that key reads. Retargeting either
+ # without re-entering the key would let an editor exfiltrate the preserved credential or
+ # pull another organization's data, so both must force secret re-entry on update.
+ return ["environment", "organization_id"]
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CONCORD
@@ -24,7 +58,114 @@ class ConcordSource(SimpleSource[ConcordSourceConfig]):
name=SchemaExternalDataSourceType.CONCORD,
category=DataWarehouseSourceCategory.SALES,
label="Concord",
- iconPath="/static/services/concord.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Concord API key to pull your contract lifecycle data into the PostHog Data warehouse.
+
+You can generate an API key in your Concord account settings (API key generation requires a paid plan). Concord sends it as an `X-API-KEY` header.
+
+Leave **Organization ID** blank to use the first organization your API key can access.""",
+ iconPath="/static/services/concord.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/concord",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="production",
+ options=[
+ SourceFieldSelectConfigOption(label="Production", value="production"),
+ SourceFieldSelectConfigOption(label="Sandbox", value="sandbox"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="organization_id",
+ label="Organization ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="Leave blank to use your first organization",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.concord.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.concordnow.com": "Your Concord API key is invalid or has been revoked. Generate a new key in your Concord account settings, then reconnect.",
+ "401 Client Error: Unauthorized for url: https://uat.concordnow.com": "Your Concord API key is invalid or has been revoked. Generate a new key in your Concord account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.concordnow.com": "Your Concord API key is missing the permissions needed to sync this data (the events log requires the Administrator role). Adjust the key's access, then reconnect.",
+ "403 Client Error: Forbidden for url: https://uat.concordnow.com": "Your Concord API key is missing the permissions needed to sync this data (the events log requires the Administrator role). Adjust the key's access, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: ConcordSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = CONCORD_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_append or endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ description=endpoint_config.description,
+ )
+
+ 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: ConcordSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_concord_credentials(config.api_key, config.environment):
+ return True, None
+ return False, "Invalid Concord API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ConcordResumeConfig]:
+ return ResumableSourceManager[ConcordResumeConfig](inputs, ConcordResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ConcordSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ConcordResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return concord_source(
+ api_key=config.api_key,
+ environment=config.environment,
+ organization_id=config.organization_id,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ 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/concord/tests/test_concord.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
new file mode 100644
index 000000000000..11a87c1b0f11
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
@@ -0,0 +1,389 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest import mock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.concord import concord
+from products.warehouse_sources.backend.temporal.data_imports.sources.concord.concord import (
+ ConcordResumeConfig,
+ _agreement_incremental_params,
+ _flatten_folder_tree,
+ _iter_events_windows,
+ _iter_page,
+ _to_epoch_ms,
+ base_url_for_environment,
+ concord_source,
+ get_rows,
+ resolve_organization_id,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.concord.settings import CONCORD_ENDPOINTS
+
+
+class FakeManager(ResumableSourceManager[ConcordResumeConfig]):
+ """In-memory stand-in for ResumableSourceManager so transport tests stay off Redis."""
+
+ def __init__(self, state: ConcordResumeConfig | None = None):
+ self._state = state
+ self.saved: list[ConcordResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> ConcordResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: ConcordResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(generator) -> list[dict[str, Any]]:
+ """Flatten the pyarrow tables a transport generator yields into plain row dicts."""
+ rows: list[dict[str, Any]] = []
+ for table in generator:
+ rows.extend(table.to_pylist())
+ return rows
+
+
+def _run(
+ endpoint: str,
+ payloads: list[Any],
+ *,
+ manager: FakeManager | None = None,
+ organization_id: str | None = "42",
+ **kwargs,
+):
+ """Drive get_rows with _fetch stubbed to return `payloads` in order; record requested URLs."""
+ urls: list[str] = []
+ manager = manager or FakeManager()
+
+ def fake_fetch(session, url, headers, logger):
+ urls.append(url)
+ return payloads[min(len(urls) - 1, len(payloads) - 1)]
+
+ with mock.patch.object(concord, "_fetch", side_effect=fake_fetch):
+ rows = _collect(
+ get_rows(
+ api_key="key",
+ environment="production",
+ organization_id=organization_id,
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ manager=manager,
+ **kwargs,
+ )
+ )
+ return rows, urls, manager
+
+
+class TestToEpochMs:
+ @parameterized.expand(
+ [
+ ("none", None, None),
+ ("datetime_utc", datetime(2024, 1, 1, tzinfo=UTC), 1704067200000),
+ ("naive_datetime", datetime(2024, 1, 1), 1704067200000),
+ ("date", date(2024, 1, 1), 1704067200000),
+ ("int_passthrough", 1700000000000, 1700000000000),
+ ("float", 1700000000000.0, 1700000000000),
+ ]
+ )
+ def test_to_epoch_ms(self, _name, value, expected):
+ assert _to_epoch_ms(value) == expected
+
+
+class TestBaseUrl:
+ @parameterized.expand(
+ [
+ ("production", "production", "https://api.concordnow.com/api/rest/1"),
+ ("sandbox", "sandbox", "https://uat.concordnow.com/api/rest/1"),
+ ("none_defaults_to_production", None, "https://api.concordnow.com/api/rest/1"),
+ ("unknown_defaults_to_production", "staging", "https://api.concordnow.com/api/rest/1"),
+ ]
+ )
+ def test_base_url_for_environment(self, _name, environment, expected):
+ assert base_url_for_environment(environment) == expected
+
+
+class TestFlattenFolderTree:
+ def test_flattens_nested_tree_to_one_row_per_folder(self):
+ root = {
+ "id": 1,
+ "name": "root",
+ "parentId": None,
+ "children": [
+ {"id": 2, "name": "a", "parentId": 1, "children": []},
+ {
+ "id": 3,
+ "name": "b",
+ "parentId": 1,
+ "children": [{"id": 4, "name": "c", "parentId": 3, "children": []}],
+ },
+ ],
+ }
+ rows = list(_flatten_folder_tree(root))
+ assert [r["id"] for r in rows] == [1, 2, 3, 4]
+ # children arrays are dropped so the warehouse row stays flat
+ assert all("children" not in r for r in rows)
+ assert rows[3]["parentId"] == 3
+
+ def test_skips_nodes_without_id(self):
+ assert list(_flatten_folder_tree({"name": "no id", "children": []})) == []
+
+
+class TestAgreementIncrementalParams:
+ @parameterized.expand(
+ [
+ ("modified", "modifiedAt", 1700000000000, {"modifiedAt.from": 1700000000000}),
+ ("created", "createdAt", 1700000000000, {"createdAt.from": 1700000000000}),
+ ("unknown_field_defaults_to_modified", "weird", 1700000000000, {"modifiedAt.from": 1700000000000}),
+ ("no_value", "modifiedAt", None, {}),
+ ]
+ )
+ def test_agreement_incremental_params(self, _name, field, value, expected):
+ assert _agreement_incremental_params(field, value) == expected
+
+
+class TestResolveOrganizationId:
+ def test_uses_configured_org_id_without_request(self):
+ session = mock.MagicMock()
+ with mock.patch.object(concord, "_fetch") as fetch:
+ assert resolve_organization_id(session, "https://x", "key", "123", mock.MagicMock()) == "123"
+ fetch.assert_not_called()
+
+ def test_resolves_first_org_when_blank(self):
+ session = mock.MagicMock()
+ with mock.patch.object(concord, "_fetch", return_value={"organizations": [{"id": 99}, {"id": 100}]}):
+ assert resolve_organization_id(session, "https://x", "key", None, mock.MagicMock()) == "99"
+
+ def test_raises_when_no_org_accessible(self):
+ session = mock.MagicMock()
+ with mock.patch.object(concord, "_fetch", return_value={"organizations": []}):
+ with pytest.raises(ValueError, match="No Concord organizations"):
+ resolve_organization_id(session, "https://x", "key", "", mock.MagicMock())
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_validate_credentials_status_mapping(self, _name, status_code, expected):
+ session = mock.MagicMock()
+ session.get.return_value.status_code = status_code
+ with mock.patch.object(concord, "make_tracked_session", return_value=session):
+ assert validate_credentials("key", "production") is expected
+
+ def test_validate_credentials_swallows_exceptions(self):
+ with mock.patch.object(concord, "make_tracked_session", side_effect=RuntimeError("boom")):
+ assert validate_credentials("key", "production") is False
+
+
+class TestSinglePagination:
+ def test_single_request_selects_rows(self):
+ rows, urls, _ = _run("groups", [{"groups": [{"id": 1}, {"id": 2}]}])
+ assert [r["id"] for r in rows] == [1, 2]
+ assert len(urls) == 1
+
+ def test_tags_passes_organization_id_query_param(self):
+ _rows, urls, _ = _run("tags", [{"tags": [{"id": 1}]}])
+ assert "organizationId=42" in urls[0]
+
+ def test_organizations_scoped_to_configured_org(self):
+ # /user/me/organizations lists every accessible org; the synced table must not leak the
+ # others when the source is configured for a specific org.
+ payload = [{"organizations": [{"id": 42, "name": "mine"}, {"id": 7, "name": "someone else"}]}]
+ rows, _urls, _ = _run("organizations", payload)
+ assert [r["id"] for r in rows] == [42]
+
+ def test_organizations_falls_back_to_first_org_when_unconfigured(self):
+ payload = [{"organizations": [{"id": 7, "name": "first"}, {"id": 8, "name": "second"}]}]
+ rows, _urls, _ = _run("organizations", payload, organization_id=None)
+ assert [r["id"] for r in rows] == [7]
+
+
+class TestPagePagination:
+ def test_walks_pages_until_short_page(self, monkeypatch):
+ monkeypatch.setattr(CONCORD_ENDPOINTS["agreements"], "page_size", 2)
+ payloads = [
+ {"items": [{"uuid": "a"}, {"uuid": "b"}]},
+ {"items": [{"uuid": "c"}]},
+ ]
+ rows, urls, _ = _run("agreements", payloads, should_use_incremental_field=False)
+ assert [r["uuid"] for r in rows] == ["a", "b", "c"]
+ assert "page=0" in urls[0]
+ assert "page=1" in urls[1]
+ # agreements require the statuses filter on every request
+ assert "statuses=DRAFT" in urls[0]
+
+ def test_resumes_from_saved_page(self, monkeypatch):
+ monkeypatch.setattr(CONCORD_ENDPOINTS["agreements"], "page_size", 2)
+ manager = FakeManager(ConcordResumeConfig(page=7))
+ _rows, urls, _ = _run("agreements", [{"items": [{"uuid": "x"}]}], manager=manager)
+ assert "page=7" in urls[0]
+
+ def test_incremental_adds_modified_at_filter(self, monkeypatch):
+ monkeypatch.setattr(CONCORD_ENDPOINTS["agreements"], "page_size", 2)
+ _rows, urls, _ = _run(
+ "agreements",
+ [{"items": [{"uuid": "a"}]}],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000000,
+ incremental_field="modifiedAt",
+ )
+ assert "modifiedAt.from=1700000000000" in urls[0]
+
+
+class TestIntraPageResume:
+ """A byte-limit flush can fire mid-page. The checkpoint must record intra-page progress so a
+ resume skips already-emitted rows instead of replaying the whole page forever (a DoS vector)."""
+
+ def _iter(self, *, start_page=0, start_row_offset=0, manager=None, page_rows=None):
+ config = CONCORD_ENDPOINTS["agreements"]
+ manager = manager or FakeManager()
+ # chunk_size=2 flushes every two rows; the 5-row page is shorter than page_size so the walk
+ # stops after one page.
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=2)
+ rows = page_rows if page_rows is not None else [{"uuid": str(i)} for i in range(5)]
+ with (
+ mock.patch.object(config, "page_size", 100),
+ mock.patch.object(concord, "_fetch", return_value={"items": rows}),
+ ):
+ tables = list(
+ _iter_page(
+ session=mock.MagicMock(),
+ base_url="https://x",
+ path="/p",
+ headers={},
+ config=config,
+ logger=mock.MagicMock(),
+ batcher=batcher,
+ manager=manager,
+ base_params={},
+ start_page=start_page,
+ start_row_offset=start_row_offset,
+ )
+ )
+ emitted = [r["uuid"] for table in tables for r in table.to_pylist()]
+ return emitted, manager
+
+ def test_mid_page_flush_advances_row_offset_monotonically(self):
+ _emitted, manager = self._iter()
+ # flushes after rows 1 and 3 (0-indexed) → committed counts 2 then 4, never rewinding to 0
+ assert [(s.page, s.row_offset) for s in manager.saved] == [(0, 2), (0, 4)]
+
+ def test_resume_skips_already_emitted_rows(self):
+ emitted, _ = self._iter(start_row_offset=3)
+ # rows 0–2 were committed last run; the resume must not re-emit them
+ assert emitted == ["3", "4"]
+
+
+class TestOffsetPagination:
+ def test_members_use_start_offset_param(self, monkeypatch):
+ monkeypatch.setattr(CONCORD_ENDPOINTS["members"], "page_size", 2)
+ payloads = [
+ {"members": [{"userOrganizationId": 1}, {"userOrganizationId": 2}]},
+ {"members": [{"userOrganizationId": 3}]},
+ ]
+ rows, urls, _ = _run("members", payloads)
+ assert [r["userOrganizationId"] for r in rows] == [1, 2, 3]
+ assert "start=0" in urls[0]
+ assert "start=2" in urls[1]
+
+ def test_clauses_use_offset_param(self, monkeypatch):
+ monkeypatch.setattr(CONCORD_ENDPOINTS["clauses"], "page_size", 2)
+ rows, urls, _ = _run(
+ "clauses",
+ [{"organizationClauses": [{"id": 1}, {"id": 2}]}, {"organizationClauses": [{"id": 3}]}],
+ )
+ assert [r["id"] for r in rows] == [1, 2, 3]
+ assert "offset=0" in urls[0]
+ assert "offset=2" in urls[1]
+
+
+class TestEventsWindowPagination:
+ @freeze_time("2024-01-20")
+ def test_walks_weekly_windows_with_bounded_range(self):
+ last_value = int(datetime(2024, 1, 1, tzinfo=UTC).timestamp() * 1000)
+ _rows, urls, manager = _run(
+ "events",
+ [{"events": [{"id": 1}]}],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=last_value,
+ )
+ # 2024-01-01 .. 2024-01-20 chunked into <= 7-day windows
+ assert "start=2024-01-01" in urls[0]
+ assert "end=2024-01-08" in urls[0]
+ assert len(urls) >= 3
+ # windows advance and checkpoint so a crash resumes at the next window
+ assert manager.saved and manager.saved[-1].window_start_ms is not None
+
+ @freeze_time("2024-01-20")
+ def test_resumes_from_saved_window(self):
+ resume_ms = int(datetime(2024, 1, 15, tzinfo=UTC).timestamp() * 1000)
+ manager = FakeManager(ConcordResumeConfig(window_start_ms=resume_ms))
+ _rows, urls, _ = _run("events", [{"events": []}], manager=manager)
+ assert "start=2024-01-15" in urls[0]
+
+ def _iter_single_window(self, *, start_row_offset=0, manager=None):
+ config = CONCORD_ENDPOINTS["events"]
+ manager = manager or FakeManager()
+ # A single window (start within 7 days of today) so the walk stops after one fetch; chunk_size=2
+ # flushes every two rows so the mid-window checkpoint fires.
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=2)
+ start_ms = int(datetime(2024, 1, 18, tzinfo=UTC).timestamp() * 1000)
+ rows = [{"id": i} for i in range(5)]
+ with mock.patch.object(concord, "_fetch", return_value={"events": rows}):
+ tables = list(
+ _iter_events_windows(
+ session=mock.MagicMock(),
+ base_url="https://x",
+ path="/p",
+ headers={},
+ config=config,
+ logger=mock.MagicMock(),
+ batcher=batcher,
+ manager=manager,
+ start_ms=start_ms,
+ start_row_offset=start_row_offset,
+ )
+ )
+ emitted = [r["id"] for table in tables for r in table.to_pylist()]
+ return emitted, manager
+
+ @freeze_time("2024-01-20")
+ def test_mid_window_flush_advances_row_offset_monotonically(self):
+ _emitted, manager = self._iter_single_window()
+ window_ms = int(datetime(2024, 1, 18, tzinfo=UTC).timestamp() * 1000)
+ # flushes after rows 1 and 3 (0-indexed) → committed counts 2 then 4, never rewinding to 0
+ assert [(s.window_start_ms, s.row_offset) for s in manager.saved] == [(window_ms, 2), (window_ms, 4)]
+
+ @freeze_time("2024-01-20")
+ def test_resume_skips_already_emitted_window_rows(self):
+ emitted, _ = self._iter_single_window(start_row_offset=3)
+ # rows 0–2 were committed last run; the resume must not re-emit them
+ assert emitted == [3, 4]
+
+
+class TestConcordSource:
+ @parameterized.expand(list(CONCORD_ENDPOINTS.keys()))
+ def test_source_response_shape(self, endpoint):
+ response = concord_source(
+ api_key="key",
+ environment="production",
+ organization_id="42",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ manager=FakeManager(),
+ )
+ config = CONCORD_ENDPOINTS[endpoint]
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_keys == [config.partition_key]
+ assert response.partition_mode == "datetime"
+ else:
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord_source.py
new file mode 100644
index 000000000000..f2686b04f661
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord_source.py
@@ -0,0 +1,123 @@
+from typing import cast
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.concord import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.concord.concord import ConcordResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.concord.source import ConcordSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ConcordSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestConcordSourceClass:
+ def setup_method(self):
+ self.source = ConcordSource()
+ self.team_id = 123
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.CONCORD
+
+ def test_source_config_fields(self):
+ fields = {f.name: f for f in self.source.get_source_config.fields}
+ assert set(fields) == {"api_key", "environment", "organization_id"}
+ api_key_field = cast(SourceFieldInputConfig, fields["api_key"])
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+ assert cast(SourceFieldInputConfig, fields["organization_id"]).required is False
+ # environment is a select offering both Concord hosts
+ environment_field = cast(SourceFieldSelectConfig, fields["environment"])
+ assert {o.value for o in environment_field.options} == {"production", "sandbox"}
+
+ def test_lists_tables_without_credentials(self):
+ # get_schemas is a static catalog, so the public docs can render the table list
+ assert self.source.lists_tables_without_credentials is True
+ documented = {t["name"] for t in self.source.get_documented_tables()}
+ assert "agreements" in documented
+
+ @parameterized.expand(["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors_present(self, fragment):
+ keys = " ".join(self.source.get_non_retryable_errors().keys())
+ assert fragment in keys
+
+ def test_get_schemas_lists_all_endpoints(self):
+ names = {s.name for s in self.source.get_schemas(ConcordSourceConfig(api_key="k"), self.team_id)}
+ assert {"organizations", "agreements", "members", "folders", "clauses", "tags", "events"} <= names
+
+ def test_get_schemas_name_filter(self):
+ schemas = self.source.get_schemas(ConcordSourceConfig(api_key="k"), self.team_id, names=["agreements"])
+ assert [s.name for s in schemas] == ["agreements"]
+
+ @parameterized.expand(
+ [
+ ("agreements", True),
+ ("events", True),
+ ("members", False),
+ ("folders", False),
+ ("groups", False),
+ ("tags", False),
+ ]
+ )
+ def test_supports_incremental_only_where_server_filter_exists(self, endpoint, expected):
+ schema = self.source.get_schemas(ConcordSourceConfig(api_key="k"), self.team_id, names=[endpoint])[0]
+ assert schema.supports_incremental is expected
+
+ def test_events_is_off_by_default_and_append(self):
+ schema = self.source.get_schemas(ConcordSourceConfig(api_key="k"), self.team_id, names=["events"])[0]
+ assert schema.should_sync_default is False
+ assert schema.supports_append is True
+
+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])
+ def test_validate_credentials(self, _name, underlying, expected_ok):
+ with mock.patch.object(source_module, "validate_concord_credentials", return_value=underlying):
+ ok, error = self.source.validate_credentials(
+ ConcordSourceConfig(api_key="k", environment="production"), self.team_id
+ )
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert manager._data_class is ConcordResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self):
+ config = ConcordSourceConfig(api_key="secret", environment="sandbox", organization_id="55")
+ inputs = mock.MagicMock()
+ inputs.schema_name = "agreements"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000000
+ inputs.incremental_field = "modifiedAt"
+ manager = mock.MagicMock()
+
+ with mock.patch.object(source_module, "concord_source") as concord_source_mock:
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ _args, kwargs = concord_source_mock.call_args
+ assert kwargs["api_key"] == "secret"
+ assert kwargs["environment"] == "sandbox"
+ assert kwargs["organization_id"] == "55"
+ assert kwargs["endpoint"] == "agreements"
+ assert kwargs["manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == 1700000000000
+
+ def test_source_for_pipeline_drops_incremental_value_when_not_incremental(self):
+ config = ConcordSourceConfig(api_key="secret")
+ inputs = mock.MagicMock()
+ inputs.schema_name = "groups"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000000
+ inputs.incremental_field = None
+
+ with mock.patch.object(source_module, "concord_source") as concord_source_mock:
+ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)
+
+ _args, kwargs = concord_source_mock.call_args
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_key_tables(self):
+ descriptions = self.source.get_canonical_descriptions()
+ assert "agreements" in descriptions
+ assert "columns" in descriptions["agreements"]
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 f904448d7617..80061b8c9a09 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
@@ -791,7 +791,9 @@ class CommercetoolsSourceConfig(config.Config):
@config.config
class ConcordSourceConfig(config.Config):
- pass
+ api_key: str
+ environment: Literal["production", "sandbox"] = config.value(default="production")
+ organization_id: str | None = None
@config.config