Credit Scoring and Pipeline Domain Runtime Scoring Endpoints and Underwriting Decision Contract

Overview

This feature turns housing application data into underwriting outputs that the platform can use consistently across backend APIs and UI summaries. The runtime path in backend/src/usecase/credit_score_runtime.py builds features from an application, scores them through Vertex AI, validates the returned contract strictly, calibrates the probability of default by corridor and product type, applies coverage-honesty adjustments, and emits a CreditScoreEstimate with score, banding, confidence, coverage, reason codes, and risk flags.

The HTTP layer exposes that runtime through application-specific score endpoints and score-conversion endpoints in backend/src/interface/http_endpoints.py, while frontend/lib/credit-risk.ts provides the browser-side blending logic used to present score and risk summaries in the UI. The contract is deliberately fail-closed: invalid model payloads, missing predictions, or unsupported reason codes are rejected instead of being coerced into a best-effort score.

Architecture Overview

flowchart LR
    subgraph FrontendProxy[Frontend score access]
        AppCreditRoute[applications id credit score route]
        AppCreditRouteV1[v1 applications id credit score route]
        CreditRiskLib[credit-risk ts]
    end

    subgraph BackendAPI[Backend interface]
        CreditScoreEndpoint[get_application_credit_score]
        GlobalScoreEndpoint[get_application_global_score]
        ScoreConvertEndpoint[score_convert_endpoint]
        LitaScoreEndpoint[score endpoint]
    end

    subgraph Runtime[Runtime scoring usecases]
        ScoreHousingApplication[score_housing_application]
        ValidateContract[_validate_risk_engine_contract]
        CalibratePd[_calibrate_pd]
        DeriveFlags[_derive_risk_flags]
        StoreArtifact[_store_score_artifact]
    end

    VertexAI[Vertex AI endpoint]
    ArtifactSink[JSONL artifact file]
    UI[Applicant score summary]

    AppCreditRoute --> CreditScoreEndpoint
    AppCreditRouteV1 --> CreditScoreEndpoint
    CreditScoreEndpoint --> ScoreHousingApplication
    GlobalScoreEndpoint --> ScoreHousingApplication
    ScoreHousingApplication --> VertexAI
    ScoreHousingApplication --> ValidateContract
    ScoreHousingApplication --> CalibratePd
    ScoreHousingApplication --> DeriveFlags
    ScoreHousingApplication --> StoreArtifact
    StoreArtifact --> ArtifactSink
    ScoreConvertEndpoint --> UI
    LitaScoreEndpoint --> UI
    CreditRiskLib --> UI

Component Structure

1. Frontend Score Summary Utilities

frontend/lib/credit-risk.ts

This module prepares score summaries for the UI from either legacy budget-and-savings inputs or richer application state. It blends account metrics, income signals, and repayment history into a single score in the 300–850 range, and it can also fall back to a legacy bucket-based score when that is the only usable signal.

Public APIs

Method Description
computeCreditScore Computes a credit score from either a legacy pair of inputs or a structured CreditScoreInput.

Key constants and parsing behavior

  • BASE_CREDIT_SCORE is 300.
  • MAX_CREDIT_SCORE is 850.
  • CREDIT_SCORE_COMPONENT_WEIGHTS blends six components:
    • loanBalanceToIncome: 0.27
    • incomeStrength: 0.19
    • paymentHistory: 0.22
    • paymentPeriod: 0.12
    • delinquency: 0.11
    • consumerFinanceUsage: 0.09
  • The module recognizes many alternate score keys when parsing risk summaries, including risk_score, credit_risk_score, credit_score, fico_score, ai_score, model_score, score_value, and score.

Interfaces

Interface Property Type Description
CreditScoreInput budgetRange `string \ null \ undefined` Legacy budget bucket input.
CreditScoreInput savings `string \ null \ undefined` Legacy savings bucket input.
CreditScoreInput income `string \ number \ null \ undefined` Declared annual income or numeric equivalent.
CreditScoreInput incomeCurrency `string \ null \ undefined` Currency for income interpretation.
CreditScoreInput connectedAccounts `CreditScoreConnectedAccountSource \ undefined` Connected account source used to compute account metrics.
CreditScoreInput loanAnalysis `Partial \ null \ undefined` Loan repayment activity used for repayment and delinquency signals.
CreditScoreInput paymentTransactions `ReadonlyArray \ undefined` Transaction summaries used to estimate income from payments.
CreditRiskAttributes classification `string \ undefined` Human-readable classification label.
CreditRiskAttributes rating `string \ undefined` Human-readable rating label.
CreditRiskAttributes score `number \ undefined` Numeric score carried into the UI summary.
ResolveCreditRiskLevelInput score `number \ null \ undefined` Numeric score for risk level resolution.
ResolveCreditRiskLevelInput classification `string \ null \ undefined` Classification label used for risk level resolution.
ResolveCreditRiskLevelInput rating `string \ null \ undefined` Rating label used for risk level resolution.
CreditScoreComponents loanBalanceToIncome `number \ null` Component score for debt versus income.
CreditScoreComponents incomeStrength `number \ null` Component score for income strength.
CreditScoreComponents paymentHistory `number \ null` Component score for repayment history.
CreditScoreComponents paymentPeriod `number \ null` Component score for repayment duration.
CreditScoreComponents delinquency `number \ null` Component score for delinquency signal.
CreditScoreComponents consumerFinanceUsage `number \ null` Component score for revolving or consumer-finance usage.

Internal scoring helpers

Method Description
computeCreditScoreFromInput Orchestrates the local blended score path from structured input.
computeLegacyCreditScore Builds a legacy score from budget and savings buckets.
computeBucketScore Converts a bucketed range into a score segment.
computeAccountMetrics Aggregates connected-account balances, debt balance, liquidity, and revolving utilization.
computeWeightedCreditScore Computes the weighted score from populated CreditScoreComponents.
computePaymentHistoryScore Scores repayment history from repayment period and late payments.
computePaymentPeriodScore Scores repayment period depth.
computeDelinquencyScore Scores delinquency intensity.
computeConsumerFinanceScore Scores revolving or consumer finance usage.

UI score blending behavior

  • computeCreditScore accepts either:
    • a legacy pair of budgetRange and savings, or
    • a full CreditScoreInput.
  • If the structured path has no usable weighted score, the function returns the legacy score or undefined.
  • When both legacy and weighted scores exist, the function blends them by a reliability score derived from:
    • account metrics presence,
    • income metrics presence,
    • repayment analysis presence.
  • The final result is always clamped to the 300–850 range.

2. Backend Runtime Scoring Engine

backend/src/usecase/credit_score_runtime.py

This module is the main runtime underwriting engine. It collects applicant features, calls Vertex AI, validates the returned risk payload, calibrates the probability of default against corridor data, converts that calibrated PD into legacy and global scores, and stores a score artifact for later analysis.

Public methods

Method Description
score_housing_application Builds features from a HousingApplication, scores them, and returns a CreditScoreEstimate.
_score_with_vertex Sends the flattened feature payload to Vertex AI and validates the returned risk output.
_validate_risk_engine_contract Enforces the runtime contract for the model payload.
_store_score_artifact Persists a JSONL score artifact for observability and later inspection.
_build_features Derives the model feature vector from the housing application and connected accounts.
_canonicalize_banking Normalizes connected-account payloads into canonical accounts and institutions.
_apply_coverage_adjustments Applies coverage-based penalties and product caps to score and PD.
_derive_risk_flags Produces displayable risk flags from features and reason codes.
_confidence Computes the final confidence value from coverage and risk uncertainty.
_calibrate_pd Applies corridor-specific PD calibration knots.
_score_band Maps a legacy score into band A through E.
_global_band Maps a global score into band A through E.
_target_score_from_global Produces a target-scale score estimate from the global score.
_resolve_endpoint_name Resolves the Vertex endpoint resource name from environment variables.
_require_project_id Resolves the GCP project identifier used for Vertex initialization.
_load_fx_rates Loads USD FX overrides from LITA_FX_RATES_JSON.
_to_usd Converts an amount into USD for comparison features.
_to_iso_date Normalizes date inputs into timezone-aware datetime values.
_employment_status_code Encodes employment status into a numeric feature.

Dataclasses

Dataclass Property Type Description
_RiskEngineOutput pd_p50_12m float Median 12-month probability of default returned by the model.
_RiskEngineOutput pd_p90_12m float Upper-tail 12-month probability of default returned by the model.
_RiskEngineOutput reason_codes list[str] Validated reason codes returned by the model.
_RiskEngineOutput breakdown Dict[str, float] Score breakdown by the required runtime keys.
_RiskEngineOutput model_version str Model version string from the Vertex response metadata.
CreditScoreEstimate score int Final legacy-style score.
CreditScoreEstimate score_band str Legacy score band.
CreditScoreEstimate provider str Score provider identifier.
CreditScoreEstimate model_version str Risk model version.
CreditScoreEstimate featureset_version str Feature set version.
CreditScoreEstimate calibration_version str Calibration version string.
CreditScoreEstimate confidence float Final runtime confidence.
CreditScoreEstimate data_coverage Dict[str, Any] Coverage summary emitted with the score.
CreditScoreEstimate reason_codes list[str] Validated reason codes used downstream.
CreditScoreEstimate breakdown Dict[str, float] Model breakdown values.
CreditScoreEstimate lita_global_score int Global score on the platform scale.
CreditScoreEstimate global_band str Global score band.
CreditScoreEstimate risk_flags list[dict[str, str]] Structured risk flags for the UI and downstream systems.
CreditScoreEstimate target_scale `str \ None` Optional target scale label.
CreditScoreEstimate target_score `int \ None` Optional target score in the requested scale.
CreditScoreEstimate target_confidence `float \ None` Optional confidence in the requested target scale.

Runtime contract

  • _validate_risk_engine_contract requires the Vertex prediction to be a JSON object.
  • pd_p50_12m must be numeric and within [0, 1].
  • pd_p90_12m must be numeric, at least pd_p50_12m, and at most 1.
  • reason_codes must be a list of strings, contain at most 6 values, and every value must be in the allowlist.
  • breakdown must contain exactly these keys:
    • affordability
    • stability
    • bureau_strength
    • liquidity
    • risk_signals
  • meta.model_version is required.
  • meta.corridor_cluster is allowed only when it is a string.

Allowed reason codes

INSUFFICIENT_LIABILITY_VISIBILITY, LOW_LIQUIDITY_BUFFER, INSUFFICIENT_DATA_COVERAGE, HIGH_SPEND_TO_INCOME, INCOME_INSTABILITY, RECENT_DELINQUENCY, HIGH_BUREAU_UTILIZATION, MULTIPLE_RECENT_INQUIRIES, RECENT_NEW_CREDIT, NEGATIVE_BALANCE_PATTERN, OVERDRAFT_ACTIVITY, RETURNED_PAYMENTS, UNVERIFIED_INCOME, POSSIBLE_UNLINKED_ACCOUNTS, LIMITED_CREDIT_HISTORY, HIGH_RISK_TX_PATTERN

Feature construction and coverage outputs

[!IMPORTANT] The runtime path is fail-closed. _score_with_vertex raises if Vertex returns no predictions, and _validate_risk_engine_contract raises if the payload is malformed or contains unsupported reason codes. The system does not synthesize a fallback prediction when the contract is violated.

The runtime feature vector includes banking, bureau, and context features such as:

  • income, savings, budget, and employment encoding,
  • institutions and accounts linked,
  • days covered and transaction activity,
  • salary detection and salary regularity,
  • debt payments, rent detection, liquidity, and overdraft indicators,
  • bureau score, bureau utilization, delinquencies, and recency,
  • host-country macro context and consent-derived KYC signal.

score_housing_application emits a data_coverage object with these fields:

Field Type Description
institutions_linked int Number of institutions present in the canonicalized banking payload.
accounts_linked int Number of canonical accounts.
days_covered int Number of days with transaction coverage.
salary_detected bool Whether salary-like income was identified.
coverage_score float Coverage quality score from the feature builder.
coverage_flags list[str] Coverage-related flags such as POSSIBLE_UNLINKED_ACCOUNTS and SHORT_HISTORY.

Confidence and scoring behavior

  • confidence is computed from:
    • coverage_score,
    • bureau_parse_confidence,
    • pd_p50_12m,
    • pd_p90_12m.
  • score_housing_application converts calibrated PD into:
    • a legacy score via pd_to_legacy_score,
    • a global score via pd_to_global_score.
  • score_housing_application also derives a target-scale score using target_mapping.
  • target_confidence is capped by the runtime confidence when it exists.

Coverage-honesty and product caps

  • _apply_coverage_adjustments increases PD and lowers score when coverage is weak, history is short, income is unverified, or external transfer outflow is high.
  • It also applies product caps:
    • loan caps at 720
    • high_ticket_loan caps at 680 when bureau evidence is unavailable
    • rental caps at 760
  • When SCORE_CAP_UNLINKED_ACCOUNTS is present in the applied policy set, lita_global_score is capped at 680, and POSSIBLE_UNLINKED_ACCOUNTS is added to the reason code list if it is not already present.

Risk flags

_derive_risk_flags emits structured flags with code, severity, and display_text. The codes include:

NO_BANK_DATA, INSUFFICIENT_HISTORY, OVERDRAFT_STRESS, HIGH_EXTERNAL_TRANSFERS, HIGH_DEBT_PAYMENT_LOAD, RECENT_DELINQUENCY, MISSING_KEY_VARIABLES

Artifact storage

_store_score_artifact writes a JSONL record to LITA_SCORE_ARTIFACT_PATH and includes:

  • application_id
  • feature_hash
  • model_version
  • calibration_version
  • pd_p50_12m
  • pd_p90_12m
  • final_score
  • score_band
  • coverage_summary
  • confidence
  • reason_codes
  • adjustments_applied
  • latency_ms
  • request_id
  • status
  • timestamp

3. Backend Heuristic Credit Estimate

backend/src/usecase/credit_scoring.py

This module provides the simpler score estimate shape used by the non-runtime scoring path. The visible contract is a compact CreditScoreEstimate record carrying the final score, the model version, and a breakdown map.

Public APIs

Method Description
CreditScoreEstimate Compact estimate object used by the heuristic scoring path.

Dataclass

Property Type Description
score int Final score.
model_version str Scoring model identifier.
breakdown Dict[str, float] Named contribution map.

The visible return path in this module clamps scores to the 300–850 range and emits breakdown categories such as income_strength, savings_buffer, connected_accounts_bonus, employment_stability, and affordability_penalty in the heuristic scoring flow.

4. Backend HTTP Endpoints

backend/src/interface/http_endpoints.py

This module exposes the application-specific score endpoints and the score-conversion endpoint. The application score handlers fetch the housing application, call the runtime scorer, and serialize the runtime estimate into response models that preserve score, global score, confidence, coverage, reason codes, and risk flags.

Public APIs

Method Description
get_application_credit_score Returns the runtime score estimate for a housing application.
get_application_global_score Returns the runtime global score estimate for a housing application.
score_convert_endpoint Converts a source score and bureau primitives into the platform global score contract.

Get Application Credit Score

{
    "title": "Get Application Credit Score",
    "description": "Returns the runtime credit score estimate for a housing application after loading the application and evaluating the Vertex-backed scoring contract",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/v1/applications/{application_id}/credit-score",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "application_id",
            "type": "int",
            "required": true,
            "description": "Housing application identifier"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"application_id\": 123,\n    \"score\": 732,\n    \"score_band\": \"B\",\n    \"provider\": \"lita\",\n    \"model_version\": \"lita-risk-v1.0.0\",\n    \"featureset_version\": \"ApplicantFeatureSetV3\",\n    \"calibration_version\": \"calib-v2:loan:US-CA\",\n    \"confidence\": 0.86,\n    \"data_coverage\": {\n        \"institutions_linked\": 2,\n        \"accounts_linked\": 4,\n        \"days_covered\": 83,\n        \"salary_detected\": true,\n        \"coverage_score\": 0.74,\n        \"coverage_flags\": [\n            \"SHORT_HISTORY\"\n        ]\n    },\n    \"reason_codes\": [\n        \"LOW_LIQUIDITY_BUFFER\"\n    ],\n    \"breakdown\": {\n        \"affordability\": 0.44,\n        \"stability\": 0.51,\n        \"bureau_strength\": 0.49,\n        \"liquidity\": 0.3,\n        \"risk_signals\": 0.67\n    },\n    \"lita_global_score\": 718,\n    \"global_band\": \"B\",\n    \"risk_flags\": [\n        {\n            \"code\": \"INSUFFICIENT_HISTORY\",\n            \"severity\": \"high\",\n            \"display_text\": \"Insufficient banking history coverage.\"\n        }\n    ],\n    \"target_scale\": \"US-FICO\",\n    \"target_score\": 718,\n    \"target_confidence\": 0.82\n}"
        }
    }
}

get_application_credit_score tracing details:

  • application_id is validated by Path(..., ge=1).
  • db is injected with Depends(get_db).
  • current_user is required through Depends(_APPLICATION_DETAIL_USER_DEPENDENCY).
  • The handler loads the application through SQLAlchemyHousingApplicationRepository.
  • ValueError becomes 400 Bad Request.
  • A missing application becomes 404 Not Found.
  • The runtime scorer is then called with score_housing_application.

Get Application Global Score

{
    "title": "Get Application Global Score",
    "description": "Returns the global underwriting score contract for a housing application",
    "method": "GET",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/v1/applications/{application_id}/global-score",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "application_id",
            "type": "int",
            "required": true,
            "description": "Housing application identifier"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"application_id\": 123,\n    \"lita_global_score\": 718,\n    \"global_band\": \"B\",\n    \"confidence\": 0.86,\n    \"data_coverage\": {\n        \"institutions_linked\": 2,\n        \"accounts_linked\": 4,\n        \"days_covered\": 83,\n        \"salary_detected\": true,\n        \"coverage_score\": 0.74,\n        \"coverage_flags\": [\n            \"SHORT_HISTORY\"\n        ]\n    },\n    \"reason_codes\": [\n        \"LOW_LIQUIDITY_BUFFER\"\n    ],\n    \"breakdown\": {\n        \"affordability\": 0.44,\n        \"stability\": 0.51,\n        \"bureau_strength\": 0.49,\n        \"liquidity\": 0.3,\n        \"risk_signals\": 0.67\n    },\n    \"provider\": \"lita\",\n    \"model_version\": \"lita-risk-v1.0.0\",\n    \"featureset_version\": \"ApplicantFeatureSetV3\",\n    \"calibration_version\": \"calib-v2:loan:US-CA\",\n    \"risk_flags\": [\n        {\n            \"code\": \"INSUFFICIENT_HISTORY\",\n            \"severity\": \"high\",\n            \"display_text\": \"Insufficient banking history coverage.\"\n        }\n    ]\n}"
        }
    }
}

Score Convert

{
    "title": "Score Convert",
    "description": "Converts a source score and bureau primitives into the global underwriting score contract and target-scale output",
    "method": "POST",
    "baseUrl": "<BackendApiBaseUrl>",
    "endpoint": "/v1/score-convert",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"source_score\": 710,\n    \"source_scale_min\": 300,\n    \"source_scale_max\": 850,\n    \"bureau_primitives\": {\n        \"score_value\": 720,\n        \"score_scale_min\": 300,\n        \"score_scale_max\": 850,\n        \"parse_confidence\": 0.91\n    },\n    \"banking_summary_features\": {\n        \"coverage_score\": 0.74,\n        \"salary_detected\": true,\n        \"days_covered\": 83\n    },\n    \"target_scale\": \"US-FICO\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"lita_global_score\": 728,\n    \"global_band\": \"B\",\n    \"confidence\": 0.87,\n    \"target_scale\": \"US-FICO\",\n    \"target_score\": 728,\n    \"target_confidence\": 0.84\n}"
        }
    }
}

score_convert_endpoint behavior:

  • Converts source_score to the global scale using _convert_source_score_to_global.
  • If bureau_primitives.score_value is present and the bureau scale is valid, the endpoint blends the source and bureau-derived global score.
  • coverage_score starts at 0.35, then increases when bureau score exists and when banking_summary_features is present.
  • confidence is computed from coverage_score, bureau parse confidence, and an uncertainty width derived from whether banking summary features are present.
  • target_confidence is capped by the final confidence when it exists.

backend/src/interface/lita_endpoints.py

This module exposes the simpler score endpoint that computes a score from a compact feature map and returns the approved limit together with reason codes.

Public APIs

Method Description
_compute_score Computes the compact score and approval limit from underwriting feature values.

Score

{
    "title": "Score",
    "description": "Computes a compact underwriting score from core credit attributes and returns the approved limit and reason codes",
    "method": "POST",
    "baseUrl": "<LitaApiBaseUrl>",
    "endpoint": "/score",
    "headers": [
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"credit_utilization\": 0.42,\n    \"debt_to_income_ratio\": 0.33,\n    \"credit_history_months\": 18,\n    \"delinquencies_last_24m\": 1,\n    \"monthly_income\": 6200\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Success",
            "body": "{\n    \"score\": 630,\n    \"reasons\": [\n        \"RECENT_DELINQUENCY\"\n    ],\n    \"approved_limit\": 1860\n}"
        }
    }
}

_compute_score behavior:

  • Starts from a base score of 700.
  • Applies downward adjustments for:
    • high utilization,
    • high debt-to-income ratio,
    • short credit history,
    • recent delinquencies.
  • Returns an approved_limit computed from monthly income, with a minimum of 1000.

5. Next.js Browser Proxy Routes

frontend/app/api/applications/[id]/credit-score/route.ts

This route sits in the browser-facing frontend API layer and proxies the application credit-score request for UI consumption. It belongs to the same contract family as the backend credit-score endpoint and is used by the frontend to retrieve the score summary without calling the backend directly from the browser.

frontend/app/api/v1/applications/[id]/credit-score/route.ts

This route provides the versioned browser-facing proxy for the same credit-score contract. The frontend consumes this path when it needs the /api/v1 form of the score response.

6. Runtime Validation and Contract Enforcement

Reason code validation

The runtime contract enforces an explicit reason-code allowlist and rejects anything outside it. This is important because downstream UI and underwriting consumers can safely interpret the returned codes without handling arbitrary model text.

Coverage outputs

The runtime outputs both a score and a coverage summary. That split lets the UI show whether the result is strong because of data richness or merely because of the score itself, which is important in this product because consented financial-data access is a central underwriting input.

Fail-closed execution

The runtime never silently substitutes an invalid model response. When the model payload does not match the contract, the request fails before a CreditScoreEstimate is returned.

7. Integration Points

  • backend/src/usecase/credit_score_runtime.py consumes src.domain.housing_application.HousingApplication.
  • backend/src/usecase/credit_score_runtime.py uses src.ml.lita_global_score_converter helpers:
    • apply_coverage_honesty_policy
    • calibrate_pd
    • confidence_score
    • pd_to_global_score
    • pd_to_legacy_score
    • target_mapping
  • backend/src/usecase/credit_score_runtime.py uses google.cloud.aiplatform.Endpoint.predict for runtime inference.
  • backend/src/usecase/credit_score_runtime.py uses src.usecase.credit_scoring._normalise_amount to normalize financial fields.
  • frontend/lib/credit-risk.ts consumes application, account, and repayment inputs to create a UI-facing score summary.
  • frontend/app/api/applications/[id]/credit-score/route.ts and frontend/app/api/v1/applications/[id]/credit-score/route.ts provide the browser-side score fetch path.

8. Logging and Artifact Observability

logging service usage in backend/src/usecase/credit_score_runtime.py

The runtime module creates a module-scoped logger and uses it for contract and calibration diagnostics.

Injected by Use
backend/src/usecase/credit_score_runtime.py Emits warnings when FX overrides are malformed and debug messages when corridor calibration falls back to default knots.

Observed log events

  • LITA_FX_RATES_JSON is malformed; using built-in rates
  • Calibration registry miss for key=...; using default knots

Artifact sink

Injected by Use
backend/src/usecase/credit_score_runtime.py Appends JSONL score artifacts to LITA_SCORE_ARTIFACT_PATH.

Artifact flow

  1. Build features.
  2. Compute feature_hash.
  3. Collect runtime outputs and adjustments.
  4. Append a single JSON line to the artifact file.

9. Feature Flow

sequenceDiagram
    participant U as User
    participant F as Frontend score summary
    participant R as credit-risk ts
    participant E as Backend credit score endpoint
    participant S as score_housing_application
    participant V as Vertex AI endpoint
    participant A as Artifact file

    U->>F: Open housing application summary
    F->>R: computeCreditScore input
    R-->>F: blended local score or undefined
    F-->>U: Render score summary

    U->>E: Request application credit score
    E->>S: Load application and score it
    S->>V: Predict with flattened features
    V-->>S: Risk engine payload
    S->>A: Append score artifact
    S-->>E: CreditScoreEstimate
    E-->>U: Score response JSON

10. Backend Underwriting Flow

sequenceDiagram
    participant Client as API client
    participant API as get_application_credit_score
    participant Repo as SQLAlchemyHousingApplicationRepository
    participant Runtime as score_housing_application
    participant Vertex as Vertex AI endpoint

    Client->>API: GET application credit score
    API->>Repo: get_by_id
    Repo-->>API: HousingApplication
    API->>Runtime: score_housing_application
    Runtime->>Vertex: endpoint.predict
    Vertex-->>Runtime: predictions
    Runtime-->>API: CreditScoreEstimate
    API-->>Client: CreditScoreResponse

11. Score Conversion Flow

sequenceDiagram
    participant Client as API client
    participant API as score_convert_endpoint
    participant Conv as score converter helpers

    Client->>API: POST source score and bureau primitives
    API->>Conv: _convert_source_score_to_global
    API->>Conv: target_mapping
    API->>Conv: confidence_score
    API-->>Client: ScoreConvertResponse

Error Handling

The runtime and endpoint layers use explicit failure paths instead of silent normalization.

  • get_application_credit_score
    • 400 Bad Request when get_housing_application raises ValueError
    • 404 Not Found when the application does not exist
  • get_application_global_score
    • 404 Not Found when the application is missing
  • _score_with_vertex
    • raises ValueError when Vertex returns no predictions
  • _validate_risk_engine_contract
    • raises ValueError for malformed types, unsupported reason codes, invalid breakdown, or missing model metadata
  • _load_fx_rates
    • falls back to built-in FX rates if LITA_FX_RATES_JSON is malformed and logs a warning

Dependencies

  • google.cloud.aiplatform
  • fastapi dependency injection and HTTP exception handling
  • src.domain.housing_application.HousingApplication
  • src.domain.housing_application.HousingApplicationRepository
  • src.ml.lita_global_score_converter
  • src.usecase.credit_scoring._normalise_amount
  • logging, json, hashlib, math, os, datetime, timezone
  • Frontend UI consumers in frontend/lib/credit-risk.ts
  • Browser-facing Next.js routes in frontend/app/api/applications/[id]/credit-score/route.ts and frontend/app/api/v1/applications/[id]/credit-score/route.ts

Testing Considerations

The visible tests in the repository cover the critical contract points for this feature:

  • Vertex provider returns a valid CreditScoreEstimate
  • invalid Vertex contract payloads fail closed
  • heuristic scoring clamps to the 300–850 range
  • heuristic scoring emits a meaningful breakdown
  • student applications are routed to the student-specific scoring model path

Key Classes Reference

Class Responsibility
credit_score_runtime.py Runtime scoring orchestration, Vertex validation, calibration, confidence, and artifact storage.
credit_scoring.py Compact heuristic score estimate contract used by the non-runtime scoring path.
http_endpoints.py Application score and score-conversion HTTP handlers.
lita_endpoints.py Compact underwriting score endpoint and approval-limit calculation.
credit-risk.ts Frontend score blending and risk-summary utilities.