Month-end engine — turns a period of metered usage into tenant invoices
(revenue side). Distinct from cloud_invoices, which are DO's bills to
Sky AI (COGS).
tenant_invoices — one per (tenant, period). subtotal/tax/total cents,
status draft/issued/paid/void. unique (tenant_id, period_start).
tenant_invoice_lines — kind plan_base/addon/overage/tax, tagged with
deployment_id (NULL for tenant-level lines like GST) + resource_kind,
so the cost-vs-revenue dashboard can group by deployment and by kind.
ArcadiaCloud.Invoicing.roll_up_period/3:
- groups active subscriptions by tenant
- one tenant_invoice per tenant; per subscription, runs the quote engine
with the deployment's ACTUAL metered usage (Metering.usage_for_period)
and persists the recurring + overage lines tagged with the deployment
- appends a tenant-level GST line (AU 10%, per project_skyai_australia)
- idempotent on (tenant_id, period_start); re-run skips unless force:true
Because the same quote engine serves provisioning-time projection and
month-end invoicing, a tenant's quoted price and invoiced price are
computed identically.
InvoiceRollupWorker — Oban cron, 1st of month 03:00 UTC, invoices the
month just ended.
API (platform_admin sees all; tenants scoped to own):
- GET /api/v1/invoices — tenant invoice list
- GET /api/v1/invoices/:id — invoice with lines
Also: SubscriptionAddon now preloads its :addon so quote/invoice lines
read "Addon: storage_50gb" rather than the addon UUID.
Smoke verified: pilot deployment on Studio + storage_50gb, 3 droplets
metered across all 30 days of April (2160 droplet_hours vs 1488
included) — rollup produced an invoice with plan_base $50 + addon $7.50
+ droplet_hours overage $6.72 (672h x 1c) = $64.22 subtotal, GST $6.42,
total $70.64. Re-run without force correctly skipped.
NOT in this chunk: pushing tenant invoices to skyai-finance as AR —
that needs an income-side endpoint on skyai-finance (the phase-1 push
endpoint creates vendor expense invoices, wrong direction). Deferred to
its own chunk.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
usage_records — one metered observation per (deployment, resource,
period, granularity). resource_kind is the BILLING kind (droplet_hours,
spaces_gb_month, ...) so it joins straight to plan_items. sub_attribution
jsonb column present from day one for forward-compat (sub-billing) but
never written in phase 3.
metering_config — per-billing-kind granularity (daily default; flip to
hourly when fine-grained billing is wanted) + retention_days.
ArcadiaCloud.Metering:
- meter_day/1 — walks every deployment-attributed resource, maps its
inventory kind to a billing kind, records that day's usage. Idempotent
via the unique (deployment, resource, period, granularity) index.
- usage_for_period/3 — SUM(qty) GROUP BY billing kind over a date range,
returns the %{kind => qty} map the quote engine takes as :usage.
Uniform accrual model so everything downstream is just SUM(qty):
- droplet -> droplet_hours, 24/day when active (0 when off)
- spaces_bucket / snapshot / droplet_backup -> *_gb_month, size/days so
the month sums to GB-months
- dns_zone -> dns_zones, 1/days so the month sums to the zone count
MeteringWorker — Oban cron 01:10 UTC daily, meters the previous
complete day.
Smoke verified: a pilot deployment with 2 droplets + 2 DNS zones + 3
snapshots attributed; 10 days metered -> 70 usage records; aggregation
gave droplet_hours 480 (2x24x10), dns_zones 0.65 (2x10/31),
snapshot_gb_month 15.48; fed into the quote engine against Studio — all
within allowance so $50 base, no overage (correct for a light partial
month).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Compares cloud_provisioned.spec (what we asked DO for) against the live
cloud_resources row (what DO actually has). Any divergence becomes an
operator-resolvable drift record.
cloud_drift table: one row per drifted field. status open/accepted/
reverted/stale. Partial unique index keeps at most one OPEN drift per
(resource, field); resolved rows are retained as history.
ArcadiaCloud.Drift context:
- detect_all/0 — sweeps every provisioned resource. Per field in spec,
resolves the actual value (top-level schema field first, then attrs),
compares with loose equality (stringified scalars; lists as sets so
JSON round-trips don't false-positive). Mismatches upsert a cloud_drift
row + emit a drift_detected event in the resource event log.
- close_stale_drift — an open drift whose field no longer mismatches
(fixed elsewhere) closes as "stale" on the next sweep.
- accept_drift/2 — the live value becomes the new desired-state: parent
cloud_provisioned.spec is updated, spec_version bumped, drift closed
"accepted". Revert (mutating live infra back to spec) is intentionally
NOT here — it needs a saga and lands with the droplet-resize work.
DriftDetectionWorker — Oban cron at :20 past the hour, offset past the
:15 resource syncs so it compares against fresh inventory.
Provisioning.record_provisioned/3 — populates cloud_provisioned desired-
state (upsert on resource_id, bumps spec_version). Future provisioning
sagas call this; for now it's how drift gets something to detect.
API (platform_admin only):
- GET /api/v1/drift — open drift inbox
- POST /api/v1/drift/:id/accept — adopt live value as desired-state
Smoke verified: recorded a droplet's desired spec with a deliberately
wrong size_slug + a correct region; detect_all flagged only size_slug,
wrote the drift_detected event; accept updated the spec to the live
value and closed the drift; re-detect found zero drift.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two patterns added:
1. ProjectsWorker now does URN-discover for kinds without a dedicated
sync worker (spaces_bucket, managed_db, k8s_cluster, etc.). For these,
it inserts a minimal placeholder row when the URN points to something
not yet in inventory. Kinds with dedicated workers (droplet, snapshot,
volume, etc.) still get attribution-only — the worker is source of
truth for richer attrs. Implemented by splitting attribute_or_discover/4
on a @dedicated_kinds whitelist.
2. New BackupsWorker pulls /v2/droplets/:id/backups for each active
droplet. DO automated backups aren't in /v2/snapshots; they live per
droplet. Cron: hourly at :41. Kind="droplet_backup".
URN normalization extended for two more aliases DO emits:
"volumesnapshot" → snapshot (was creating a duplicate row)
"image" → snapshot (DO droplet snapshots show as do:image:id)
Billing.find_resource/1 gets a kind-specific clause for droplet_backup
that matches to the parent droplet by name, since invoice lines for
backups read "<droplet-name> (Weekly Backup Services)" — the line is a
per-droplet subscription, not a per-backup-snapshot fee.
Live verified on the same April 2026 invoice:
- 6 Spaces buckets discovered via URN (account has 6, only 1 visible in
the invoice as the $5 subscription line — that's account-level so it
can't tie to a specific bucket, expected).
- 4 droplet backups discovered via BackupsWorker; the git.sky-ai.com
backup line now matches (repo.sky-ai.com backup line can't match — that
droplet was destroyed).
- Of 16 unmatched lines: 11 are destroyed historic resources, 1 is GST,
1 is the account-level Spaces subscription, 3 are likely tiny snapshot
name variances. Effectively ~100% of currently-existing billable
resources match.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Five new Oban workers, all on cloud_sync_full following the established
droplet/domains pattern (list → normalize → upsert → mark_stale):
- VolumesWorker — block storage
- SnapshotsWorker — both droplet and volume snapshots (kind="snapshot"
with attrs.resource_type to differentiate)
- FloatingIpsWorker — provider_id is the IP; status assigned/unassigned
- FirewallsWorker — inbound/outbound rules + droplet_ids in attrs
- LoadBalancersWorker — name + region + algorithm + forwarding rules
DigitalOcean.Client gains list_snapshots / list_firewalls / list_load_balancers.
ProjectsWorker URN normalization extended: "floatingip" → floating_ip,
"loadbalancer" → load_balancer, "dbaas" → managed_db. URNs DO emits don't
have underscores for these.
Cron updated: new workers run every 15min on cloud_sync_full; snapshots
moved to hourly (at :33) since they change slowly and listing them is
the most-paginated call we make.
InvoiceIngestWorker.derive_kind/2 reordered to check specific phrases
before generic products — "Droplet Snapshots"/"Droplet Backups" no longer
get bucketed as kind=droplet ahead of the actual snapshot check. Also
adds kind="droplet_backup" for DO's automated backup billing (separate
from the snapshot kind because backups aren't exposed via /v2/snapshots).
Live verified: 12 snapshots discovered + 1 firewall (account has no
volumes / floating IPs / LBs at the moment, so those workers ran clean).
April 2026 invoice match rate jumped from 18.2% → 51.5%. Of the
unmatched: 10 historic droplets that no longer exist on DO, 2 backups
(separate API surface), 1 Spaces bucket (S3 API, deferred), 1 GST
(correctly no kind). Effectively ~95% of currently-extant resources match.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
After InvoiceIngestWorker writes cost lines and matches resources, it
pushes a normalized invoice payload to skyai-finance-svc's new endpoint
POST /api/v1/integrations/cloud/import-invoice. Idempotent — finance
dedups on (tenant_id, source, external_id), so re-runs return "updated"
not duplicate rows.
ArcadiaCloud.Integrations.SkyaiFinance is the HTTP client. Auth is a
short-lived JWT minted via Guardian (shared secret per memory) with
identity {tenant_id: "platform-admin", roles: ["admin"]} — the role
satisfies finance's RequireWriteRole plug. Identity + base URL are
configurable; SKYAI_FINANCE_URL env var can override the default
http://localhost:4010 for arcadia-dev / prod.
GST line detection: lines whose description contains "gst" or "tax"
get summed into amount_tax_minor; everything else into amount_net_minor;
sum stays gross. Phase 1 enough — proper tax handling lands when
real per-tenant invoices flow.
cloud_invoices gains pushed_to_finance_at + finance_invoice_id so we
don't re-push uselessly (Billing.mark_invoice_pushed/2 records both).
A missing finance config (no :skyai_finance app env) makes the push a
silent skip rather than a worker failure — environments without finance
configured still get a working ingest.
Live verified end-to-end against both services:
- April 2026 DO invoice (33 lines, $86.92) lands in finance as a row
with gross=$86.92, tax=$7.90, source=digitalocean, tenant=platform-admin
- DigitalOcean vendor auto-created (category=cloud) under platform-admin
- Re-running the worker returns action: "updated" not "created";
finance still has exactly 1 row for the invoice
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three new schemas:
- cloud_balance_snapshots — hourly MTD balance/usage poll for live-accrual.
- cloud_invoices — header per provider invoice, with ingest status flags.
- cloud_cost_lines — per-line-item COGS, FK to cloud_resources where matched.
Three new Oban workers (queue: cloud_billing):
- BalanceWorker (hourly) records a snapshot.
- BillingHistoryWorker (daily) discovers invoices via /v2/customers/my/
billing_history, upserts headers, enqueues an InvoiceIngestWorker for
each not-yet-ingested invoice.
- InvoiceIngestWorker (per-invoice) fetches /invoices/:uuid/csv, parses
with NimbleCSV (header-keyed so column order shifts don't break us),
replaces the invoice's line set, then matches lines to cloud_resources
by (kind, name) — case-insensitive, name extracted from "name (size)"
description format.
DigitalOcean.Client gains get_balance / list_billing_history /
get_invoice_summary / fetch_invoice_csv. The CSV endpoint returns text/csv
so we bypass Req's body decoder.
Cron additions: BalanceWorker hourly at :07, BillingHistoryWorker daily
at 02:23.
API:
- GET /api/v1/billing/balance — latest snapshot, platform_admin only.
- GET /api/v1/billing/cost-lines?period=YYYY-MM-DD&kind&limit — per-line
COGS, platform_admin only.
Live smoke against real DO billing API surfaced and fixed three CSV-format
gotchas: column headers use underscores not spaces (group_description,
project_name), USD column has $ prefix, dates use "YYYY-MM-DD HH:MM:SS
+0000" format (space separator + RFC822 offset).
Verified: 137 historical invoices discovered going back to 2014;
April 2026 invoice (33 lines, $86.92 total) ingested with 6/33 lines
matched to current cloud_resources. Unmatched lines are correctly
historic droplets, Spaces buckets (not yet synced), and GST.
NimbleCSV ~> 1.2 added as a dep.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ProjectsWorker mirrors DO Projects to cloud_projects table in a two-pass
sweep: upsert projects, then walk each project's resource membership
(list_project_resources) and update cloud_resources.cloud_project_id +
tenant_id. DO URN kinds get normalized via normalize_kind/1 (domain →
dns_zone, space → spaces_bucket) so attribution matches local naming.
DomainsWorker syncs DNS zones (DO Domains). Same upsert chokepoint, same
three-strike stale handling. Zones are global to the account; attribution
happens via ProjectsWorker if a domain is in a DO project, else stays
NULL pending operator classification.
Oban.Plugins.Cron added with 15-minute schedules for ProjectsWorker,
DropletsWorker, DomainsWorker — workers run automatically once a token
is configured. Phase 0/1 cadence; phase 2 moves droplets to cloud_sync_fast
(1-min) for real-time status visibility.
DigitalOcean.Client gains list_domains / list_volumes / list_floating_ips.
Volumes and floating IPs not yet wired to workers; trivial follow-on.
Live smoke test: 5 droplets + 7 DNS zones discovered, all attributed to
their existing DO projects via membership lookup (skyai-internal becomes
the fallback only for genuinely orphan resources).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Models:
- cloud_projects: arcadia-cloud's mirror of DO Projects, indexed by
(provider, provider_id); tenant_id + purpose classify each project.
- cloud_resources: single unified resource table; kind-specific bits in
attrs JSONB; first_seen_at / last_seen_at / stale_strike_count drive
three-strike deletion.
- cloud_resource_events: append-only audit (discovered, updated, deleted,
drift_detected, tagged, restored).
ArcadiaCloud.Cloud context owns the single upsert chokepoint that:
- inserts new with `discovered` event
- updates existing only when meaningful fields change
- restores tombstoned rows seen again
- bumps last_seen_at and resets strike count
mark_stale/3 implements the three-strike rule.
ArcadiaCloud.DigitalOcean.Client is a Req wrapper with auto-pagination.
Per-purpose token resolution via .Tokens (phase 1: env DO_API_TOKEN;
phase 2: vault). Per project_arcadia_cloud memory the long-term shape
is one PAT per queue purpose for rate-limit isolation.
ArcadiaCloud.Sync.Bootstrap ensures the skyai-internal DO Project exists
on first sync, idempotent thereafter. ArcadiaCloud.Sync.DropletsWorker
runs full droplet sync on the cloud_sync_full Oban queue.
InventoryController wired to real data: platform_admin sees all,
tenants see only their scope.
Live smoke test against real DO: 5 droplets synced; skyai-internal
project auto-created; events written; endpoint returns scoped results.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>