WeKnora/internal/database
Leo Dawn 56d075e213
fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it (#3471)
* fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it

tenant_sandbox_configs is keyed by (tenant_id, id), so a config id is not an
address on its own. sessions.sandbox_config_id stored only the id and every
reader took the workspace from the ambient request context.

That holds inside a chat turn, which already runs under the agent's workspace
(WithExecutionTenant in the QA handler). It breaks for a shared agent
everywhere else, because a shared agent runs on ITS OWNER's sandbox config
while the session belongs to the borrower, and these paths run from plain
requests whose only tenant is the session owner's:

  * DeleteSession resolved nothing and returned after a warning. Cube and E2B
    create session sandboxes with onTimeout=pause, so the MicroVM was not
    reclaimed later either: it stayed paused, billing, with nobody holding its
    id. ReapOrphanSandboxes has no production caller, so nothing recovered it.
  * The terminal and desktop panels failed on both branches - attaching to the
    pinned sandbox and provisioning a new one - with ErrSandboxConfigNotFound,
    which terminalErrorFrame maps to a bare INTERNAL close reason. The panel is
    offered unconditionally and already forwards agent_source_tenant_id, so
    this was a dead end the user could reach in one click.
  * Fork read the pin through PinnedSessionSandbox, got no manager, and
    silently degraded to SNAPSHOT_UNSUPPORTED, losing the sandbox state.
  * The fork snapshot lease recorded the session's workspace next to the
    lending workspace's config id, so the reaper could not resolve it either.

Record the owning workspace beside the pin and make the pair travel together
as SandboxPin. Readers now take the workspace from the pin and fall back to the
session's own, which is what every non-borrowed pin (and every row written
before this column) resolves to - so behaviour for own agents is unchanged.

The provision path has no pin yet, so the WebSocket handler passes the agent's
workspace along with its config: terminalProvisionPin already resolved the
shared agent, it just discarded the tenant resolveAgent handed back.

Backfill in the migration is limited to sessions whose pinned config does not
exist in their own workspace - the only ones that can have borrowed it - using
the lending workspace recorded on their newest shared-agent message. Lite has
no shared spaces, so the SQLite mirror adds the column without a backfill.

* fix(sandbox): backfill the pin owner from the config row and self-heal legacy pins

Three gaps in the session sandbox pin owner:

Backfilling from messages.agent_tenant_id names the wrong workspace. The
pin is sticky to the session's FIRST sandbox, while the newest message
carrying agent_tenant_id may belong to a later shared agent from another
workspace. Writing that tenant leaves teardown resolving a config the
workspace does not own - the very failure the column exists to fix.
tenant_sandbox_configs.id is a global UUID primary key, so joining the
config row itself names the workspace that actually owns the pin.

The column was INTEGER while every other tenant id is BIGINT/uint64.
Postgres INTEGER is 32-bit signed, so a large tenant id would not fit.

Rows the SQL backfill cannot reach keep sandbox_config_tenant_id = 0
forever: the reader falls back to the caller's workspace but never
records what it learned. The next chat turn already runs under the
workspace that can resolve the config, so persisting it there is what
lets a later DELETE, panel open or fork find the sandbox. recordOwner
only writes when the lookup actually succeeded and the stored owner is
still unset - stamping the caller's tenant onto a failed lookup would
brand a sticky pin left by a previous shared agent with the wrong
workspace.

Also renames the lentSandboxConfg typo and corrects the fork degrade
reason in a comment: a lent config that resolves to nil fails
BoundSandboxID, so the fork degrades to SANDBOX_GONE, not
SNAPSHOT_UNSUPPORTED.

* fix(sandbox): require a named backend before recording a pin's owner

The self-heal wants to persist an owner "that actually resolved this config",
but a nil error does not prove that. resolveTenantSandboxForConfig returns a
disabled manager with no error twice before it ever reads the config row: for
the workspace kill switch, and for an empty or deployment-default config id.

That reopens the leak this column exists to close. The SQL backfill correctly
leaves sandbox_config_tenant_id at 0 whenever the pinned config belongs to the
session's own workspace, which is most existing rows. One turn of a shared
agent lent by a workspace whose admin has script execution turned off then
short-circuits on the kill switch, returns nil, and stamps that lending
workspace onto a config it does not own. The next DELETE resolves the pin there,
finds nothing, and strands the paused MicroVM.

The pin branch runs before agentConfigID is read, so the shared agent does not
even need a sandbox config of its own to trigger it.

A named backend (Cube/E2B/Docker) is the proof, and it is the same condition
that is already allowed to CREATE a pin further down: what may write a pin may
update whose it is. A config that exists but resolves to type "disabled" is
skipped as well - ownership is genuine there, but such a config never creates a
sandbox, so no teardown can go missing.

The deployment-default pin was inert either way (both workspaces short-circuit
to a manager with no DestroySession), but it is covered too so a later
relaxation of the proof cannot quietly reopen the kill-switch case.

Both tests fail without the guard.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-21 15:38:39 +08:00
..
im_transport_migration_test.go fix: align client sessions and integration request handling (#3305) 2026-09-16 16:20:57 +08:00
migration.go feat(system-info): surface DB migration errors with troubleshooting links 2026-05-14 16:34:50 +08:00
migration_postgres_test.go feat(agent): size agent history by the window and calibrate token estimates (#3413) 2026-09-18 22:51:31 +08:00
migration_sqlite_message_artifacts_test.go feat(artifacts): artifacts library page backed by a message_artifacts table (#3384) 2026-09-18 12:10:19 +08:00
migration_sqlite_test.go fix(knowledge): address auto-tag review findings 2026-08-07 15:01:01 +08:00
migration_sqlite_versioned_schema_test.go fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it (#3471) 2026-09-21 15:38:39 +08:00
migration_versions_test.go fix(migrations): renumber the context checkpoint migration to 000105 2026-09-18 21:26:26 +08:00