API Reference¶
Auto-generated from Google-style docstrings in src/. Any function or class with a docstring is reflected here — no manual updates needed.
Domain Layer¶
The domain layer is pure Python — no infrastructure dependencies. All business rules live here.
Customer Domain¶
src.domain.customer.entities ¶
Customer entity – core of the Customer bounded context.
An Entity has a unique identity (customer_id) and mutable lifecycle state. Business rules about customers live here, not in the API or infrastructure layers.
Classes¶
Customer
dataclass
¶
Represents a B2B SaaS customer account.
The customer entity owns lifecycle state (active vs churned) and exposes domain methods that encapsulate churn-relevant business rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer_id
|
str
|
Unique identifier (UUID string). |
required |
industry
|
Industry
|
Vertical segment, used for cohort analysis. |
required |
plan_tier
|
PlanTier
|
Commercial tier (starter / growth / enterprise). |
required |
signup_date
|
date
|
Date of first contract activation. |
required |
mrr
|
MRR
|
Monthly Recurring Revenue value object. |
required |
churn_date
|
date | None
|
Date of cancellation; None means still active (right-censored). |
None
|
Source code in src/domain/customer/entities.py
Attributes¶
property
¶Days from signup to churn (or today if still active).
Used as the time axis in survival analysis models.
property
¶True if customer is within the critical first-90-day onboarding window.
20–25% of voluntary churn occurs in this window (per Forrester data).
property
¶Human-readable annual revenue that would be lost if this customer churns.
Functions¶
Record the churn event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
churn_date
|
date
|
The date cancellation was confirmed. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If churn_date precedes signup_date or customer already churned. |
Source code in src/domain/customer/entities.py
src.domain.customer.value_objects ¶
Value objects for the Customer domain.
Value objects are immutable and compared by value, not identity. They encapsulate business rules about what constitutes a valid value.
Classes¶
PlanTier ¶
Bases: StrEnum
The commercial tier a customer is on.
Tier correlates with feature access, support SLA, and churn risk profile. Enterprise customers have dedicated CSMs and lower base churn rates. CUSTOM represents bespoke enterprise contracts — the ceiling of the tier ladder. FREE represents the freemium tier (zero MRR); the highest-leverage conversion event in SaaS is free → paid when a customer hits a feature data-sharing limit.
Source code in src/domain/customer/value_objects.py
Industry ¶
Bases: StrEnum
Vertical industry segment.
Used for cohort segmentation and industry-specific churn benchmarking.
Source code in src/domain/customer/value_objects.py
MRR
dataclass
¶
Monthly Recurring Revenue in USD.
Enforces non-negative constraint. Used for business impact calculations (e.g. revenue at risk = MRR × churn_probability).
Source code in src/domain/customer/value_objects.py
src.domain.customer.repository ¶
CustomerRepository – abstract port (interface) for the Customer domain.
Infrastructure implementations live in src/infrastructure/repositories/. The domain layer depends only on this interface, never on DuckDB directly.
Classes¶
CustomerRepository ¶
Bases: ABC
Port (interface) for persisting and retrieving Customer entities.
Source code in src/domain/customer/repository.py
Functions¶
abstractmethod
¶Retrieve a customer by their unique ID.
Returns:
| Type | Description |
|---|---|
Customer | None
|
Customer entity, or None if not found. |
abstractmethod
¶Return all customers who have not yet churned.
Used for batch churn scoring runs.
abstractmethod
¶Return a random sample of n customers (any churn status).
Business Context
Used by the demo list endpoint to seed load-test tooling and the UI customer picker. Deterministic seed (REPEATABLE 42) ensures the same customers are returned across requests for reproducibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of customers to sample (caller must clamp to safe max). |
required |
Source code in src/domain/customer/repository.py
Usage Domain¶
src.domain.usage.entities ¶
UsageEvent entity – core of the Usage bounded context.
Classes¶
UsageEvent
dataclass
¶
A single product interaction by a customer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_id
|
str
|
UUID primary key. |
required |
customer_id
|
str
|
FK to Customer entity. |
required |
timestamp
|
datetime
|
UTC datetime of the event. |
required |
event_type
|
EventType
|
The type of product action taken. |
required |
feature_adoption_score
|
FeatureAdoptionScore
|
Adoption score snapshot at the time of the event. |
required |
Source code in src/domain/usage/entities.py
src.domain.usage.value_objects ¶
Value objects for the Usage domain.
Classes¶
EventType ¶
Bases: StrEnum
Product event types tracked in usage_events.
integration_connect events are strong retention signals.
Absence of monitoring_run events is an early churn indicator.
Source code in src/domain/usage/value_objects.py
FeatureAdoptionScore
dataclass
¶
Composite 0–1 score reflecting breadth and depth of feature usage.
Scores below 0.2 combined with declining event frequency are the strongest leading indicators of churn in the first 90 days.
Source code in src/domain/usage/value_objects.py
src.domain.usage.repository ¶
UsageRepository – abstract port for the Usage domain.
Classes¶
UsageRepository ¶
Bases: ABC
Port for retrieving usage events.
Source code in src/domain/usage/repository.py
Functions¶
abstractmethod
¶Retrieve all usage events for a customer, optionally filtered by date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer_id
|
str
|
The customer whose events to fetch. |
required |
since
|
datetime | None
|
If provided, return only events after this UTC datetime. |
None
|
Source code in src/domain/usage/repository.py
abstractmethod
¶Count events in the last N days.
Used as a feature for churn model: event decay is a leading indicator.
Prediction Domain¶
src.domain.prediction.entities ¶
PredictionResult entity – output of the Prediction domain services.
Classes¶
ShapFeature
dataclass
¶
A single SHAP feature contribution to a prediction.
Provides model explainability for CS teams to understand why a customer was flagged, enabling targeted interventions.
Source code in src/domain/prediction/entities.py
PredictionResult
dataclass
¶
The complete output of a churn + risk prediction for one customer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer_id
|
str
|
The customer this prediction belongs to. |
required |
churn_probability
|
ChurnProbability
|
Calibrated P(churn in 90 days). |
required |
risk_score
|
RiskScore
|
Composite compliance/usage risk score. |
required |
top_shap_features
|
list[ShapFeature]
|
Top-N SHAP drivers (sorted by |shap_impact|). |
list()
|
model_version
|
str
|
Semantic version of the model artifact used. |
'0.0.0'
|
predicted_at
|
datetime
|
UTC timestamp of when the prediction was generated. |
(lambda: now(UTC))()
|
Source code in src/domain/prediction/entities.py
src.domain.prediction.value_objects ¶
Value objects for the Prediction domain.
Classes¶
ChurnProbability
dataclass
¶
P(churn in next 90 days) output from the churn model.
Calibrated probability in [0, 1]. The 0.5 threshold is the default operating point; business impact analysis should inform the actual threshold used for CS outreach triggers.
Source code in src/domain/prediction/value_objects.py
RiskScore
dataclass
¶
Composite compliance + usage risk score in [0, 1].
Combines compliance_gap_score, vendor_risk_flags, and usage_decay_score. Distinct from churn probability — a customer can have high risk score but low churn probability if they are contractually locked in.
Source code in src/domain/prediction/value_objects.py
src.domain.prediction.churn_model_service ¶
ChurnModelService – domain service for churn probability prediction.
Domain services encapsulate operations that don't naturally belong to a single entity. The model artifact is injected as a dependency (no direct file I/O here).
Classes¶
ChurnFeatureVector ¶
Bases: Protocol
Protocol for feature extraction – implemented in infrastructure layer.
Phase 4 update: the extractor queries the dbt mart directly (single DuckDB read), so events no longer need to be passed from the use case layer. This keeps the protocol minimal and moves feature logic into dbt.
Source code in src/domain/prediction/churn_model_service.py
Functions¶
Extract the model's feature vector for a customer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer
|
Customer
|
Active Customer entity (used to look up mart row by ID). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float | str]
|
Flat dict of feature_name → value (numerics as float, categoricals |
dict[str, float | str]
|
as lowercase string for sklearn OrdinalEncoder compatibility). |
dict[str, float | str]
|
All feature engineering lives in mart_customer_churn_features. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the customer is not found in the mart (e.g. churned customers are excluded from the mart). |
Source code in src/domain/prediction/churn_model_service.py
ChurnModelPort ¶
Bases: ABC
Abstract port for the underlying ML model.
Concrete implementations in src/infrastructure/ml/ load the trained XGBoost/survival model artifact.
Source code in src/domain/prediction/churn_model_service.py
ChurnModelService ¶
Orchestrates feature extraction → model inference → result construction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ChurnModelPort
|
Concrete ML model (injected from infrastructure layer). |
required |
feature_extractor
|
ChurnFeatureVector
|
Queries the dbt mart for the customer's feature vector. |
required |
Source code in src/domain/prediction/churn_model_service.py
Functions¶
Generate a full PredictionResult for a customer.
Business Context: Feature extraction, model inference, and SHAP computation are all delegated to injected dependencies. This service only owns the assembly logic, keeping it testable in isolation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
customer
|
Customer
|
Active Customer entity. |
required |
risk_score
|
RiskScore
|
Pre-computed composite risk score (from RiskModelService). |
required |
Returns:
| Type | Description |
|---|---|
PredictionResult
|
PredictionResult with calibrated churn probability, SHAP explanations, |
PredictionResult
|
and a deterministic recommended CS action. |
Source code in src/domain/prediction/churn_model_service.py
src.domain.prediction.risk_model_service ¶
RiskModelService – domain service for compliance + usage risk scoring.
Classes¶
RiskSignals
dataclass
¶
Raw risk inputs from the risk_signals table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compliance_gap_score
|
float
|
0–1 score of open compliance gaps. |
required |
vendor_risk_flags
|
int
|
Count of third-party vendor risk alerts. |
required |
usage_decay_score
|
float
|
0–1 score of recent usage decline (computed from events). |
required |
Source code in src/domain/prediction/risk_model_service.py
RiskModelService ¶
Computes a composite risk score from compliance and usage signals.
Weights are calibrated to business impact: - Usage decay is the strongest leading indicator of near-term churn - Compliance gaps drive risk but not always churn (contractual stickiness) - Vendor risk flags have lower weight but non-zero contribution
These weights should be revisited quarterly using SHAP analysis on the full churn model to ensure they remain calibrated to observed outcomes.
Source code in src/domain/prediction/risk_model_service.py
Functions¶
Compute a composite RiskScore from raw signals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signals
|
RiskSignals
|
The three risk signal components. |
required |
Returns:
| Type | Description |
|---|---|
RiskScore
|
RiskScore value object in [0, 1]. |
Source code in src/domain/prediction/risk_model_service.py
GTM Domain¶
src.domain.gtm.entities ¶
Opportunity entity for the GTM bounded context.
Classes¶
Opportunity
dataclass
¶
A sales or expansion opportunity linked to a customer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
opp_id
|
str
|
UUID primary key. |
required |
customer_id
|
str
|
FK to Customer entity. |
required |
stage
|
SalesStage
|
Current CRM pipeline stage. |
required |
close_date
|
date
|
Actual or expected close date. |
required |
amount
|
Decimal
|
USD opportunity value. |
required |
sales_owner
|
str
|
Anonymised sales rep identifier. |
required |
Source code in src/domain/gtm/entities.py
src.domain.gtm.value_objects ¶
Value objects for the GTM domain.
Classes¶
SalesStage ¶
Bases: StrEnum
CRM pipeline stage for an opportunity.