jieheng

    Exact usage pricing with verified catalog migration audits, multi-customer mixed-bill replay and per-customer release policies.

    pricing
    graduated
    billing
    decimal
    Download zip
    Author
    Version
    0.8.0
    License
    Apache-2.0
    Last updated
    5 days ago
    Downloads
    20

    #阶衡 · Jieheng

    精确的阶梯用量计价库。给定一个版本化价目表和已经汇总的用量,按渐进分档或整量选档规则生成明细、精确小计,以及按明确规则舍入一次的结算金额。适合 API、消息、存储等产品的报价、账单解释和价格变更复算。

    独立价值集中在“聚合用量合同计价 → 可信凭证核验 → 完整目录与客户账单调价检查”。与现有金额、token 成本、物流和会计项目的实际交集、公开 API 对照、固定提交来源及检索局限见 生态边界审查。

    #当前能力

    • 任意 1–1024 档渐进式计价(graduated):每档只对落入该档的用量收费,支持免费档;最终档必须无上限。
    • 整量选档计价(volume):按总用量选中一个档位,再将该档单价应用于全部用量;零用量不收费,不包含档位固定费。
    • 标准库 BigInt 精确运算,价格最多 30 位整数和 18 位小数,用量最多 30 位非负整数;不经过浮点数。
    • 分档明细与合计;显式选择 0–18 位结算精度,支持 HalfEven、HalfUp、Down、Up,保留舍入差额。
    • 严格版本化 JSON 价目表与用量交换,拒绝未知字段和重复键;文件计价工具与公开 Stripe/AWS 价格示例。
    • 可归档的计算凭证;独立检查分档守恒、小计、合计和结算规则,提供凭证核验命令。
    • 同一用量下比较两个价格方案,保留双方凭证,分别输出精确差额和结算差额,并可核验归档比较报告。
    • 批量调价影响汇总:逐客户周期结算、拒绝重复快照、保留每项比较和可核验总计。
    • 显式最低消费:保留原始用量,单列补差,明确零用量政策,在补差后结算一次。
    • 多指标用量账单:同客户周期逐项补差、结算后汇总;拒绝重复指标和混币种,保留完整核验依据。
    • 价格生效时间表:明确日期选择版本,拒绝重叠和无覆盖日期,支持历史凭证核验。
    • 整包容量计价:用量向上取整到完整包,保留未使用容量,独立核验最小包数与结算。
    • 预算内最大用量:支持渐进与非单调整量价,显式限制搜索范围,提供独立最大性核验。
    • 阶梯与整包组合账单:保留两类完整凭证,跨模型拒绝重复指标,逐项结算后汇总。
    • 全范围调价审查:按完整整数域分析金额差异,保留整量价跳变,验证所有分段和极值。
    • 安全预算配额:保证零到配额的每个整数用量都可负担,保留第一个超预算数量的凭证。
    • 版本化多指标目录:按日期选择阶梯、最低消费与整包规则,要求完整用量覆盖后生成账单。
    • 整单合同比较:按指标对齐相同用量,分列价格、补差和结算差异,允许计价模型迁移。
    • 整单预算配额:保留固定用量项,为一个含最低消费或整包规则的可变指标求安全配额。
    • 目录覆盖审查:发布前列出每个必需指标在日期窗口内的全部计价空窗,可作为失败退出的上线检查。
    • 账单解释报告:核验后导出 Markdown,解释分档、最低消费、整包和舍入,并保留完整合同与凭证附录。
    • 目录迁移审查:覆盖整个日期窗口,区分指标/单位/币种/空窗阻断和价格/模型/最低消费等复核项,提供可核验报告与发布门禁。
    • 完整账单批量回放:按客户周期回放多指标目录变更,核验涨降分布和最大涨额,并用金额/百分比上限阻止异常调价发布。
    • Wasm、Wasm-GC、JavaScript、Native 使用同一个纯计算库,仅依赖标准库;文件工具使用 moonbitlang/async,支持 Wasm 和 Native。

    #使用

    模块名为 cosettese/jieheng。目前从源码使用;尚未发布到 Mooncakes。先阅读可执行快速上手和 API 兼容政策。独立消费模块 展示源码工作区接入;发行包验证 另行检查打包后的真实消费流程。开发仓库的 moon.work 同时测试主库和消费模块,发布包不携带此工作区。

    moon update moon test --target all --deny-warn moon run cmd/demo --target wasm

    示例重现公开的分档定价案例:前 5 单位每单位 7,接下来的 5 单位每单位 6.5,之后每单位 6。6 单位为 USD 41.50,20 单位为 USD 127.50,25 单位为 USD 157.50。输入来自公开教学规则,不是实际客户账单。

    let plan = @jieheng.compile_plan(
    id="api", version="2026-09", metric="requests",
    unit="request", currency="USD",
    tiers=[
    { up_to: Some("1000"), unit_price: "0" },
    { up_to: None, unit_price: "0.001" },
    ],
    )
    let calculation = @jieheng.rate(plan, {
    customer: "acme", metric: "requests", period: "2026-09", quantity: "1501",
    })
    let settlement = @jieheng.settle(calculation, scale=2, rounding=HalfEven)
    // calculation.total == "0.501"; settlement.amount == "0.50"
    // settlement.delta == "-0.001"

    公开接口见 pkg.generated.mbti。调用方需传播或处理 PricingError;诊断提供 code、path、message。Plan 是已校验且脱离输入数组的快照。Calculation 是可检查的公开记录;settle 只校验金额和精度。接受外部明细时,使用 verify_evidence 对可信计划、用量和结算规则进行独立核验。

    #精确定义与边界

    渐进分档将数量 q 分配到各档 (previous, up_to];整量选档根据 q 所处区间选中一档,对全部 q 收费。两种模式的零用量均得到空明细和零金额,不包含固定费。明细完全精确,合计后才结算舍入。整量选档跨越降价档位时,总价可能下降。

    compile_plan 的可选参数 mode=Volume 启用整量选档,默认 Graduated 保持旧行为;JSON 中用 "mode":"volume" 或 "graduated"。现有渐进价目表与凭证的规范输出不变。完整规则与示例见 docs/volume.md。

    数字使用 ASCII 十进制字符串;拒绝负数、指数、前导零、空白、空小数部分、超出精度或资源上限的输入。货币是三个 ASCII 大写字母的标签,不自动验证 ISO 币种或选择小数位。客户、周期、指标、计划版本都是调用方提供的标签;周期不参与时间计算。usage.metric 必须与计划一致。

    不支持原始事件计量/去重、分数用量、阶梯固定费、税费、折扣、预付额度/结转套餐、汇率、按时间比例分摊、收款、完整云厂商账单。存储的 GB-month 等时间汇总必须由调用方先完成并约定整数计量单位。

    #三个实际工作流

    1. SaaS 月结:上游按客户和月份汇总请求次数;本库应用免费档和收费档,客服可以逐档解释账单。
    2. 容量报价:调用方先把存储使用汇总为约定的整数单位;按公开价格快照计算分档估价,不把估价当作供应商的完整发票。
    3. 调价回归:保留相同用量快照,分别应用旧版本和新版本计划,检查边界客户和结算差额。

    #后续路线

    已形成“目录全窗口迁移审查 → 完整客户账单回放 → 涨额门禁”的工作流,并完成发行包与独立消费验证。可运行固定种子生成式验证检查组合边界、保存失败上下文并跨后端重放,以及九项性能基线记录运行耗时、输入规模和可采集的平台内存。后续重点是实际接入反馈与相同环境下的性能跟踪;注册表发布暂缓。回放、生成测试和性能基线均只覆盖提供或生成的样本。

    #开发与验证

    验收索引与统一入口:运行 moon run scripts/acceptance.mbtx portable HEAD,在同一提交的隔离快照中依次完成全部技术验证;all HEAD 增加 Native 实际运行。索引将已实现能力对应到 API、测试和可运行示例,并单列尚未完成的提交条件。

    可复现交付验证 提供统一入口:moon run scripts/verify.mbtx portable HEAD 在只含 Git 已提交文件的新目录中运行格式、接口、严格检查、三个后端及端到端验证;all HEAD 增加 Native 实际运行,CI 在三个系统执行完整模式。

    使用 moon.mod / moon.pkg。当前验证工具链:稳定版 MoonBit v0.10.16+b1a0e846e,moon 0.1.20261020。CI 在 Linux、Windows、macOS 执行四种后端测试和示例。CI 配置代表预期覆盖,具体运行结果以 Actions 为准。

    moon update moon fmt moon info moon check --target all --deny-warn moon test --target all --deny-warn

    测试包含边界前后值、零用量、免费档、分配守恒、逐单位独立参考计算、18 位小数、超大整数、四种舍入规则、畸形输入、失败后恢复、输入数组隔离和确定性。生成式验证另覆盖世纪闰年与跨年窗口、目录迁移完整分段、多客户完整账单回放及涨幅阈值;两个生成域均支持固定种子与单例重放。

    Apache-2.0;依赖和示例来源见 SOURCES.md。

    完整文件工作流、JSON 格式与预期输出见 docs/formats.md。真实 S3 价格快照的区域、SKU、发布时间、单位和估价限制见 examples/s3/README.md。运行 moon run scripts/e2e.mbtx wasm 可核对公开案例、错误退出和失败后恢复。

    计算凭证的生成、核验、篡改示例与独立核验算法见 docs/verification.md。凭证没有密码学签名,核验方必须保留可信的计划、用量和结算规则。

    新旧方案或两种计价模式的比较、差额定义及归档核验见 docs/comparison.md。比较不进行币种或计量单位转换。

    PricingError

    pub(all) suberror PricingError {
    Invalid(code~ : String, path~ : String, message~ : String)
    } derive(Eq,
    Debug
    )

    Diagnostics contain a stable code, an input path, and an actionable message.

    PricingError::equal

    PricingError::not_equal

    fn PricingError::not_equal(x : PricingError, y : PricingError) -> Bool

    Bill

    pub(all) struct Bill {
    customer : String
    period : String
    currency : String
    items : Array[BillEvidence]
    totals : BillTotals
    } derive(Eq,
    Debug
    )

    Bill::equal

    fn Bill::equal(Bill, Bill) -> Bool

    Bill::not_equal

    fn Bill::not_equal(x : Bill, y : Bill) -> Bool

    Bill::to_repr

    BillChange

    pub(all) struct BillChange {
    metric : String
    unit : String
    baseline_index : Int
    candidate_index : Int
    usage_delta : String
    top_up_delta : String
    exact_delta : String
    settled_delta : String
    } derive(Eq,
    Debug
    )

    Candidate minus baseline for one identical metric snapshot. Indices preserve both original bill orders; the change list follows the baseline order.

    BillChange::equal

    fn BillChange::equal(BillChange, BillChange) -> Bool

    BillChange::not_equal

    fn BillChange::not_equal(x : BillChange, y : BillChange) -> Bool

    BillComparison

    pub(all) struct BillComparison {
    baseline : Bill
    candidate : Bill
    changes : Array[BillChange]
    exact_delta : String
    settled_delta : String
    } derive(Eq,
    Debug
    )

    BillComparison::equal

    BillComparison::not_equal

    fn BillComparison::not_equal(x : BillComparison, y : BillComparison) -> Bool

    BillEvidence

    pub(all) enum BillEvidence {
    MeteredCharge(Charge)
    PackageCharge(PackageEvidence)
    } derive(Eq,
    Debug
    )

    BillEvidence::equal

    BillEvidence::not_equal

    fn BillEvidence::not_equal(x : BillEvidence, y : BillEvidence) -> Bool

    BillItem

    pub(all) enum BillItem {
    Metered(ChargeInput)
    Packaged(PackagePlan, Usage)
    }

    Explicitly tagged inputs preserve each pricing model's complete contract.

    BillQuota

    pub(all) struct BillQuota {
    request : BudgetRequest
    variable_metric : String
    bill : Bill
    first_unaffordable : Bill?
    } derive(Eq,
    Debug
    )

    BillQuota::equal

    fn BillQuota::equal(BillQuota, BillQuota) -> Bool

    BillQuota::not_equal

    fn BillQuota::not_equal(x : BillQuota, y : BillQuota) -> Bool

    BillQuotaInput

    pub(all) struct BillQuotaInput {
    fixed : Array[BillItem]
    variable : Tariff
    request : BudgetRequest
    }

    Fixed snapshots retain every quantity. The variable rule has no quantity; its customer/period/limit come explicitly from request.

    BillTotals

    pub(all) struct BillTotals {
    usage_total : String
    top_up : String
    total : String
    scale : Int
    rounding : Rounding
    minor_units : String
    amount : String
    delta : String
    } derive(Eq,
    Debug
    )

    Item settlements are summed without a second rounding operation.

    BillTotals::equal

    fn BillTotals::equal(BillTotals, BillTotals) -> Bool

    BillTotals::not_equal

    fn BillTotals::not_equal(x : BillTotals, y : BillTotals) -> Bool

    BudgetQuote

    pub(all) struct BudgetQuote {
    request : BudgetRequest
    evidence : Evidence
    } derive(Eq,
    Debug
    )

    Maximum affordable quantity within the explicit limit, with complete evidence. For Volume, smaller quantities need not all be affordable.

    BudgetQuote::equal

    fn BudgetQuote::equal(BudgetQuote, BudgetQuote) -> Bool

    BudgetQuote::not_equal

    fn BudgetQuote::not_equal(x : BudgetQuote, y : BudgetQuote) -> Bool

    BudgetRequest

    pub(all) struct BudgetRequest {
    customer : String
    period : String
    budget : String
    limit : String
    } derive(Eq,
    Debug
    )

    A finite procurement request, without an ignored or guessed usage quantity.

    BudgetRequest::equal

    BudgetRequest::not_equal

    fn BudgetRequest::not_equal(x : BudgetRequest, y : BudgetRequest) -> Bool

    Calculation

    pub(all) struct Calculation {
    plan_id : String
    plan_version : String
    currency : String
    unit : String
    usage : Usage
    lines : Array[Line]
    total : String
    } derive(Eq,
    Debug
    )

    Exact, unsettled calculation. Public records may be inspected and serialized.

    Calculation::equal

    fn Calculation::equal(Calculation, Calculation) -> Bool

    Calculation::not_equal

    fn Calculation::not_equal(x : Calculation, y : Calculation) -> Bool

    Catalog

    pub struct Catalog {
    // private fields
    }

    Detached timelines for all required metrics of one product, in one currency.

    CatalogBill

    pub(all) struct CatalogBill {
    on : String
    bill : Bill
    } derive(Eq,
    Debug
    )

    CatalogBill::equal

    fn CatalogBill::equal(CatalogBill, CatalogBill) -> Bool

    CatalogBill::not_equal

    fn CatalogBill::not_equal(x : CatalogBill, y : CatalogBill) -> Bool

    CatalogChange

    pub(all) enum CatalogChange {
    MetricAdded
    MetricRemoved
    BaselineGap
    CandidateGap
    CurrencyChanged
    UnitChanged
    IdentityChanged
    VersionChanged
    ModelChanged
    PricingChanged
    MinimumChanged
    ZeroPolicyChanged
    } derive(Eq,
    Debug
    )

    CatalogChange::equal

    CatalogChange::is_blocking

    fn CatalogChange::is_blocking(self : CatalogChange) -> Bool

    Identical usage cannot be bound without an explicit mapping. Nonblocking changes still require business review; structural compatibility is not approval.

    CatalogChange::not_equal

    fn CatalogChange::not_equal(x : CatalogChange, y : CatalogChange) -> Bool

    CatalogEntry

    pub(all) struct CatalogEntry {
    starts_on : String
    ends_before : String?
    tariff : Tariff
    }

    CatalogGap

    pub(all) struct CatalogGap {
    metric : String
    starts_on : String
    ends_before : String
    } derive(Eq,
    Debug
    )

    A maximal uncovered half-open interval for one required catalog metric.

    CatalogGap::equal

    fn CatalogGap::equal(CatalogGap, CatalogGap) -> Bool

    CatalogGap::not_equal

    fn CatalogGap::not_equal(x : CatalogGap, y : CatalogGap) -> Bool

    CatalogMigration

    pub(all) struct CatalogMigration {
    starts_on : String
    ends_before : String
    spans : Array[MigrationSpan]
    } derive(Eq,
    Debug
    )

    Unchanged spans are retained to prove full metric and window coverage.

    CatalogMigration::equal

    CatalogMigration::not_equal

    fn CatalogMigration::not_equal(x : CatalogMigration, y : CatalogMigration) -> Bool

    CatalogReplay

    pub(all) struct CatalogReplay {
    currency : String
    rows : Array[CatalogReplayRow]
    baseline_exact : String
    candidate_exact : String
    baseline_settled : String
    candidate_settled : String
    exact_delta : String
    settled_delta : String
    increased : Int
    decreased : Int
    unchanged : Int
    max_increase : String
    max_increase_index : Int?
    } derive(Eq,
    Debug
    )

    Counts describe customer-period snapshots; exact totals are never rounded across customers. The maximum is the greatest positive settled increase, with the first input index winning ties; no increase gives zero and None.

    CatalogReplay::equal

    CatalogReplay::not_equal

    fn CatalogReplay::not_equal(x : CatalogReplay, y : CatalogReplay) -> Bool

    CatalogReplayCase

    pub(all) struct CatalogReplayCase {
    on : String
    usages : Array[Usage]
    } derive(Eq,
    Debug
    )

    CatalogReplayCase::equal

    CatalogReplayCase::not_equal

    fn CatalogReplayCase::not_equal(x : CatalogReplayCase, y : CatalogReplayCase) -> Bool

    CatalogReplayRow

    pub(all) struct CatalogReplayRow {
    on : String
    comparison : BillComparison
    } derive(Eq,
    Debug
    )

    CatalogReplayRow::equal

    CatalogReplayRow::not_equal

    fn CatalogReplayRow::not_equal(x : CatalogReplayRow, y : CatalogReplayRow) -> Bool

    Charge

    pub(all) struct Charge {
    calculation : Calculation
    minimum : String
    zero_usage : ZeroUsageMinimum
    top_up : String
    total : String
    settlement : Settlement
    } derive(Eq,
    Debug
    )

    Usage-only calculation remains untouched. total = calculation.total + top_up. Only total is settled; no intermediate rounded amount is fed into the floor.

    Charge::equal

    fn Charge::equal(Charge, Charge) -> Bool

    Charge::not_equal

    fn Charge::not_equal(x : Charge, y : Charge) -> Bool

    Charge::to_repr

    ChargeInput

    pub(all) struct ChargeInput {
    plan : Plan
    usage : Usage
    minimum : String
    zero_usage : ZeroUsageMinimum
    }

    Trusted charge input: one already aggregated metric, one plan and one floor. Plans are validated snapshots; arrays are consumed without being retained.

    CohortComparison

    pub(all) struct CohortComparison {
    rows : Array[Comparison]
    baseline_exact : String
    candidate_exact : String
    baseline_settled : String
    candidate_settled : String
    exact_delta : String
    settled_delta : String
    } derive(Eq,
    Debug
    )

    One comparison per trusted usage, in input order. Totals sum separately settled customer-period amounts: never round a cohort-wide exact total.

    CohortComparison::equal

    CohortComparison::not_equal

    fn CohortComparison::not_equal(x : CohortComparison, y : CohortComparison) -> Bool

    Comparison

    pub(all) struct Comparison {
    baseline : Evidence
    candidate : Evidence
    exact_delta : String
    settled_delta : String
    } derive(Eq,
    Debug
    )

    Candidate minus baseline, for one identical aggregated usage snapshot. Deltas are signed exact decimal strings. Both sides retain complete evidence.

    Comparison::equal

    fn Comparison::equal(Comparison, Comparison) -> Bool

    Comparison::not_equal

    fn Comparison::not_equal(x : Comparison, y : Comparison) -> Bool

    EffectivePlan

    pub(all) struct EffectivePlan {
    starts_on : String
    ends_before : String?
    plan : Plan
    }

    Gregorian dates: inclusive start, exclusive optional end.

    Evidence

    pub(all) struct Evidence {
    calculation : Calculation
    settlement : Settlement
    } derive(Eq,
    Debug
    )

    A transport record, not a signature or an authenticated invoice.

    Evidence::equal

    fn Evidence::equal(Evidence, Evidence) -> Bool

    Evidence::not_equal

    fn Evidence::not_equal(x : Evidence, y : Evidence) -> Bool

    Evidence::to_repr

    Invoice

    pub(all) struct Invoice {
    customer : String
    period : String
    currency : String
    charges : Array[Charge]
    usage_total : String
    top_up : String
    total : String
    scale : Int
    rounding : Rounding
    minor_units : String
    amount : String
    delta : String
    } derive(Eq,
    Debug
    )

    Pricing statement, not a legal invoice or payment instruction. Each charge is settled separately; amount sums those settlements exactly. delta = amount - total can exceed one minor unit over multiple charges.

    Invoice::equal

    fn Invoice::equal(Invoice, Invoice) -> Bool

    Invoice::not_equal

    fn Invoice::not_equal(x : Invoice, y : Invoice) -> Bool

    Invoice::to_repr

    Line

    pub(all) struct Line {
    tier : Int
    from_exclusive : String
    to_inclusive : String
    quantity : String
    unit_price : String
    subtotal : String
    } derive(Eq,
    Debug
    )

    Exact allocation for one occupied tier. No line-level monetary rounding.

    Line::equal

    fn Line::equal(Line, Line) -> Bool

    Line::not_equal

    fn Line::not_equal(x : Line, y : Line) -> Bool

    Line::to_repr

    MigrationSpan

    pub(all) struct MigrationSpan {
    metric : String
    starts_on : String
    ends_before : String
    baseline_entry : Int?
    candidate_entry : Int?
    changes : Array[CatalogChange]
    } derive(Eq,
    Debug
    )

    Half-open interval, referencing entries in the two trusted catalog snapshots.

    MigrationSpan::equal

    MigrationSpan::not_equal

    fn MigrationSpan::not_equal(x : MigrationSpan, y : MigrationSpan) -> Bool

    PackageEvidence

    pub(all) struct PackageEvidence {
    plan_id : String
    plan_version : String
    currency : String
    unit : String
    usage : Usage
    package_size : String
    package_price : String
    packages : String
    unused_units : String
    total : String
    settlement : Settlement
    } derive(Eq,
    Debug
    )

    PackageEvidence::equal

    PackageEvidence::not_equal

    fn PackageEvidence::not_equal(x : PackageEvidence, y : PackageEvidence) -> Bool

    PackagePlan

    pub struct PackagePlan {
    // private fields
    }

    A fixed nonzero package capacity and exact price per package.

    Plan

    pub struct Plan {
    // private fields
    }

    Validated, detached snapshot of a price plan.

    Plan::mode

    fn Plan::mode(self : Plan) -> PricingMode

    Return the plan's explicit pricing semantics.

    PlanRef

    pub(all) struct PlanRef {
    id : String
    version : String
    } derive(Eq,
    Debug
    )

    PlanRef::equal

    fn PlanRef::equal(PlanRef, PlanRef) -> Bool

    PlanRef::not_equal

    fn PlanRef::not_equal(x : PlanRef, y : PlanRef) -> Bool

    PlanRef::to_repr

    PriceAnalysis

    pub(all) struct PriceAnalysis {
    baseline : PlanRef
    candidate : PlanRef
    currency : String
    metric : String
    unit : String
    limit : String
    spans : Array[PriceSpan]
    minimum_delta : String
    minimum_at : String
    maximum_delta : String
    maximum_at : String
    } derive(Eq,
    Debug
    )

    Candidate minus baseline over every integer quantity from zero to limit. Extreme ties select the smallest quantity. This is exact, unsettled pricing.

    PriceAnalysis::equal

    PriceAnalysis::not_equal

    fn PriceAnalysis::not_equal(x : PriceAnalysis, y : PriceAnalysis) -> Bool

    PriceSpan

    pub(all) struct PriceSpan {
    from_quantity : String
    to_quantity : String
    baseline_total : String
    candidate_total : String
    baseline_step : String
    candidate_step : String
    } derive(Eq,
    Debug
    )

    Inclusive integer interval. For q in [from_quantity,to_quantity], each exact total equals its value at from_quantity plus step * (q-from_quantity).

    PriceSpan::equal

    fn PriceSpan::equal(PriceSpan, PriceSpan) -> Bool

    PriceSpan::not_equal

    fn PriceSpan::not_equal(x : PriceSpan, y : PriceSpan) -> Bool

    PricingMode

    pub(all) enum PricingMode {
    Graduated
    Volume
    } derive(Eq,
    Debug
    )

    Pricing semantics chosen explicitly in a plan.

    PricingMode::equal

    fn PricingMode::equal(PricingMode, PricingMode) -> Bool

    PricingMode::not_equal

    fn PricingMode::not_equal(x : PricingMode, y : PricingMode) -> Bool

    QuotaQuote

    pub(all) struct QuotaQuote {
    request : BudgetRequest
    evidence : Evidence
    first_unaffordable : Evidence?
    } derive(Eq,
    Debug
    )

    Every integer usage from zero through evidence.quantity is affordable. Unless limited by request.limit, the next quantity has a verified over-budget witness. This differs from maximum feasible quantity under Volume pricing.

    QuotaQuote::equal

    fn QuotaQuote::equal(QuotaQuote, QuotaQuote) -> Bool

    QuotaQuote::not_equal

    fn QuotaQuote::not_equal(x : QuotaQuote, y : QuotaQuote) -> Bool

    ReplayPolicy

    pub(all) struct ReplayPolicy {
    currency : String
    max_increase : String
    max_increase_percent : String?
    } derive(Eq,
    Debug
    )

    Per-snapshot settled-price limits. A percentage limit rejects any positive change from a zero baseline, since no finite relative increase exists.

    ReplayPolicy::equal

    ReplayPolicy::not_equal

    fn ReplayPolicy::not_equal(x : ReplayPolicy, y : ReplayPolicy) -> Bool

    Rounding

    pub(all) enum Rounding {
    HalfEven
    HalfUp
    Down
    Up
    } derive(Eq,
    Debug
    )

    All amounts are nonnegative; Down/Up mean toward/away from zero.

    Rounding::equal

    fn Rounding::equal(Rounding, Rounding) -> Bool

    Rounding::not_equal

    fn Rounding::not_equal(x : Rounding, y : Rounding) -> Bool

    Rounding::to_repr

    Schedule

    pub struct Schedule {
    // private fields
    }

    Validated, detached timeline for one plan identity, metric, unit and currency.

    ScheduledEvidence

    pub(all) struct ScheduledEvidence {
    on : String
    evidence : Evidence
    } derive(Eq,
    Debug
    )

    ScheduledEvidence::equal

    ScheduledEvidence::not_equal

    fn ScheduledEvidence::not_equal(x : ScheduledEvidence, y : ScheduledEvidence) -> Bool

    Settlement

    pub(all) struct Settlement {
    currency : String
    scale : Int
    rounding : Rounding
    minor_units : String
    amount : String
    delta : String
    } derive(Eq,
    Debug
    )

    Exactly one rounding operation on the complete total. delta = amount - exact total, and can be negative.

    Settlement::equal

    fn Settlement::equal(Settlement, Settlement) -> Bool

    Settlement::not_equal

    fn Settlement::not_equal(x : Settlement, y : Settlement) -> Bool

    Tariff

    pub(all) enum Tariff {
    MeteredTariff(Plan, String, ZeroUsageMinimum)
    PackageTariff(PackagePlan)
    }

    A complete pricing rule without any ignored usage quantity.

    Tier

    pub(all) struct Tier {
    up_to : String?
    unit_price : String
    } derive(Eq,
    Debug
    )

    A cumulative inclusive upper bound, or None for the final unbounded tier. Decimal prices are in currency units per one integer usage unit.

    Tier::equal

    fn Tier::equal(Tier, Tier) -> Bool

    Tier::not_equal

    fn Tier::not_equal(x : Tier, y : Tier) -> Bool

    Tier::to_repr

    Usage

    pub(all) struct Usage {
    customer : String
    metric : String
    period : String
    quantity : String
    } derive(Eq,
    Debug
    )

    Already aggregated usage for one customer, metric, and opaque period label.

    Usage::equal

    fn Usage::equal(Usage, Usage) -> Bool

    Usage::not_equal

    fn Usage::not_equal(x : Usage, y : Usage) -> Bool

    Usage::to_repr

    ZeroUsageMinimum

    pub(all) enum ZeroUsageMinimum {
    Charge
    Waive
    } derive(Eq,
    Debug
    )

    Whether a contractual minimum applies when the trusted quantity is zero.

    ZeroUsageMinimum::equal

    ZeroUsageMinimum::not_equal

    fn ZeroUsageMinimum::not_equal(x : ZeroUsageMinimum, y : ZeroUsageMinimum) -> Bool

    analyze_prices

    fn analyze_prices(baseline : Plan, candidate : Plan, limit : String) -> PriceAnalysis raise PricingError

    Partition the entire bounded integer domain at both plans' tier transitions. Affine extrema occur at endpoints; volume cliffs remain separate spans.

    test {
    let a = @jieheng.compile_plan(
    id="api",
    version="v1",
    metric="calls",
    unit="call",
    currency="USD",
    tiers=[{ up_to: None, unit_price: "1", }],
    )
    let r = @jieheng.analyze_prices(a, a, "999999999999999999999999999999")
    inspect(r.spans.length(), content="1")
    inspect(r.maximum_delta, content="0")
    }

    audit_catalog_migration

    fn audit_catalog_migration(before : Catalog, after : Catalog, starts_on : String, ends_before : String) -> CatalogMigration raise PricingError

    Audit every metric throughout the civil-date window. No usage is synthesized and no monetary impact is inferred.

    test {
    let p = @jieheng.compile_package(
    id="sms",
    version="v1",
    metric="messages",
    unit="message",
    currency="USD",
    package_size="1000",
    package_price="0.85",
    )
    let c = @jieheng.compile_catalog([
    { starts_on: "2026-10-01", ends_before: None, tariff: PackageTariff(p), },
    ])
    let r = @jieheng.audit_catalog_migration(c, c, "2026-10-01", "2026-11-01")
    inspect(r.spans[0].changes.length(), content="0")
    }

    catalog_gaps

    fn catalog_gaps(catalog : Catalog, starts_on : String, ends_before : String) -> Array[CatalogGap] raise PricingError

    Inspect every required metric over [starts_on, ends_before), without usage samples or day-by-day expansion. Results follow catalog metric order, then chronological order. Empty results mean complete date coverage only.

    check_replay_policy

    fn check_replay_policy(before : Catalog, after : Catalog, cases : ArrayView[CatalogReplayCase], report : CatalogReplay, policy : ReplayPolicy, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Verify first, then apply both optional relative and mandatory absolute limits per complete customer-period bill. Uses integer cross-products, not division.

    compare_bills

    fn compare_bills(before : ArrayView[BillItem], after : ArrayView[BillItem], scale~ : Int, rounding~ : Rounding) -> BillComparison raise PricingError

    Compare identical metric usages across full mixed contracts, aligning by metric rather than position. Pricing models and minimum policies may change.

    test {
    let p = @jieheng.compile_package(
    id="sms",
    version="v1",
    metric="messages",
    unit="message",
    currency="USD",
    package_size="1000",
    package_price="0.85",
    )
    let items : Array[@jieheng.BillItem] = [
    Packaged(p, {
    customer: "acme",
    metric: "messages",
    period: "October",
    quantity: "2501",
    }),
    ]
    let c = @jieheng.compare_bills(items[:], items[:], scale=2, rounding=HalfEven)
    inspect(c.exact_delta, content="0")
    }

    compare_cohort

    fn compare_cohort(baseline : Plan, candidate : Plan, usages : ArrayView[Usage], scale~ : Int, rounding~ : Rounding) -> CohortComparison raise PricingError

    Compare a cohort under one compatible pair of plans and settlement policy. All-or-nothing: malformed or duplicate snapshots reject the whole request.

    test {
    let plan = @jieheng.compile_plan(
    id="api",
    version="v1",
    metric="calls",
    unit="call",
    currency="USD",
    tiers=[{ up_to: None, unit_price: "0.004", }],
    )
    let report = @jieheng.compare_cohort(
    plan,
    plan,
    [{ customer: "acme", metric: "calls", period: "2026-10", quantity: "1", }],
    scale=2,
    rounding=HalfEven,
    )
    inspect(report.baseline_exact, content="0.004")
    inspect(report.baseline_settled, content="0")
    }

    compare_plans

    fn compare_plans(baseline : Plan, candidate : Plan, usage : Usage, scale~ : Int, rounding~ : Rounding) -> Comparison raise PricingError

    Compare compatible plans at the same usage and settlement policy. Settled delta is the difference of two settled amounts, not a rounded delta.

    test {
    let before = @jieheng.compile_plan(
    id="api",
    version="v1",
    metric="calls",
    unit="call",
    currency="USD",
    tiers=[{ up_to: None, unit_price: "0.004", }],
    )
    let after = @jieheng.compile_plan(
    id="api",
    version="v2",
    metric="calls",
    unit="call",
    currency="USD",
    tiers=[{ up_to: None, unit_price: "0.006", }],
    )
    let report = @jieheng.compare_plans(
    before,
    after,
    { customer: "acme", metric: "calls", period: "2026-10", quantity: "1", },
    scale=2,
    rounding=HalfEven,
    )
    inspect(report.exact_delta, content="0.002")
    inspect(report.settled_delta, content="0.01")
    }

    compile_catalog

    fn compile_catalog(entries : ArrayView[CatalogEntry]) -> Catalog raise PricingError

    compile_package

    fn compile_package(id~ : String, version~ : String, metric~ : String, unit~ : String, currency~ : String, package_size~ : String, package_price~ : String) -> PackagePlan raise PricingError

    compile_plan

    fn compile_plan(id~ : String, version~ : String, metric~ : String, unit~ : String, currency~ : String, tiers~ : ArrayView[Tier], mode? : PricingMode) -> Plan raise PricingError

    Compile tiers and detach them from caller-owned arrays. The default mode preserves graduated pricing for existing callers. Bounds must increase strictly, and only the last bound must be None.

    compile_schedule

    fn compile_schedule(entries : ArrayView[EffectivePlan]) -> Schedule raise PricingError

    Require ordered nonoverlapping intervals and unique versions. Gaps are allowed but selecting a date inside a gap fails rather than choosing a fallback.

    decode_analysis

    fn decode_analysis(text : String) -> PriceAnalysis raise PricingError

    Structural decode only; verify_analysis proves semantic coverage and values.

    decode_bill

    fn decode_bill(text : String) -> Bill raise PricingError

    Strict structural decode; verify_bill requires the complete trusted manifest.

    decode_bill_comparison

    fn decode_bill_comparison(text : String) -> BillComparison raise PricingError

    Strict structural decode; verify_bill_comparison requires both trusted manifests.

    decode_bill_input

    fn decode_bill_input(text : String) -> Array[BillItem] raise PricingError

    decode_bill_quota

    fn decode_bill_quota(text : String) -> BillQuota raise PricingError

    Structural decode only; accept after verify_bill_quota with complete trusted input.

    decode_bill_quota_input

    fn decode_bill_quota_input(text : String) -> BillQuotaInput raise PricingError

    decode_budget

    fn decode_budget(text : String) -> BudgetQuote raise PricingError

    Structural decode only; use verify_budget with a trusted plan and request.

    decode_budget_request

    fn decode_budget_request(text : String) -> BudgetRequest raise PricingError

    decode_catalog

    fn decode_catalog(text : String) -> Catalog raise PricingError

    decode_catalog_bill

    fn decode_catalog_bill(text : String) -> CatalogBill raise PricingError

    decode_catalog_migration

    fn decode_catalog_migration(text : String) -> CatalogMigration raise PricingError

    Structural decoding only; trusted catalogs are required for verification.

    decode_catalog_replay

    fn decode_catalog_replay(text : String) -> CatalogReplay raise PricingError

    Strict structural decoding; verify_catalog_replay still needs both catalogs, complete dated cases and the settlement policy from a trusted source.

    decode_charge

    fn decode_charge(text : String) -> Charge raise PricingError

    decode_cohort

    fn decode_cohort(text : String) -> CohortComparison raise PricingError

    decode_cohort_usage

    fn decode_cohort_usage(text : String) -> Array[Usage] raise PricingError

    decode_comparison

    fn decode_comparison(text : String) -> Comparison raise PricingError

    Strict structural decoder; semantic acceptance requires verify_comparison.

    decode_evidence

    fn decode_evidence(text : String) -> Evidence raise PricingError

    Strict structural decoder; semantic acceptance requires verify_evidence.

    decode_invoice

    fn decode_invoice(text : String) -> Invoice raise PricingError

    decode_invoice_input

    fn decode_invoice_input(text : String) -> Array[ChargeInput] raise PricingError

    decode_package_plan

    fn decode_package_plan(text : String) -> PackagePlan raise PricingError

    decode_packages

    fn decode_packages(text : String) -> PackageEvidence raise PricingError

    Strict structural decoder; accept only after verify_packages with trusted inputs.

    decode_plan

    fn decode_plan(text : String) -> Plan raise PricingError

    Strict versioned JSON plan decoder. Unknown fields and duplicate keys fail.

    decode_quota

    fn decode_quota(text : String) -> QuotaQuote raise PricingError

    Structural decode; verify_quota requires a trusted plan, request and policy.

    decode_replay_cases

    fn decode_replay_cases(text : String) -> Array[CatalogReplayCase] raise PricingError

    decode_replay_policy

    fn decode_replay_policy(text : String) -> ReplayPolicy raise PricingError

    decode_schedule

    fn decode_schedule(text : String) -> Schedule raise PricingError

    decode_scheduled

    fn decode_scheduled(text : String) -> ScheduledEvidence raise PricingError

    Strict structural decode; use verify_scheduled with trusted date and schedule.

    decode_usage

    fn decode_usage(text : String) -> Usage raise PricingError

    Decode one already aggregated usage snapshot, without implicit coercions.

    decode_usage_bundle

    fn decode_usage_bundle(text : String) -> Array[Usage] raise PricingError

    encode_analysis

    fn encode_analysis(report : PriceAnalysis) -> String raise PricingError

    encode_bill

    fn encode_bill(bill : Bill) -> String raise PricingError

    encode_bill_comparison

    fn encode_bill_comparison(report : BillComparison) -> String raise PricingError

    encode_bill_input

    fn encode_bill_input(items : ArrayView[BillItem]) -> String raise PricingError

    encode_bill_quota

    fn encode_bill_quota(report : BillQuota) -> String raise PricingError

    encode_bill_quota_input

    fn encode_bill_quota_input(input : BillQuotaInput) -> String raise PricingError

    encode_budget

    fn encode_budget(quote : BudgetQuote) -> String raise PricingError

    encode_budget_request

    fn encode_budget_request(request : BudgetRequest) -> String raise PricingError

    encode_catalog

    fn encode_catalog(catalog : Catalog) -> String raise PricingError

    encode_catalog_bill

    fn encode_catalog_bill(record : CatalogBill) -> String raise PricingError

    encode_catalog_migration

    fn encode_catalog_migration(report : CatalogMigration) -> String raise PricingError

    encode_catalog_replay

    fn encode_catalog_replay(report : CatalogReplay) -> String raise PricingError

    encode_charge

    fn encode_charge(charge : Charge) -> String raise PricingError

    Structural encoding; semantic acceptance requires verify_charge.

    encode_cohort

    fn encode_cohort(report : CohortComparison) -> String raise PricingError

    Structural encoding only; verify against trusted plans and usages on receipt.

    encode_cohort_usage

    fn encode_cohort_usage(usages : ArrayView[Usage]) -> String raise PricingError

    Encode an ordered cohort input; identities must be unique.

    encode_comparison

    fn encode_comparison(report : Comparison) -> String

    Encode all typed fields in deterministic order; verify before accepting data.

    encode_evidence

    fn encode_evidence(evidence : Evidence) -> String

    Encode every typed field in deterministic schema order. Does not validate authenticity: use verify_evidence before accepting a record.

    encode_invoice

    fn encode_invoice(invoice : Invoice) -> String raise PricingError

    Structural encoding; verify_invoice is required for semantic acceptance.

    encode_invoice_input

    fn encode_invoice_input(items : ArrayView[ChargeInput]) -> String raise PricingError

    Encode a complete trusted input manifest with embedded validated plans.

    encode_package_plan

    fn encode_package_plan(plan : PackagePlan) -> String

    encode_packages

    fn encode_packages(record : PackageEvidence) -> String raise PricingError

    encode_plan

    fn encode_plan(plan : Plan) -> String

    Deterministic schema-order JSON; decimal trailing zeroes are normalized.

    encode_quota

    fn encode_quota(quote : QuotaQuote) -> String raise PricingError

    encode_replay_cases

    fn encode_replay_cases(cases : ArrayView[CatalogReplayCase]) -> String raise PricingError

    encode_replay_policy

    fn encode_replay_policy(policy : ReplayPolicy) -> String raise PricingError

    encode_schedule

    fn encode_schedule(schedule : Schedule) -> String raise PricingError

    encode_scheduled

    fn encode_scheduled(record : ScheduledEvidence) -> String raise PricingError

    encode_usage

    fn encode_usage(usage : Usage) -> String raise PricingError

    Validate before encoding; no unknown data can be silently lost.

    encode_usage_bundle

    fn encode_usage_bundle(usages : ArrayView[Usage]) -> String raise PricingError

    quote_bill_quota

    fn quote_bill_quota(input : BillQuotaInput, scale~ : Int, rounding~ : Rounding) -> BillQuota raise PricingError

    Keep 0..63 fixed metric snapshots and maximize a safe prefix for one variable metric under the total settled bill budget, including explicit minimum rules.

    test {
    let p = @jieheng.compile_package(
    id="sms",
    version="v1",
    metric="messages",
    unit="message",
    currency="USD",
    package_size="1000",
    package_price="0.85",
    )
    let input : @jieheng.BillQuotaInput = {
    fixed: [],
    variable: PackageTariff(p),
    request: {
    customer: "acme",
    period: "October",
    budget: "3",
    limit: "10000",
    },
    }
    let q = @jieheng.quote_bill_quota(input, scale=2, rounding=HalfEven)
    inspect(q.bill.totals.amount, content="2.55")
    }

    quote_budget

    fn quote_budget(plan : Plan, request : BudgetRequest, scale~ : Int, rounding~ : Rounding) -> BudgetQuote raise PricingError

    Maximize integer quantity subject to settled charge <= budget and q <= limit. Does not apply minimum spend, package rules, taxes or cross-metric budgets.

    test {
    let p = @jieheng.compile_plan(
    id="api",
    version="v1",
    metric="calls",
    unit="call",
    currency="USD",
    tiers=[{ up_to: None, unit_price: "0.006", }],
    )
    let q = @jieheng.quote_budget(
    p,
    { customer: "acme", period: "2026-10", budget: "0.01", limit: "100", },
    scale=2,
    rounding=HalfEven,
    )
    inspect(q.evidence.calculation.usage.quantity, content="2")
    inspect(q.evidence.settlement.amount, content="0.01")
    }

    quote_quota

    fn quote_quota(plan : Plan, request : BudgetRequest, scale~ : Int, rounding~ : Rounding) -> QuotaQuote raise PricingError

    Find the largest safe prefix of integer quantities, stopping at the first unaffordable point even if later volume discounts make larger points feasible.

    test {
    let p = @jieheng.compile_plan(
    id="api",
    version="v1",
    metric="calls",
    unit="call",
    currency="USD",
    mode=Volume,
    tiers=[
    { up_to: Some("5"), unit_price: "10", },
    { up_to: Some("10"), unit_price: "1", },
    { up_to: None, unit_price: "20", },
    ],
    )
    let r = @jieheng.quote_quota(
    p,
    { customer: "acme", period: "2026-10", budget: "12", limit: "20", },
    scale=2,
    rounding=HalfEven,
    )
    inspect(r.evidence.calculation.usage.quantity, content="1")
    inspect(r.first_unaffordable.unwrap().calculation.usage.quantity, content="2")
    }

    rate

    fn rate(plan : Plan, usage : Usage) -> Calculation raise PricingError

    Rate cumulative usage according to the plan mode; never rounds individual lines.

    test {
    let plan = @jieheng.compile_plan(
    id="api",
    version="v1",
    metric="requests",
    unit="request",
    currency="USD",
    tiers=[
    { up_to: Some("1000"), unit_price: "0", },
    { up_to: None, unit_price: "0.001", },
    ],
    )
    let result = @jieheng.rate(plan, {
    customer: "acme",
    metric: "requests",
    period: "2026-09",
    quantity: "1001",
    })
    inspect(result.total, content="0.001")
    }

    rate_bill

    fn rate_bill(items : ArrayView[BillItem], scale~ : Int, rounding~ : Rounding) -> Bill raise PricingError

    Combine metered and package items with their original evidence intact.

    test {
    let p = @jieheng.compile_package(
    id="sms",
    version="v1",
    metric="messages",
    unit="message",
    currency="USD",
    package_size="1000",
    package_price="0.85",
    )
    let b = @jieheng.rate_bill(
    [
    Packaged(p, {
    customer: "acme",
    metric: "messages",
    period: "2026-10",
    quantity: "2501",
    }),
    ],
    scale=2,
    rounding=HalfEven,
    )
    inspect(b.totals.amount, content="2.55")
    }

    rate_catalog

    fn rate_catalog(catalog : Catalog, on : String, usages : ArrayView[Usage], scale~ : Int, rounding~ : Rounding) -> CatalogBill raise PricingError

    Select all required metric rules on one explicit civil date, then produce a mixed bill. Input usage order does not change the catalog's output order.

    test {
    let p = @jieheng.compile_package(
    id="sms",
    version="v1",
    metric="messages",
    unit="message",
    currency="USD",
    package_size="1000",
    package_price="0.85",
    )
    let c = @jieheng.compile_catalog([
    { starts_on: "2026-10-01", ends_before: None, tariff: PackageTariff(p), },
    ])
    let r = @jieheng.rate_catalog(
    c,
    "2026-10-22",
    [
    {
    customer: "acme",
    metric: "messages",
    period: "October",
    quantity: "2501",
    },
    ],
    scale=2,
    rounding=HalfEven,
    )
    inspect(r.bill.totals.amount, content="2.55")
    }

    rate_charge

    fn rate_charge(plan : Plan, usage : Usage, minimum~ : String, zero_usage~ : ZeroUsageMinimum, scale~ : Int, rounding~ : Rounding) -> Charge raise PricingError

    Apply an explicit single-metric minimum before one settlement operation.

    test {
    let p = @jieheng.compile_plan(
    id="api",
    version="v1",
    metric="calls",
    unit="call",
    currency="USD",
    tiers=[{ up_to: None, unit_price: "0.004", }],
    )
    let c = @jieheng.rate_charge(
    p,
    { customer: "acme", metric: "calls", period: "2026-10", quantity: "1", },
    minimum="0.005",
    zero_usage=Charge,
    scale=2,
    rounding=HalfEven,
    )
    inspect(c.top_up, content="0.001")
    inspect(c.total, content="0.005")
    inspect(c.settlement.amount, content="0.00")
    }

    rate_invoice

    fn rate_invoice(items : ArrayView[ChargeInput], scale~ : Int, rounding~ : Rounding) -> Invoice raise PricingError

    Rate multiple metrics for one customer-period, apply each explicit minimum, settle each charge, then sum minor units without a second rounding operation.

    test {
    let p = @jieheng.compile_plan(
    id="api",
    version="v1",
    metric="calls",
    unit="call",
    currency="USD",
    tiers=[{ up_to: None, unit_price: "0.006", }],
    )
    let bill = @jieheng.rate_invoice(
    [
    {
    plan: p,
    usage: {
    customer: "acme",
    metric: "calls",
    period: "2026-10",
    quantity: "1",
    },
    minimum: "0",
    zero_usage: Waive,
    },
    ],
    scale=2,
    rounding=HalfEven,
    )
    inspect(bill.total, content="0.006")
    inspect(bill.amount, content="0.01")
    }

    rate_packages

    fn rate_packages(plan : PackagePlan, usage : Usage, scale~ : Int, rounding~ : Rounding) -> PackageEvidence raise PricingError

    Round capacity up to full packages, then settle the exact package total once.

    test {
    let p = @jieheng.compile_package(
    id="seats",
    version="v1",
    metric="users",
    unit="user",
    currency="USD",
    package_size="5",
    package_price="10",
    )
    let e = @jieheng.rate_packages(
    p,
    { customer: "acme", metric: "users", period: "2026-10", quantity: "6", },
    scale=2,
    rounding=HalfEven,
    )
    inspect(e.packages, content="2")
    inspect(e.unused_units, content="4")
    inspect(e.settlement.amount, content="20.00")
    }

    rate_scheduled

    fn rate_scheduled(schedule : Schedule, on : String, usage : Usage, scale~ : Int, rounding~ : Rounding) -> ScheduledEvidence raise PricingError

    Rate one already aggregated snapshot under the selected version.

    test {
    let p = @jieheng.compile_plan(
    id="api",
    version="v1",
    metric="calls",
    unit="call",
    currency="USD",
    tiers=[{ up_to: None, unit_price: "1", }],
    )
    let s = @jieheng.compile_schedule([
    { starts_on: "2026-10-01", ends_before: None, plan: p, },
    ])
    let e = @jieheng.rate_scheduled(
    s,
    "2026-10-22",
    { customer: "acme", metric: "calls", period: "October", quantity: "2", },
    scale=2,
    rounding=HalfEven,
    )
    inspect(e.evidence.settlement.amount, content="2.00")
    }

    render_bill_markdown

    fn render_bill_markdown(items : ArrayView[BillItem], bill : Bill, scale~ : Int, rounding~ : Rounding) -> String raise PricingError

    Verify against the complete trusted manifest before returning a deterministic Markdown statement. Includes lossless canonical input and bill JSON appendices. No partial output is returned on verification, encoding or size failure.

    replay_catalogs

    fn replay_catalogs(before : Catalog, after : Catalog, cases : ArrayView[CatalogReplayCase], scale~ : Int, rounding~ : Rounding) -> CatalogReplay raise PricingError

    Replay complete metric snapshots against two trusted catalog versions on each case's explicit date. Missing or incompatible metrics reject the batch.

    test {
    let p = @jieheng.compile_package(
    id="sms",
    version="v1",
    metric="messages",
    unit="message",
    currency="USD",
    package_size="10",
    package_price="1",
    )
    let c = @jieheng.compile_catalog([
    { starts_on: "2026-01-01", ends_before: None, tariff: PackageTariff(p), },
    ])
    let cases : Array[@jieheng.CatalogReplayCase] = [
    {
    on: "2026-10-22",
    usages: [
    {
    customer: "acme",
    metric: "messages",
    period: "October",
    quantity: "11",
    },
    ],
    },
    ]
    let r = @jieheng.replay_catalogs(c, c, cases[:], scale=2, rounding=HalfEven)
    inspect(r.unchanged, content="1")
    }

    select_plan

    fn select_plan(schedule : Schedule, on : String) -> Plan raise PricingError

    Select exactly one version by an explicit civil date; usage.period is opaque.

    settle

    fn settle(calculation : Calculation, scale~ : Int, rounding~ : Rounding) -> Settlement raise PricingError

    Settle an exact total with an explicit decimal scale and rounding rule. Currency is a label, not an ISO currency database; callers choose the scale.

    verify_analysis

    fn verify_analysis(baseline : Plan, candidate : Plan, limit : String, report : PriceAnalysis) -> Unit raise PricingError

    Prove complete canonical coverage, both affine functions and endpoint extrema against trusted plans. No sampled-quantity assumption or solver reexecution.

    verify_bill

    fn verify_bill(items : ArrayView[BillItem], bill : Bill, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Reject model substitution, omission, reordering and forged totals. Each item is checked by its independent pricing verifier, against the trusted manifest.

    verify_bill_comparison

    fn verify_bill_comparison(before : ArrayView[BillItem], after : ArrayView[BillItem], report : BillComparison, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Verify both complete bills against trusted manifests, then check alignment and every signed difference. Does not invoke compare_bills or rate_bill.

    verify_bill_quota

    fn verify_bill_quota(input : BillQuotaInput, report : BillQuota, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Verify fixed settlements, every model-specific witness and prefix safety. Uses verified fixed amounts and rounding thresholds, never quota/rate producers.

    verify_budget

    fn verify_budget(plan : Plan, request : BudgetRequest, quote : BudgetQuote, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Check trusted request, allocation, settlement, feasibility and global maximality. For Volume, examine the cheapest larger point of every tier.

    verify_calculation

    fn verify_calculation(plan : Plan, usage : Usage, calculation : Calculation) -> Unit raise PricingError

    Verify a supplied breakdown against trusted plan and usage snapshots. Does not invoke rate(): checks a contiguous partition, per-tier products, and conservation of the exact quantity and amount independently.

    verify_catalog

    fn verify_catalog(catalog : Catalog, on : String, usages : ArrayView[Usage], record : CatalogBill, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    verify_catalog_migration

    fn verify_catalog_migration(before : Catalog, after : Catalog, starts_on : String, ends_before : String, report : CatalogMigration) -> Unit raise PricingError

    Independently check ordered coverage, maximal intervals and trusted selections. Does not call audit_catalog_migration or its sorted-boundary algorithm.

    verify_catalog_replay

    fn verify_catalog_replay(before : Catalog, after : Catalog, cases : ArrayView[CatalogReplayCase], report : CatalogReplay, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Verify complete dated input binding and both bills of every row, without invoking replay_catalogs or pricing producers, then conserve all aggregates.

    verify_charge

    fn verify_charge(plan : Plan, usage : Usage, charge : Charge, minimum~ : String, zero_usage~ : ZeroUsageMinimum, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Verify usage allocation, explicit policy binding, floor conservation and the independently checked rounding interval. Does not invoke rate_charge.

    verify_cohort

    fn verify_cohort(baseline : Plan, candidate : Plan, usages : ArrayView[Usage], report : CohortComparison, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Independently verify every row and its binding to trusted input order, then check exact conservation of all totals and both signed differences.

    verify_comparison

    fn verify_comparison(baseline : Plan, candidate : Plan, usage : Usage, report : Comparison, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Validate both sides against trusted inputs and recompute signed differences.

    verify_evidence

    fn verify_evidence(plan : Plan, usage : Usage, evidence : Evidence, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Verify against trusted inputs and policy, never against embedded claims alone.

    verify_invoice

    fn verify_invoice(items : ArrayView[ChargeInput], invoice : Invoice, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Verify against the complete trusted item list and settlement policy. Missing/reordered/duplicated charges and all forged aggregates are rejected.

    verify_packages

    fn verify_packages(plan : PackagePlan, usage : Usage, record : PackageEvidence, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Independently check capacity conservation and minimality without repeating the producer's ceiling division, then check exact price and rounding interval.

    verify_quota

    fn verify_quota(plan : Plan, request : BudgetRequest, quote : QuotaQuote, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Independently verify the whole feasible prefix and the first unsafe neighbor. Does not invoke quote_quota, curve_piece, binary search or settlement producers.

    verify_scheduled

    fn verify_scheduled(schedule : Schedule, on : String, usage : Usage, record : ScheduledEvidence, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    verify_settlement

    fn verify_settlement(calculation : Calculation, settlement : Settlement, scale~ : Int, rounding~ : Rounding) -> Unit raise PricingError

    Verify arithmetic and an explicitly trusted settlement policy. This checker uses rounding error intervals and tie parity, not settle().