Repository navigation
[databricks-anthropic] Run Claude Managed Agents sessions in Databricks Sandbox, from a Databricks App or a local dispatcher - #844
Conversation
…in Databricks Sandbox New integration package (integrations/anthropic): - DatabricksSandboxDispatcher polls a Claude Managed Agents self-hosted environment's work queue (outbound HTTPS only) and DatabricksSandboxLauncher runs each session's EnvironmentWorker in its own Databricks Sandbox. - Genie One (and other Databricks managed MCP servers) served as custom tools from inside the sandbox with the sandbox credential; genie_ask_and_wait polls Genie in the sandbox. - Ephemeral (default) and resumable lifecycles, memory stores, optional UC Volume export, cleanup sweep, and a databricks-anthropic CLI (doctor, sandbox-dispatcher, sandbox-list, sandbox-cleanup). - Fixed User-Agent ClaudeManagedAgents-DatabricksSandbox/0.1.0 on connector calls, plus DATABRICKS_SDK/CLI_UPSTREAM for CLI and in-sandbox calls. - Unit tests, gated live integration tests (RUN_SANDBOX_INTEGRATION_TESTS / RUN_SANDBOX_E2E), quickstart and Genie One examples. Co-authored-by: Isaac <no-reply@databricks.com>
…p; harden the sandbox boundary - Add app/: a Databricks App (FastAPI, one instance) that long-polls a self-hosted environment and runs each session's worker in its own Databricks Sandbox as the App's service principal. Bundle with the App, secret scope and secret resources; deploy.sh; put_secrets.py; /api/status and /api/health. - The environment key never enters a sandbox: the worker runs on the work item's session token only (fails closed otherwise). No login shells in sandbox commands; the worker starts under env -i. HMAC sandbox names with tag ownership checks; idempotent launch for re-delivered items; exact worker pins and a worker hash check; https-only base URL. - Remove the local CLI, U2M login helpers and examples (the App is the supported dispatcher). - Tests: App routes and service, isolation and hardening unit tests; live tests for sandbox isolation and the deployed App. Co-authored-by: Isaac <no-reply@databricks.com>
…in-shell docstring Co-authored-by: Isaac <no-reply@databricks.com>
…er race, health recovery, kept sandboxes, hash-locked worker deps
A code review of this PR reported 10 findings plus cleanups. Each was checked against the code and on a
live workspace before changing anything.
Fixed
- (3) Stale pid after a sandbox stop/start: the pidfile persists in the home directory, and pids restart
low after a boot. Because a session's work items reuse the session id as their work id, a pid now
held by another process made the next turn look "already served", and stop could signal that
process. Now only a pid whose /proc/<pid>/cmdline runs worker.py is trusted or signalled; stale
files are removed. Verified live with a decoy process (ignored, not killed).
- (4) A new turn arriving while the previous worker finishes (export, then delete): the worker writes
a finishing marker before exporting and re-checks the replace marker right before delete/stop; the
launcher replaces a finishing worker and recreates the sandbox if it was deleted meanwhile.
- (1) /api/health stayed 503 after a crash loop even once polling recovered: it now recovers once the
current run has stayed up for 2x the max restart delay.
- (2) The hourly cleanup deleted sandboxes kept because their Volume export failed: the worker now
marks them "[export failed, kept]" in display_name (tags are immutable) and cleanup keeps them until
retention_days; unmarked leftovers still go after the 1-hour grace period.
- (5) Early worker failures were hidden (the sandbox was already deleted): a worker that fails before
attaching keeps its sandbox; the launcher reads liveness and the log tail in one call, reports the
reason, then deletes the sandbox it created. Verified live.
- (8) genie_ask_and_wait broke on non-dict payloads: they are normalised ({"text": ...} /
{"items": ...}), and an answer with nothing to poll is returned instead of a false timeout.
- (9) Only top-level packages were pinned: the worker venv now installs from hash-locked requirements
for every dependency (uv pip compile --universal --generate-hashes, --require-hashes);
scripts/lock_worker.sh regenerates them; tests check them against the pins. Cold start ~11.5 s.
- (10) env -i set unset allowlisted variables to "": now ${K+"K=$K"}.
- References to files outside this package (app.py, databricks.yml, requirements.txt) fixed; tag
parsing shared in _ops.tags_of.
Not changed, with reasons
- (6) "Skipped items re-delivered every ~2 s": reclaim_older_than_ms reclaims un-acknowledged work and
the poller acknowledges what it yields. Verified live: a skipped item was not re-delivered within
180 s. The App skips nothing. The docstring that claimed re-delivery is corrected.
- (7) "Shutdown waits for queued launches": each queued launch is an acknowledged item; cancelling it
would drop that session's turn. Waiting (bounded by the platform's termination grace) is kept and
documented.
- "Ownership checked twice": the two checks are on different paths (existing sandbox vs the
AlreadyExists race); one per launch.
- "Worker re-uploaded every launch": intentional, so the sandbox always runs the current, hash-checked
worker (~1 s).
- "Sequential sandbox commands per launch": a fair optimisation, deferred to avoid destabilising
live-tested paths.
- "UPSTREAM_ENV copies": worker.py runs in the sandbox without this package, so it carries its own
copy; a unit test asserts it matches.
Testing: 125 unit tests on Python 3.10 and 3.12 (lowest-direct and highest); ruff and ty clean; live
suite 14 passed, 1 skipped (custom image), including a fresh bootstrap from the locks, sandbox
isolation and the deployed App.
Co-authored-by: Isaac <no-reply@databricks.com>
prasadkona
left a comment
There was a problem hiding this comment.
Automated review notes from two /code-review passes (Claude Code). These come from reading the code only: nothing was run against a workspace, and the findings weren't independently verified, so please treat them as leads. Two depend on stated assumptions.
Highest priority: the agent-writable ~/.cma state (venv, pid/work_id files) and the symlink-follow in upload_text could expose the sessions token. See the comments on launcher.py:403 and _ops.py:195.
Smaller cleanups (not inline): the tag-parsing code and the UPSTREAM_ENV constants are duplicated across files, and two references point to files that don't exist: docs/design/hosted-dispatcher.md, and packages/databricks-anthropic in requirements.txt.
…ink-safe uploads, finishing-worker grace Review 5886520329 (20 inline comments). Fixed here: - Start-up check: the launcher waits for a ready marker the worker writes right before serving the session (after the credential and MCP setup) instead of a fixed 5 s sleep; an exit is reported with the log tail, the created sandbox deleted, and the item force-stopped by the dispatcher. - Secrets upload could follow a planted symlink: uploads now use a fresh mktemp file (O_EXCL); small files (secrets) are written, chmod-ed and renamed in one exec; multi-chunk appends refuse a symlink. - SIGTERM during _finish: a finishing worker being replaced gets 120 s before KILL, sees the replace marker, completes its export and keeps the sandbox. - Reuse vs idle-finish race: reuse is confirmed by a second look one poll interval later. - Recreate path: NotFound from ensure_running is handled. - healthy no longer mutates state; the run loop resets the counter and backoff. - MCP auth resolves headers in a thread (async_auth_flow), off the event loop. - Worker source and hash cached per process. Already fixed in the previous commit: stale pid, export-failed cleanup, unset env vars, replace-marker race, Genie payloads, masked early-exit error, hash-locked dependencies, dangling references. Not changed (reasons in the replies): skipped-item churn (disproved live), duplicate claim (same item, served by the attached worker), shutdown wait (cancelling drops acknowledged turns), agent-writable ~/.cma (one sandbox per session; only that session's token is reachable). Testing: 131 unit tests on Python 3.10 and 3.12 (lowest-direct and highest); ruff and ty clean; live suite 14 passed, 1 skipped; live probes for the stale-pid and start-up-failure paths. Co-authored-by: Isaac <no-reply@databricks.com>
prasadkona
left a comment
There was a problem hiding this comment.
Round 3 of automated /code-review notes (Claude Code), against 6825d86. These come from reading the code only: nothing was run against a workspace, and the findings weren't independently verified, so please treat them as leads.
| Priority | Count | What |
|---|---|---|
| P0 security | 1 | Agent-writable venv is trusted (launcher.py:550) |
| P1 turns lost / launches fail | 4 | SDK timeout retries (launcher.py:567), force-stop on temporary errors (dispatcher.py:138), bootstrap before replace marker (launcher.py:409), reuse/idle race (launcher.py:398) |
| P2 edge cases, data loss | 3 | Cleanup idle time (dispatcher.py:258), DELETING/failed states (_ops.py:126), reinstall under a live worker (launcher.py:552) |
| P3 cleanup | 2 | Duplicated MCP/token helpers (mcp.py:95), unused code (_ops.py:308) |
The two P2 items tagged 'depends on Sandbox API' assume how update_time behaves and which sandbox states exist. Worth confirming with the Sandbox API team. The venv trust gap (P0) and the reuse/idle race (P1) are still open from the previous round.
…ds, replace before bootstrap, transient retries Review 5887228151 (10 inline comments). Each was checked against the code, the installed SDK (databricks-sdk 0.159.0) and, where it depended on behaviour, a live workspace. Fixed - P1 long commands re-sent: the SDK's HTTP client times out after 60 s and retries a timed-out request by re-sending it; measured live, a 75 s command ran 5 times. Commands whose execution timeout exceeds the client's HTTP timeout now use a copy of the client with a longer one (its own config dict, since Config.copy() is shallow). After the fix the command runs once. - P1 bootstrap before the replace marker / P2 reinstall under a live worker: the previous worker is stopped (marker, TERM, grace, KILL) before memory-dir prep and the venv bootstrap. - P1 temporary errors dropped the turn: a stopped item is not re-delivered (verified live), so the dispatcher retries clearly transient launch errors twice (5 s, 15 s) before force-stopping; permanent errors still fail at once. Not changed, with reasons - P0 agent-writable venv: one sandbox per session; the agent shares the worker's Linux user (sudo, no ptrace restriction), so it can read the worker's memory anyway; the only Anthropic credential there is that session's token (queue 401, other sessions 403, other memory stores 404, verified live). - P1 reuse/idle race: the suggested handshake risks force-stopping the turn it should serve (work id == session id; the SDK stops the item on exit); the window is already narrowed. - P2 update_time: verified live that stop and start move it; resumable sandboxes are stopped and started on every use, so retention reflects last use. - P2 DELETING/failed states: not in the SDK's SandboxState; NotFound is handled. - P3 duplicated helpers / unused code: not bugs; the worker must be self-contained (equivalence-tested) and the listed helpers are used by the local dev dispatcher, public API or the live tests. Testing: 139 unit tests on Python 3.10 and 3.12 (lowest-direct and highest); ruff and ty clean; live suite 14 passed, 1 skipped; live probes for the re-send, stale-pid and start-up-failure paths. Co-authored-by: Isaac <no-reply@databricks.com>
| @@ -0,0 +1,11 @@ | |||
| #!/usr/bin/env bash | |||
| # Build the connector wheel (from the package next to app/) and point requirements.txt's wheel line at it. | |||
| # Once databricks-anthropic is on PyPI, replace that line with `databricks-anthropic[mcp]==<version>` instead. | |||
There was a problem hiding this comment.
Are there additional step we need to take to publish databricks-anthropic on PyPI, or will it be handled automatically through the ai bridge repo? I imagine there should be some wiring we need to make?
| @@ -0,0 +1,99 @@ | |||
| """Hosted dispatcher for Claude Managed Agents on Databricks Sandbox, as a Databricks App (M1, service mode). | |||
There was a problem hiding this comment.
Out of curiosity, here we use Databricks App to host the dispatcher for full integration poc - will users be able to take databricks sandbox to integrate with their own dispatcher setup hosted on other non-Databricks platforms?
There was a problem hiding this comment.
Yes. The App is a thin host around the library. DatabricksSandboxDispatcher and DatabricksSandboxLauncher run anywhere with outbound HTTPS to Anthropic and the workspace, for example a VM or Kubernetes (see "Library" in the package README). The sandboxes still run in Databricks. The host needs the environment key and a Databricks identity, such as a service principal; sandboxes act as that identity. The App adds secret-scope key storage, health and status, and user mode. Per-user identity relies on Databricks Apps on-behalf-of sign-in and Lakebase, so that part needs the App.
| @@ -0,0 +1,118 @@ | |||
| # Dispatcher App: serve Claude Managed Agents sessions from a Databricks App | |||
There was a problem hiding this comment.
nit: Should the files in this directory be homed under an examples folder, similar to this setup for OpenAI?
|
@prasadkona would it be feasible to get reviews from Anthropic folks on this PR to make sure we are integrating with the right contract? |
|
cc agentbricks oncall @shaotong-db , we are trying to introduce a new library similar to what we already have with |
… who signs in The dispatcher App gains user mode (the standard deploy). A session started in the Claude Console on the user environment gets a one-time sign-in link at its first tool call; after the user signs in on /connect and replies 'done', its sandbox is created with the user's own Databricks credential, so the sandbox, Genie One and Unity Catalog reads use their grants, capped to the App's user_api_scopes. - One watcher polls the user environment (a dispatcher with a routing launcher, app/signin.py). With a ticket left by /connect for a session bound to the same user, it launches as that user; otherwise it answers the pending tool calls with the link (posted with the work item's session token) and releases the item. - /connect shows the session, agent and signed-in user and asks for confirmation. Codes are random, stored as SHA-256 hashes, valid 15 minutes and single-use (an insert into connect_uses). A session bound to another user is never taken over; other environments, agents not allowed, memory stores and vaults are refused. - State in Lakebase (schema cma_dispatcher, owned by the App's service principal): bindings, codes and an insert-only audit trail. The store never updates or deletes. - User tokens stay in App memory (tickets expire before the token, at most 30 minutes) and are never logged, stored or returned. - Bundle: the base App is service mode; targets dev/prod add the user-mode secrets, Lakebase and settings; dev-service/prod-service are service-only. deploy.sh --store-secrets stores the user-mode secrets for user-mode targets. - Service mode (sessions as the App's service principal) is unchanged, for automation and shared agents. Co-authored-by: Isaac <no-reply@databricks.com>
… them acknowledged The poller acknowledges every item it yields, and an acknowledged item that is not stopped stays stranded until its lease expires. The dispatcher now force-stops any item it can't serve (non-session types). The SDK only defines session work today, so this is defensive. Covered in the dispatcher unit test. Co-authored-by: Isaac <no-reply@databricks.com>
…igned-in user); service mode for automation Co-authored-by: Isaac <no-reply@databricks.com>
…t/doctor/run/list/cleanup A second supported way to run the dispatcher: on a developer laptop or a self-managed VM, as the developer's Databricks CLI login. Sessions started from the Claude Console or the Anthropic SDK on that environment run in a Databricks Sandbox with the developer's own access. - Databricks CLI profiles only (databricks auth login). Every command requires --profile; nothing falls back to DEFAULT or DATABRICKS_CONFIG_PROFILE. - init saves ~/.config/databricks-anthropic/<name>.toml (0700 directory) and a <name>.secrets file created O_EXCL 0600: the environment key (hidden prompt), a sandbox-name HMAC key generated once, and an optional API key. - run: a per-environment lock; refuses when another worker already polls the environment (re-checked after 35 s, since a stopped worker counts for ~30 s; --force overrides); prints whose identity the sessions run as; SIGINT/SIGTERM finish claimed launches before exiting. - HMAC sandbox names with the cmalocal- prefix; cleanup only touches this dispatcher's sandboxes. Uses the same launcher and worker as the App. - doctor checks the login, Sandbox API, environment, queue, lock and file modes. - 115 offline CLI tests, including a canary scan that no key ever reaches the output. Co-authored-by: Isaac <no-reply@databricks.com>
The CLI runs tools one way, in a sandbox created through the Sandbox API with the worker inside it (the same launcher as the App). The unimplemented 'mcp' option and its 'not available yet' path are removed; a config file that still names a backend loads unchanged. Co-authored-by: Isaac <no-reply@databricks.com>
Each Databricks identity gets its own managed memory store (/api/2.0/agents/memory-stores), served inside its sandbox as memory_search, memory_list, memory_save and memory_delete with the sandbox credential. - The store id is an HMAC of the identity's immutable user id (cma-memory-...). The worker creates the store if missing, so that identity owns it, and refuses a store owned by anyone else. The store and actor_id (databricks-user:<id>) are fixed by the launcher; the tools take only paths, content, descriptions and queries. - sandbox/memory.py: MemoryConfig, memory_store_id, memory_custom_tools() for the agent's tool declarations. DatabricksSandboxLauncher(memory=...). - Local dispatcher: run --memory (recommended), memory show, memory delete --yes. - App user mode: user_memory bundle variable, off by default. The memory API requires the agent-kit OAuth scope, which Databricks Apps doesn't accept in user_api_scopes yet, so user-mode memory waits for that. With it on, the App checks the API at start-up and reports user_memory in /api/status. - deploy.sh: a failed bundle deploy grants the App's READ on its secret scope again (the bundle rewrites the scope ACL before the App update). - Anthropic memory stores stay refused in user mode. Co-authored-by: Isaac <no-reply@databricks.com>
00b105d to
73b19e0
Compare
…iron
_useragent.apply() (run at import) only sets the SDK's global product; CLI
subprocesses still get DATABRICKS_{SDK,CLI}_UPSTREAM* through
subprocess_env(), and the in-sandbox worker sets them for the agent's calls.
Tests cover that import leaves os.environ unchanged and that the new memory
calls (worker, App start-up check, CLI) send the connector as the product.
App README: "Anthropic memory stores".
Co-authored-by: Isaac <no-reply@databricks.com>
| await asyncio.to_thread( | ||
| user.store.bind, | ||
| Binding( | ||
| session_id, caller.principal_id, caller.user_name, session_agent_id(session) |
There was a problem hiding this comment.
A session on the user environment ends up running as whoever signs in and connects it, taken from their login here - not necessarily the person who started the session. It means who can start sessions on this environment is what matters. Worth one line in the operator docs so that stays intentional:
"Sessions on the user environment run with the Databricks access of whoever signs in to connect them. Anyone who can start a session on this environment can ask another user to connect it. Keep this environment's membership limited to trusted users."
There was a problem hiding this comment.
Added, nearly verbatim, to the App README's identity section and the user-mode docs. It's also why the README recommends a dedicated Anthropic workspace for the user environment.
| number answered. A turn that ends without a tool call needs nothing.""" | ||
| deadline = self._clock() + self._item_max_s | ||
| answered: set[str] = set() | ||
| while True: |
There was a problem hiding this comment.
When a session is waiting for someone to sign in, the app keeps checking that session for up to 5 minutes, using the same limited set of worker slots (8 by default) it uses to actually start sandboxes. Usually each check finishes in seconds, but if several sessions are waiting at once they can tie up those slots and delay real sandbox launches on this environment. Worth giving the sign-in waiting its own slots, or a shorter time limit, so it can't crowd out real launches.
There was a problem hiding this comment.
Fixed: sign-in-link handling now runs on its own pool (4 threads, separate from the 8 launch slots), and its wait is capped at 120 s, so waiting sessions can't delay real launches.
| raise _ops.SandboxCommandError( | ||
| f"worker exited during start-up in {name}:\n{log_tail}" | ||
| ) | ||
| if time.monotonic() > deadline: |
There was a problem hiding this comment.
If a sandbox's worker takes longer than the start timeout to come up, the code stops waiting but still reports the launch as a success. Claude was already told the work was picked up, so if that worker is actually stuck (not just slow), the user's request silently never gets answered and nothing in the status page shows a problem. It's fine to leave a slow worker running - this case just shouldn't look identical to a normal success. A separate counter or an error note would make it visible.
There was a problem hiding this comment.
Fixed: that case now returns ready=False, counts as slow_starts in /api/status, and sets last_error=WorkerNotReady. The slow worker is still left running.
| now = self._clock() | ||
| with self._lock: | ||
| hit = self._cache.get(key) | ||
| if hit and hit[0] > now: |
There was a problem hiding this comment.
The app remembers which user a login token belongs to for 60 seconds and skips re-checking with Databricks during that time, so for up to a minute after a token is revoked it can still be used to connect a session. Impact is small - it only connects a session to that user's own account, and a revoked token can't actually start a sandbox - so this is a cleanup, not a security hole. Re-checking on the connect step, or shortening that 60 seconds, would close it.
There was a problem hiding this comment.
Fixed: the confirm step (POST /api/connect) always re-checks the token with Databricks. The cache is only used to show the page.
| ) | ||
| ) | ||
|
|
||
| def add_code(self, code_hash: str, session_id: str, ttl_s: float) -> None: |
There was a problem hiding this comment.
Expired sign-in codes are never deleted - the code only ignores them by checking the expiry time, so old rows keep piling up (same for the used-codes table). Keeping the full audit history is intentional, but expired sign-in codes are just dead weight. A periodic cleanup of expired codes would help.
There was a problem hiding this comment.
Fixed: an hourly sweep deletes sign-in codes (and their use rows) a day after they expire. Bindings and the audit trail stay append-only, and the SQL test now allows only those two deletes.
| if getattr(result, "reused", False): | ||
| status.reused += 1 | ||
| else: | ||
| status.launched += 1 |
There was a problem hiding this comment.
On the user-mode watcher this counts every item as "launched," including the cases where no sandbox was started and the app just sent back a sign-in link. So the "launched" number reads higher than the number of sandboxes actually started, which also makes it a weaker signal for spotting the stuck-worker case above. A separate count for "sign-in link sent" would keep "launched" meaning what it says.
There was a problem hiding this comment.
Fixed: link-only items count as deferred, so launched is sandboxes actually started. With slow_starts, a stuck start now stands out.
| minutes = int(CODE_TTL_S // 60) | ||
| message = ( | ||
| "Databricks sign-in needed. Ask the user to open this link, sign in, confirm, and then reply " | ||
| f"'done': {self.app_url}/connect?code={code} . The link works once and expires in {minutes} " |
There was a problem hiding this comment.
The sign-in code is part of the link's web address (and the first page load passes it in the address too; the final confirm step correctly sends it in the request body). The page clears it from browser history, but the app can't stop the Databricks Apps proxy in front of it from logging the address, code included. The harm is limited - a stolen code only lets the thief connect a not-yet-connected session to their own account, and it expires in 15 minutes and works once - so this is mostly a heads-up, flagging so that putting the code in the address is a deliberate choice.
There was a problem hiding this comment.
Thanks, I tried moving it to the URL fragment, but the Databricks Apps sign-in redirect drops fragments, so a first-time sign-in lost the code (verified live). So the code stays in the query by design: it works once, for 15 minutes, and only binds a not-yet-connected session to whoever opens it. The page clears it from the address bar and history, and the lookup and confirm now both send it in the request body (POST /api/connect/info), so no other URL carries it. Also fixed along the way: codes are now letters and digits only, because link auto-detection dropped a trailing _.
| cfg = w.config.copy() # shares the credential provider; keeps the User-Agent info | ||
| # Config.copy() is shallow: attribute values live in a shared dict, so setting the timeout on the | ||
| # copy would change the caller's config too. Give the copy its own. | ||
| if isinstance(getattr(cfg, "_inner", None), dict): |
There was a problem hiding this comment.
To give long commands a longer network timeout, this copies the client's config and reaches into an internal SDK field (_inner). There's a check that the field is a dictionary first, which is good - but if a future SDK version renames that field, the check quietly passes over it and the timeout change ends up modifying the shared config instead, lengthening the timeout on the caller's own client with no error. Worth failing loudly if that field isn't there, or a comment noting the assumption, so an SDK change can't silently do the wrong thing.
There was a problem hiding this comment.
Fixed: it now raises if Config._inner isn't a dict, with a comment on the assumption. A test checks that the caller's config is untouched.
| from databricks.sdk import useragent | ||
|
|
||
| PRODUCT_NAME = "ClaudeManagedAgents-DatabricksSandbox" | ||
| PRODUCT_VERSION = "0.1.0" |
There was a problem hiding this comment.
PRODUCT_VERSION is hardcoded to 0.1.0 here and copied again in worker.py, so after the next release the reported version won't match the real package version until someone bumps both by hand. The other integrations in this repo read their version from the installed package automatically, so they stay correct on their own. Suggestion: in _useragent.py, read it from the installed package (importlib.metadata.version("databricks-anthropic"), falling back to "unknown"); the worker can't do that itself since it runs without this package installed, so have the launcher pass the version into the worker through the environment alongside the other vars it already sets. One source of truth, nothing to hand-edit each release.
There was a problem hiding this comment.
Fixed, with one source of truth. _useragent reads the installed version (converted to semver, since the SDK requires it), the launcher passes it to the worker as CMA_PRODUCT_VERSION, and deploy.sh and the bundle read it from pyproject.toml. Nothing to hand-edit per release.
…ion, SDK assumption - Sign-in-link answers run on their own pool (4 threads), off the launch slots; the wait is capped at 120 s. - The sign-in code travels in the URL fragment (/connect#code=...); the lookup is POST /api/connect/info with the code in the body. - POST /api/connect always re-checks the user's token (no cached identity). - An hourly sweep deletes sign-in codes and their use rows a day after expiry; bindings and the audit trail stay append-only. - Status: launched counts sandboxes started; deferred counts items answered without one; slow_starts counts workers not ready after start_timeout_s (ready=False on LaunchResult; still left running). - The long-timeout client copy raises if Config._inner is missing. - The connector version is read from the installed package (as semver) and passed to the worker (CMA_PRODUCT_VERSION); deploy.sh and the bundle derive it from pyproject.toml. - App README: who supplies a user-mode session's identity. Co-authored-by: Isaac <no-reply@databricks.com>
…agments); alphanumeric codes The Databricks Apps sign-in redirect drops URL fragments, so a #code= link lost its code on a first sign-in (verified live). The code stays in the query by design; the page clears it from the address bar and history, and every API call (POST /api/connect/info, POST /api/connect) sends it in the body. Codes are 32 letters and digits, since link auto-detection drops a trailing "_". Co-authored-by: Isaac <no-reply@databricks.com>
…en (revocation note) Co-authored-by: Isaac <no-reply@databricks.com>
| self._session_client_for = session_client_for or self._session_client | ||
| self._clock, self._sleep = clock, sleep | ||
| self._item_max_s, self._poll_s = item_max_s, poll_s | ||
| self._links = link_executor or ThreadPoolExecutor( |
There was a problem hiding this comment.
Small thing, not blocking: this pool has the default unbounded work queue, so under a sustained flood of unbound sessions the submitted answers would pile up in memory behind the 4 workers rather than push back. In practice each answer finishes in seconds and an unserved item releases on its lease, and freeing the dispatcher's launch slots (the point of this change) still holds - so this is fine as is. Flagging only in case you'd rather cap it (a bounded queue, or skip answering when it's full) so a burst can't grow memory unbounded.
There was a problem hiding this comment.
Thanks. Agreed it's unbounded. I'll leave it as is for now: an entry is just the claimed work item, each answer takes seconds, and only members of the user environment's Anthropic workspace can create sessions (the docs say to keep that to trusted users). A cap would mean skipping the answer, which leaves the user's tool call hanging instead of showing a link. Happy to add one (for example, release past 64 queued) if you'd prefer.
| @@ -0,0 +1,412 @@ | |||
| """Thin helpers over the released ``databricks-sdk`` sandbox APIs. | |||
|
|
|||
| Everything here uses sandbox CRUD plus ``execute_command_sync``. Facts these rely on | |||
There was a problem hiding this comment.
Everything here uses sandbox CRUD plus
execute_command_sync
Is there anywhere that would be better suited for the streaming execute_command method? e.g. for streaming certain exec input/output to/from sandboxes. Or does Claude Managed Agent not care about streaming things from sandbox at all?
There was a problem hiding this comment.
Good question. Managed Agents doesn't need it here: the Claude worker runs inside the sandbox and streams tool calls and results to Anthropic over its own outbound connection, so no tool I/O goes through the exec API. Our exec calls are control plane only (venv bootstrap, starting the worker detached, readiness and liveness checks, small uploads, cleanup, and a /bin/true keep-alive heartbeat), and each needs just its final result. The longest is the first venv install, which already uses a longer HTTP timeout. Also, the SDK we pin (0.159.0) only has execute_command_sync. Streaming would be nice for live-tailing the worker log while debugging; I'll keep it in mind if the streaming method lands in the SDK.
HsingTang
left a comment
There was a problem hiding this comment.
LGTM overall, left some minor comments
|
Small packaging cleanup before publishing: Automated comment on Ivan's behalf; checked at |
What did you change, and why?
Why: Claude Managed Agents can run a session's tools on infrastructure the customer controls ("self-hosted environments"). Anthropic keeps the agent loop and puts each session's work on a queue; something in the customer's environment has to claim the work and run the tools. There is no Databricks option today. This adds one: each session's tools run in their own Databricks Sandbox in the customer's workspace, served by a dispatcher that runs in one of two ways:
databricks-anthropic runon a developer laptop or a self-managed VMBoth use the same library, launcher and in-sandbox worker, and both only need outbound HTTPS.
Pattern A, the user journey (user mode, the standard deploy):
/connect). No sandbox has started yet.user_api_scopes.The same App also serves a service environment whose sessions run as the App's service principal, for automation and shared agents.
Pattern B, the developer journey:
databricks auth login --host https://<your-workspace-url>once, and name the profile.databricks-anthropic init --profile <name> --environment env_...saves the settings and prompts for the environment key (hidden).databricks-anthropic doctorchecks every prerequisite.databricks-anthropic runserves the environment until Ctrl-C. Sessions started on it from the Claude Console, or from code through the Anthropic SDK, run in a Databricks Sandbox with the developer's own access.Change: New package
databricks-anthropicinintegrations/anthropic:app/: the dispatcher App (FastAPI, one instance, outbound HTTPS only, no inbound endpoint):service.py) long-polls the service environment and starts each session's worker in its sandbox as the App's service principal.user_mode.py,signin.py,user_store.py,static/):/connectis waiting for the session (the signed-in user's client, in memory only) and the session is bound to that same user, it launches the sandbox with the user's client. Otherwise it answers the session's pending tool calls with the sign-in link and releases the item. The link is posted with the work item's own session token, the only credential Anthropic accepts for tool results./connectshows the session, agent and signed-in user, andPOST /api/connectbinds the session to the user's immutable Databricks id and leaves the ticket.cma_dispatcher, created and owned by the App's service principal): session bindings and an append-only audit trail, plus sign-in codes, which an hourly sweep deletes a day after they expire.dev/proddeploy user mode (user-mode secrets, Lakebase resource and settings added through a shared overlay);dev-service/prod-servicedeploy service mode only, with no Lakebase or API key. Secrets are App secret resources in a secret scope pinned to one manager.scripts/deploy.shbuilds the package wheel, deploys the bundle, stores the secrets (never printed) and starts the App. If a bundle deploy fails after the scope ACL was rewritten, it grants the App's READ on the scope again./api/statusand/api/healthreport the poll loops.src/databricks_anthropic/cli/: thedatabricks-anthropiccommand (pattern B;init,doctor,run,list,cleanup,memory):databricks auth login). Every command requires--profile; nothing falls back toDEFAULTorDATABRICKS_CONFIG_PROFILE.~/.config/databricks-anthropic/<name>.toml(directory0700) and<name>.secrets, createdO_EXCLwith mode0600: the environment key (hidden prompt), a sandbox-name HMAC key generated once and never regenerated, and an optional API key. Keys never reach the output.--forceoverrides).runprints whose identity the sessions run as.cmalocal-prefix;listandcleanuponly touch this dispatcher's sandboxes.src/databricks_anthropic), which both patterns run:DatabricksSandboxDispatcherpolls a queue, with a bounded launch pool, transient-error retries, status counters and cleanup.launchedcounts sandboxes started,deferreditems answered without one (the user-mode sign-in link), andslow_startsworkers still not ready after the start timeout (LaunchResult.ready=False; left running).DatabricksSandboxLaunchercreates or reuses the session's sandbox, builds the worker'suvvenv from hash-locked requirements, and starts Anthropic'sEnvironmentWorkerinside it (sandbox/worker.py).alist_mcp_custom_tools,genie_ask_and_wait), so no Databricks token goes to Anthropic.sandbox/memory.py; Beta "Agent Memory Sessions"):memory_search,memory_list,memory_saveandmemory_deleteinside the sandbox with the sandbox's credential. Agents declare them withmemory_custom_tools().actor_iddoesn't restrict access). The store id iscma-memory-plus an HMAC of the identity's immutable user id. The worker creates the store if it's missing, so that identity owns it, and refuses a store owned by anyone else.actor_id(databricks-user:<id>); the tools take only paths (no..), content (up to 16,000 characters), descriptions and queries. A failed call is a tool error, never a crash.databricks-anthropic run --memory(recommended);memory showandmemory delete --yes.user_memorybundle variable, off by default. The memory API requires the OAuth scopeagent-kit, and Databricks Apps doesn't accept it inuser_api_scopesyet (400 not a valid scope), so user-mode memory waits for that; it then needs onlyagent-kitadded to the user-mode scopes. Withuser_memory=1, the App checks the memory API at start-up, serves without memory if it's unavailable, and reportsuser_memoryin/api/status./connectpage; the confirm step always re-checks the token with Databricks.connect_uses). The code is in the link's query, because the Databricks Apps sign-in redirect drops URL fragments; the page clears it from the address bar, and the lookup and confirm (POST /api/connect/info,POST /api/connect) send it in the body. Bindings and the audit trail are append-only; the only deletes purge expired sign-in codes.user_agents, and sessions with Anthropic memory stores or vaults.POST /api/connectand/api/connect/infoneedX-CMA-Request: 1and a same-hostOrigin, and rejects unknown fields; the page has a strict CSP and writes text only withtextContent.user_api_scopes(verified: clusters and jobs are refused from inside).0600file the worker reads and deletes before any tool runs. The launcher refuses to launch if an environment key would reach the sandbox.bash --noprofile --norc), and the worker starts underenv -iwith an allowlist.ephemeral(the App's default; user sandboxes always): when the session goes idle,outputs/is optionally exported to a UC Volume and the sandbox is deleted.resumableis a library option. Cleanup only touches sandboxes with this deployment's prefix and tags.Dependencies:
databricks-sdk[sandbox]>=0.157.0(the first release withSandboxMetadata),anthropic>=2.3,<3,brotli>=1.2andprotobuf>=4.25.8,<8, plustomlion Python 3.10 (the CLI's config). The package now has adatabricks-anthropicconsole script. Optional extramcp:mcp>=1.24; both mcp 1.x (httpx) and 2.x (httpx2) are supported. The App'srequirements.txtaddspsycopg[binary]for Lakebase. Thetestsgroup addsfastapifor the App'sTestClienttests.app/is not part of the wheel.How do you know it works?
Testing:
tests/unit_tests, 359 cases, no network calls) cover:actor_id, API errors as tool errors, the declarations matching the served tools, the launcher's worker environment, user mode passing the bound user's id, the start-up check, andrun --memory/memory show/memory delete;O_EXCL,0600/0700), the HMAC key never regenerated, a profile never picked implicitly (including withDATABRICKS_CONFIG_PROFILEset) and non-CLI profiles refused, noos.environchanges, the lock blocking a second instance, the double-serving check (proceed, wait and proceed, refuse,--force, read errors), SIGTERM/SIGINT handling, aliases,doctor, and a canary scan that no key reaches stdout, stderr or logs;env -iworker start; HMAC sandbox names, the tag ownership check and theAlreadyExistsrace; idempotent launch and the readiness signal; hash-locked worker requirements and the worker hash check; launch retries for transient errors; dispatcher filtering, counters and failed-item stop; cleanup ownership and retention; export; the Genie wait tool; and an import contract for theanthropic.lib.*modules the worker uses.ruff check,ruff format --checkandty checkare clean.tests/integration_tests, gated onRUN_SANDBOX_INTEGRATION_TESTS; end-to-end cases also needRUN_SANDBOX_E2Eand Anthropic credentials) run real sessions on Claude Haiku with a $1 per-session cap: prerequisites, bash, Genie One from inside the sandbox, resume, memory stores, cleanup, UC Volume export, sandbox isolation (with the in-sandbox session token the work queue returns 401, other sessions 403 and unattached memory stores 404; the environment key is absent from every process environment, the home directory and/tmp; planted shell start-up files have no effect), and the deployed App serving a service-mode session. Result: 14 passed; the custom-image case is skipped (it needs an Artifact Registry image).databricks current-user mereturned the signing-in user, and Genie One answered with their grants.signin-link,connectandlaunch.init,doctorandrunagainst a personal environment; an API-created session was answered in about 17 s, anddatabricks current-user mein the sandbox returned the developer.runwas refused by the lock, and a second dispatcher on the same environment was refused after the 35 s re-check.cleanupremoved only that dispatcher's sandboxes.memory_saveinto a store created and owned by the developer, under theiractor_id; session 2, a new session in a new sandbox, found it withmemory_searchand answered with it. Store, sandboxes and agent were removed afterwards.--scopesshow the memory API returns 403required scopes: agent-kitfor the App's user scopes (also withmodel-serving,postgresorappsadded) and 200 withagent-kit; the Apps API rejectsagent-kitinuser_api_scopes.Notes for reviewers
integrations/anthropic/. CI,tyand release wiring are left to maintainers; the job I used locally mirrorsopenai_test(uv run --resolution ${{ matrix.uv-resolution }} --exact --group tests pytest tests/unit_testsinintegrations/anthropic).databricks-anthropicconsole script is the entry point; let me know if you'd prefer it shipped differently.agent-kitscope inuser_api_scopes; the code is in and off by default.ClaudeManagedAgents-DatabricksSandbox/<version>as the SDK product (the version is read from the installed package, as semver, and passed to the in-sandbox worker asCMA_PRODUCT_VERSION;deploy.shreads it frompyproject.toml), including the new memory calls (worker, App start-up check, CLI); tests capture the headers. Importing the package sets only the SDK's product and never changesos.environ; CLI subprocesses get the upstream variables throughsubprocess_env().anthropic.lib.environments.EnvironmentWorker,anthropic.lib.tools.mcp.async_mcp_toolandanthropic.lib.tools.agent_toolset. They are capped at<3and covered by an import contract test.Apache-2.0, README "MIT License" link.Additional references
DatabricksSandbox), [databricks-openai] Add Databricks sandbox backend for OpenAI Agents SDK #774 (databricks-openaiDatabricksSandboxClient)This pull request and its description were written by Isaac.