Every generator in Studio costs real money to run: model calls, image generation, rendering. A workspace pays in credits. The awkward property of generation is that the cost is incurred up front and the result arrives minutes later, or does not arrive. This page is about charging for something that might fail, and giving the money back exactly once when it does.
The flow

- The route creates the document for the thing being generated.
- It deducts the price. If the workspace cannot pay, the document is deleted again and the request is answered 402.
- It starts the pipeline as a background task, passing the reference it charged under.
- If the pipeline raises, its error path refunds by that reference. Two failures fall outside this: a second phase started by confirming an outline carries no reference, and a run that dies with the process is marked failed by the sweeper. Neither is refunded.
Charging first is deliberate. Charging on success would mean that a workspace with no credits could start any number of expensive runs and only be stopped when they finished.
Lots and a ledger
Two collections hold the money, and they have different jobs.
| Collection | Is | Holds |
|---|---|---|
| Credit lots | The balance | One row per grant of credits: its source, the amount, how much remains, when it was granted, when it expires |
| Credit ledger | The journal | One row per event: workspace, signed amount, balance after, type, pipeline, reference, time |
A comment at the top of the lot model states the division: the lot is the truth of the balance, and the ledger is the audit journal. The balance field on the workspace is a cache that is recomputed from the lots.
Why lots. Credits are not all alike. Credits from a subscription, credits bought as a top-up and credits returned as a refund have different lifetimes: purchased credits expire after 30 days, and a refund never expires. A single balance number cannot say which credits a charge should use. Lots can.
A deduction runs in this order.
- Backfill a lot for any balance that predates lots.
- Expire lots whose date has passed.
- Consume from the lots that expire soonest, first in first out.
- Recompute the cached balance.
- Write the ledger row.
Spending the soonest-to-expire credits first is the customer-friendly order. A customer with 100 credits expiring tomorrow and 100 expiring next month keeps the ones that last.
The reference
Every charge carries a reference, and the refund is found by it. What the reference is made of turned out to be the subtle part.
The obvious reference is the document id. One article, one charge, one possible refund. That breaks on retries.
| Sequence with the document id as reference | Result |
|---|---|
| Attempt 1 is charged, fails, is refunded | Correct |
| The user retries. Attempt 2 is charged under the same reference, and fails | The refund finds an existing refund for that reference and skips. The user has paid for a failed run |
So the reference is the document id plus a nonce generated for each paid attempt. Each attempt is its own charge with its own possible refund. A retry that the system offers for free passes no reference, and so can never trigger a refund of the original charge.
Two tests pin both sides: one shows that a shared document-id reference under-refunds the second attempt, and one shows that the per-request nonce does not.
A refund that happens once
The refund function is a sequence of guards, each returning early.
already_refunded = await CreditLedger.find_one(
CreditLedger.workspace_id == workspace_id,
CreditLedger.pipeline == pipeline,
CreditLedger.reference_id == reference_id,
CreditLedger.type == "refund",
)
if already_refunded:
return True
matching_deduct = await CreditLedger.find_one(
CreditLedger.workspace_id == workspace_id,
CreditLedger.pipeline == pipeline,
CreditLedger.reference_id == reference_id,
CreditLedger.type == "deduct",
)
Logging between the two queries is removed here.
| Guard | Why |
|---|---|
| No workspace, or a price of zero | Nothing was charged |
| An empty reference | Without a reference a refund cannot be matched, so none is made |
| A refund row already exists for this workspace, pipeline and reference | The refund has been made. A pipeline’s error path can run twice |
| No deduct row exists for it | Nothing was charged for this attempt, for example a free retry |
Only after all four does the function issue a lot. The refund lot has no expiry, because the customer should not lose refunded credits to a clock they did not start.
Workspaces
Credits belong to a workspace, not a user. A user can be a member of several workspaces with a role in each: owner, admin, member or viewer.
The workspace for a request is resolved by a dependency. The resolver used on ownership and write paths works as follows.
| Case | Resolved workspace |
|---|---|
| The request names a workspace | That workspace, after a membership check |
| It names none | The user’s oldest membership |
| A guest | A synthetic id unique to that guest |
| A user with no workspace | A synthetic id unique to that user |
Queries then filter by that id. Plans attach to the workspace and set its credit allowance, with one plan unmetered.
Tests
| Test | Asserts |
|---|---|
test_refund_credits_idempotent_same_reference_id | A second refund for one reference is skipped |
test_refund_credits_different_reference_id_not_deduped | Two attempts are refunded separately |
test_refund_credits_empty_reference_id_is_noop | No reference, no refund |
test_refund_credits_without_matching_deduct_is_noop | Nothing charged, nothing refunded |
test_refund_credits_survives_balance_resync | A refund is still there after the cached balance is recomputed |
test_shared_doc_id_reference_would_under_refund_second_attempt | The document id alone is the wrong reference |
test_per_request_nonce_avoids_same_doc_under_refund | The nonce fixes it |
test_article_free_retry_failure_does_not_refund_original_paid_create | A free retry cannot refund the original charge |
test_guest_resolves_to_isolated_synthetic_id | The strict resolver gives a guest its own synthetic id |
Failure modes
| What happens | What the system does |
|---|---|
| The workspace cannot pay | 402, and the half-created document is removed |
| The pipeline raises in the run that was charged | Refunded by the attempt’s reference |
| The pipeline raises after the outline was confirmed | Not refunded: the second phase carries no reference |
| The process dies mid-run | The sweeper marks the document as an error. No refund is issued |
| The error path runs twice | The second refund is skipped |
| A free retry fails | No refund, because nothing was charged for it |
| Credits reach their expiry | The lot is expired before the next deduction is computed |
| The cached balance is stale | It is recomputed from the lots |
Limits
- Refunds are idempotent and deductions are not. A refund is matched by reference. A deduction is not deduplicated by reference, so the guard against double charging is that a route charges once per request.
- Consuming lots is a read followed by writes. It is not one atomic update. Two simultaneous charges on one workspace are rare in a tool used by a person at a keyboard, and they are not excluded by the database.
- Charging is an explicit call in each handler. A decision record proposed a dependency that would charge by declaration. It was not built, so a new route has to remember to charge.
- Not every failure is refunded. A failure after outline confirmation and a run that dies with the process keep their charge.
- Tenant filtering is written in each query. There is no layer that applies it automatically, and read paths use a different resolver from write paths.
