Repository navigation
AI-3756: no sandbox for a suspended or unpaid organization - #2410
martinmitrevski merged 7 commits into
Conversation
A Daytona sandbox on Stream's account was made, and started again, with no admission: a suspended organization, or one with no credit or past its spend hard limit, could run paid VMs next to a free custom LLM. The sandbox now goes through Gate.Admit as an LLM response does, before it is made, started again or used, and on its lifecycle timer every slice while it runs. A running sandbox refused is stopped as at an idle stop, and starts again on the next run its organization may pay for. A suspended organization is always refused; one that may spend no money is refused unless the sandbox is in its own Daytona organization. A refusal that only means the money could not be checked leaves a running sandbox running. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The once-a-minute admission rode the lifecycle timer, which waits for the gate a run holds for up to 30 minutes, so a refused organization's code ran on. Each call in the sandbox is now watched: a goroutine owned by the call admits the owner every AdmitEvery and cuts the call on a refusal; the sandbox is then stopped under the gate and the run returns the refusal. One whose session closed is not stopped, as its delete follows. A BYOK sandbox is refused on Admission.Spend as a BYOK model is: the LLM path's rule (Spend and Recorder.Billable), on the config the sandbox's meter bills under. A sandbox with no recorder is taken as billable. newSandboxes takes the *policy.Enforcer, so its test covers the nil guard and the gate it builds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
thesyncim
left a comment
There was a problem hiding this comment.
Reviewed at 6a79381 merged with main 0e5197a. Every path I found that makes or wakes a sandbox goes through the new check, and a race probe of 8 callers with refusals flipping was clean under -race. Two should-fixes are inline; both are about stopping a running sandbox.
Tests that would hold rules nothing holds now (each mutant passes): passing nil for policies in main.go; the second call after a vanished sandbox left unwatched (daytona.go:441); arm using admitEvery when the idle stop is sooner; halt ignoring the stop's error.
Questions
- A customer's own sandbox account is refused with no credit here, where #2406 serves a customer's own vendor account. Is the difference meant?
watcheddrops the result of a run that finished in the moment the check refuses, so the model is told it was refused though the code ran. Return the result and still halt?
Nit: a free price entry with a class condition, as the priced entries have, is not matched in metered/sandbox.go since the config has no attributes, so such a sandbox is refused with no credit. Pass the attributes, or say in the README that only an entry without conditions counts.
| func (s *Sandbox) halt(ctx context.Context, refusal error) { | ||
| stop, end := context.WithTimeout(context.WithoutCancel(ctx), s.check) | ||
| defer end() | ||
| if err := s.box.Stop(stop); err != nil { |
There was a problem hiding this comment.
Should fix: Stop can return an error after Daytona stopped the sandbox: the SDK posts the stop and then waits for stopped, so a lost answer or a wait that times out ends here. The sandbox then stays recorded as running, with stoppedAt zero. I let daytonatest stop the sandbox but dropped the answer: the meter kept running, and once the owner was admitted again every run failed with "sandbox sandbox-1 is not started", because lapsed() is false and revive is never reached. Each failed run moves used, so it stays that way until the sandbox idles out. With the sandbox deleted by someone else, halt fails every minute with not found and the meter is never told it is gone. Could this read the state after a failed stop, and take stopped/stopping/archived as stopped and not found/destroyed as lost? Ignoring the stop's error also passes the tests, so a failing stop needs one.
There was a problem hiding this comment.
Fixed in 99c40cd (tests in d642a06). After a failed stop, halt now reads the sandbox's state (the read is shared with vanished as deleted). Stopped, stopping or archived is billed as stopped and started again by the next run that is allowed. Not found or destroyed is forgotten and its meter told it is gone, so nothing is stopped every minute. A stop that never reached Daytona leaves it running until the next check. admit_test.go covers the lost answer, the sandbox deleted by someone else, a stop that did not happen, and the stopping and destroyed states; ignoring the stop's error fails the would-not-stop test.
| return nil | ||
| } | ||
| return func(ctx context.Context, running bool) error { | ||
| admission, err := s.options.Gate.Admit(ctx, owner) |
There was a problem hiding this comment.
Should fix: Admit counts what is set aside as well as what is spent, so a running sandbox is stopped, and its code cut, while the organization still has credit. With 1,000,000 of credit and one other reservation of 1,500,000, the running sandbox was stopped at its next check as no credit left; releasing the reservation admitted it again at once. An uncapped response near the end of a balance, or several at once, does that. For new work the caller can retry, but here a run of up to 30 minutes is lost. It also counts the sandbox's own lease, which Reserve leaves out on purpose ("never refused for its own last minute"). Could a running sandbox be stopped only for suspension or for money spent, not held?
There was a problem hiding this comment.
Fixed in f39af6c. A running sandbox is now checked with Enforcer.AdmitRunning (routing.RunningGate), which counts money spent, not set aside: the balance as a low-balance warning reads it (settledBalance), and the spend hard limit and the customer's limits by their ledgers alone. Neither another reservation nor its own lease stops it; suspension and money actually spent still do. Starting or restarting one still uses Admit, so new work can still be refused for held money. With your numbers the running sandbox keeps running and a new one is refused (metered/sandbox_admission_integration_test.go, plus five cases in policy/money_test.go).
…keeps its result A stop whose answer was lost, or whose wait ran out, reads the sandbox's state: stopped, stopping or archived is billed as stopped and started again by the next admitted run, and one someone else deleted is forgotten, its meter told it is gone, rather than stopped again every minute. A stop Daytona did not make leaves it running, to be stopped at its next admission. A refusal that lands as a run finishes no longer drops the run's result: the code ran, so its output and files come back, and the sandbox is stopped once they are read, under the gate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…set aside Admit counts every hold, so a reservation of other work, or the sandbox's own lease, stopped a running sandbox and cut its run while its organization still had credit. The enforcer's AdmitRunning (routing.RunningGate) counts what was spent instead: the balance a warning reads (settledBalance), and the spend hard limit and the customer's limits on their ledgers alone, as their holds keep no reservation apart. A new or stopped sandbox is still admitted with Admit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rganization may pay for A test through buildSessions and Manager.Run, with a model that calls run_code: an organization with no credit has no sandbox made, one with credit does. It fails when buildSessions hands newSandboxes no policies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… a refusal stopping it once Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks. Both inline points are fixed (replied there). On the rest: Tests for the surviving mutants: each now has a test that fails with it. The
Nit (free entry with a |
Why
Nothing asked whether an organization could pay before a sandbox was made on Stream's shared Daytona account.
Enforcer.Sandbox(internal/policy/sandbox.go:154-195) checks only the sandbox limits (size, network, concurrency), and only once, when the session opens.metered.Sandboxes.Openanddaytona.Sandbox.create(daytona.go:495) andrevivenever callAdmit. A suspended organization, or one with no credit or past its spend hard limit, could pair a freecustom/*LLM withsandbox: daytonaand run paid Daytona VMs for as long as it liked. A sandbox already running when money ran out also billed on until it went idle, and code could run in it for up to 30 minutes (timeout_ms).How it works
The sandbox now goes through the same
Gate.Admitas an LLM response (internal/llmrouter/session.go:613), with the same rule forAdmission.Spend. Daytona asks before any work that starts billing, and again every minute while the sandbox runs, idle or running code.Gate.Admitand nothing else, so limits mode comes from the enforcer. Off allows. Shadow allows and counts "would refuse" (LimitHit,Enforced=false). Enforce refuses.admission.Spend != nil && recorder.Billable(config), asllmrouter/session.go:619, withconfigthe one the sandbox's meter bills under (sandboxMeter.config(): daytona, running, its region, BYOK). A BYOK sandbox is billable at its 20% fee (pricing.BYOKModalities), so it is refused like a BYOK model. A Stream sandbox stays billable:vendor.json's sandbox entries name aclass, so an item with no attributes matches none, and an unmatched item is billable. Only a price list that makes sandboxes free admits one with no credit.create(daytona.go:589) andwake's start (:743) are the only calls that make Daytona bill, and both run behindstarted().metered.Sandboxes.Openis the only caller ofdaytona.New.usewraps the call inwatched. Its goroutine only callsAdmitand cuts the call's context. The stop is made after the goroutine is joined, under the gate the call holds, so it never racesClose, the idle stop or the timer. The goroutine is owned by the call, ends with it, and is not started for a sandbox with noAdmit. It starts throughgoroutine.Go, so a panic in it ends that call, not the router.Enforcer.Admit, which counts reservations, as new work does. One already running goes throughEnforcer.AdmitRunning(routing.RunningGate), which takes the balance as a low-balance warning reads it (settledBalance: this router's recorded work, no reservations, its own lease included) and the spend hard limit and the customer's limits by their ledgers alone, and records no grant draw. So a reservation elsewhere never cuts a run while the organization has credit; suspension and money actually spent still do.haltthen reads the state: stopped, stopping or archived is billed as stopped and started again by the next run that is allowed; not found or destroyed is forgotten and its meter told it is gone; anything else stays running and is stopped at the next check.done, once its files have been read, under the same gate.haltdoes what the idle stop does (stoppedAt,letGo,meter.Stopped) and also calls Daytona's stop. The files stay, and only disk bills. The next run its organization may pay for starts the same sandbox again.StoppedDeleteand the session's close delete it as before.Runreturns thepolicyerror unchanged, also when it cut the run. The agent and the harness hand its text to the model ("the organization has no credit left; …"), as they already do forErrSandboxLimit.newSandboxes(cmd/router/sandboxes.go) takes the*policy.Enforcerand setsSandboxesOptions.Gatefrom it, asmetered.Knowledgetakes its gate.AdmitEveryisSandboxesOptions.Every, which production leaves at zero: a minute.Decisions to check
Admission.Spend, as a BYOK LLM call isRecorder.Billableon the meter's config), not a sandbox-specific one.Recorder.Billableis checked for every sandbox, not just BYOKwhen-less entry matches them. A deployment whose price list marks them free admits them with no credit.SandboxesOptionswith noRecordertakes the sandbox as billableAdmitdoes for LLM calls there. No suspension, credit or hard limit exists there, so only a spend limit the customer set can refuse. Untested.Enforcer.Sandbox(the ticket's suggestion)api/configs.go:1022shares it on config save. Money can run out long after the session opens, so the check sits where billing starts.policy.Transientsays work under way should wait for the check rather than end. A new or stopped sandbox is still refused, as an LLM call is.routing.Sliceslease refusals (the ticket's step 2)Reserve, which refuses a lease, checks whatAdmitchecks, and the watch asks every minute rather than on the 30 s renewal. One difference:Admitcounts the sandbox's own lease hold, so a sandbox stops when less than about a minute of its cost is left, as the organization's other billable work is refused then too.watchedcoversuse's call, not the downloads after it, which are bounded by the 60 s check timeout.usewraps the call (the run, a write), notstarted(). Create, the wait for start, a revive and the setup are admitted once, just before, and then hold the gate unwatched for up toTimeout: 20 minutes for a built image's first start, 60 seconds otherwise. A refusal in that window is seen by the call's first check or the timer's next one.Closegave up waiting and its delete follows as the run lets the gate go. A stop would setstoppedAt, so if that delete failed the timer would never try it again (it retries only an idle running orphan), aslapsealready skips admission once closed.Validation
MeteredSuite/TestASuspendedOrganizationNeitherMakesNorStartsAgainASandboxMeteredSuite/TestAnOrganizationWithNoCreditNeitherMakesNorStartsAgainASandboxMeteredSuite/TestAnOrganizationOverItsSpendHardLimitNeitherMakesNorStartsAgainASandboxMeteredSuite/TestASandboxInTheOwnersOwnDaytonaOrganizationIsRefusedWithNoCreditAdmission.Spend, unlike a BYOK modelMeteredSuite/TestASandboxThePricesMakeFreeIsMadeWithNoCreditSpendrefuses a sandbox the price list makes free (theBillablehalf of the rule is missing)MeteredSuite/TestASandboxRecordedNowhereIsRefusedWithNoCreditSandboxeswith a gate and no recorder admits, or panics on, a zero-credit ownerMeteredSuite/TestASandboxInTheOwnersOwnDaytonaOrganizationIsRefusedWhileTheyAreSuspendedMeteredSuite/TestARunRefusedForMoneyStopsTheRunningSandboxAtOnceUntilItsOrganizationMayPayAgainMeteredSuite/TestARunningSandboxIsStoppedOnceItsOrganizationRunsOutOfCreditMeteredSuite/TestInShadowASandboxOfAnOrganizationWithNoCreditIsMadeAndCountedAsWouldRefuseMeteredSuite/TestWhileMoneyCannotBeCheckedARunningSandboxRunsOnAndNoOtherIsMadeMeteredSuite/TestASandboxWhoseSessionClosedIsStillDeletedOnceItIdlesThoughItsOrganizationIsRefusedLifecycleSuite/TestASandboxStoppedForItsOwnersMoneyGivesBackItsSlotmax_concurrentslotLifecycleSuite/TestARefusalWhileCodeRunsEndsTheRunAndStopsTheSandboxLifecycleSuite/TestARefusalWhileCodeRunsInAClosedSandboxLeavesItToBeDeletedClosegave up on stops the sandbox, so its failed delete is never tried againLifecycleSuite/TestARunGoesOnWhileItsOwnersMoneyOnlyCannotBeCheckedLifecycleSuite/TestASandboxNobodyAdmitsRunsAsBeforeAdmitstarts the watch and calls a nil hook (a panic once a run outlastsAdmitEvery)LifecycleSuite/TestARunningSandboxIsAdmittedAgainEveryMinuteUnlessToldOtherwiseAdmitEveryleft at zero, as production leaves it, re-arms the timer at once: admissions in a loopsynctest)cmd/routerTestTheSessionsSandboxesAreAdmittedByTheGatenewSandboxesbuilds its sandboxes with no gate from the router's policiespolicytest). Suspension, credit, the hard limit and shadow are set through its management API, and Daytona isdaytonatest. The daytona tests use the in-process Daytona and anAdmithook; a code run is held in a client-sideRoundTripper, sincedaytonatestanswers one request at a time and a run held there would hold the stop too. The slot test uses the real slots on Redis.metered.Sandboxes.admitreturns no hook, which is the code before the fix. The three run tests were checked against the first version ofdaytona.goon this branch withgo test -overlay, and the BYOK and free-price tests against its firstmetered/sandbox.go.go test -overlay, then the touched suite was run under-race.Spend…OwnDaytonaOrganizationIsRefusedWithNoCreditRecorder.Billabledropped (Spendrefuses whatever the prices say)TestASandboxThePricesMakeFreeIsMadeWithNoCreditTestASandboxRecordedNowhereIsRefusedWithNoCreditAdmit's error ignored (suspension)SpendignoredTestWhileMoneyCannotBeChecked…usedoes not watch the callTestARefusalWhileCodeRuns…,TestARunGoesOn…TestARefusalWhileCodeRuns…haltafter a refused callTestARefusalWhileCodeRuns…haltafter a refused call though the session closedTestARefusalWhileCodeRunsInAClosedSandbox…TestARefusalWhileCodeRuns…running=falseTestARunGoesOn…AdmitTestASandboxNobodyAdmitsRunsAsBefore(panic)AdmitEverydefaultTestARunningSandboxIsAdmittedAgainEveryMinute…(admitted at 0 s, 0 s instead of 1 min, 2 min)newSandboxesbuilds no gate (if policies != nil→if false)TestTheSessionsSandboxesAreAdmittedByTheGatenewSandboxessets a typed-nil gate (guard deleted)*policy.Enforceradmits everything; only a watch and a timer run for nothingbuildSessionspassesnilinstead ofpoliciesbuildSessionsandManager.Runwith a model that callsrun_codehaltnow has a second caller, so its mutants were re-run, all caught: withoutmeter.Stopped(TestARefusalWhileCodeRuns…, the slot test,TestARunRefusedForMoney…,TestARunningSandboxIsStoppedOnce…), withoutletGo(the slot test), withoutstoppedAt(TestARunRefusedForMoney…'s restore), without Daytona's stop (TestARefusalWhileCodeRuns…,TestARunRefusedForMoney…,TestARunningSandboxIsStoppedOnce…). The first version's mutants forstarted()and the lifecycle timer (no admission instarted,armorlapse, a lapsed sandbox taken as running, the timer admitting an orphan) were not re-run: that code is unchanged.-tags integration -race; after thegoroutine.Gochange,internal/sandbox/daytonathree times andinternal/meteredonce more):internal/meteredandinternal/sandbox/...in full, thecmd/routersandbox tests,go vet -tags integration ./..., gofmt. The new daytona tests passed 20 runs in a row under-race(the closed-session one 10), the new metered ones 5. One full run failedegress'sTestProxySuite/…IsClosedAtTheIdleTimeout/neither_readson its memory bound while other tests ran beside it;egressimports none of the changed packages, and it passed on the rerun.internal/policyis unchanged and was not rerun.internal/policy,internal/metered,internal/sandbox/daytonain full, unit tests ofrouting,policy,daytona,metered, andcmd/router -run 'Sandbox|BuildSessions', all with-race; each new test checked against its mutant (8 inpolicy, 3 inmetered, and thehalt,watched,armand wiring ones), also on a trial merge withorigin/main.archiving,archivedanddestroyinghave no test of their own.haltlogs a warning and tries again at the next admission. A refusal that cuts arevivewhile Daytona is starting the sandbox leaves it to Daytona's own idle stop.mainat8c4910e0d(git merge-tree), andgo vet -tags integration ./...passes on the merged tree. None of those commits touches the sandbox, metered, policy or routing code.git merge-treeagainst this commit):cmd/router/sandboxes_test.go,main.goand the README. It conflicts incmd/router/sandboxes.go, incustomerDaytonaKeys, which conflicts againstmainalready; this PR's change tonewSandboxesis not part of that conflict.admit_test.gouses (slotsFor,held,told,run, the suite'smeter,logs,daytona) are unchanged there, and none of its names (stallingRuns,running,unpaid) is taken. With its four test files laid over this branch, the package vets and the new tests pass.Follow-ups, not in this PR
classcondition is not matched: the sandbox's billing config carries no attributes, so such an entry still leaves the sandbox billable and refused with no credit.Fixes AI-3756
🤖 Generated with Claude Code