Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

feat(templates): configure minimum free disk (#1845)

gm-e2bf842aa8dacb1
diff --git a/.changeset/grumpy-icons-roll.md b/.changeset/grumpy-icons-roll.md
new file mode 100644
index 000000000..18e7dbbae
--- /dev/null
+++ b/.changeset/grumpy-icons-roll.md
@@ -0,0 +1,7 @@
+---
+'@e2b/python-sdk': minor
+'e2b': minor
+'@e2b/cli': minor
+---
+
+Expose a configurable minimum free-disk target with `minFreeDiskMb` in JavaScript, `min_free_disk_mb` in Python, and `--min-free-disk-mb` in `template create`. Omission uses the team default, while explicit zero requests no minimum growth. Growth is best effort and never shrinks an existing filesystem.
diff --git a/packages/cli/src/commands/template/create.ts b/packages/cli/src/commands/template/create.ts
index ab8b35121..67f9eb43c 100644
--- a/packages/cli/src/commands/template/create.ts
+++ b/packages/cli/src/commands/template/create.ts
@@ -6,7 +6,7 @@ import {
defaultDockerfileName,
fallbackDockerfileName,
} from 'src/docker/constants'
-import { parsePositiveInt, pathOption } from 'src/options'
+import { minFreeDiskMbOption, parsePositiveInt, pathOption } from 'src/options'
import { validateTemplateName } from 'src/utils/templateName'
import { getRoot } from 'src/utils/filesystem'
import {
@@ -53,6 +53,7 @@ export const createCommand = new commander.Command('create')
'specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 1024.',
parsePositiveInt('Memory in megabytes')
)
+ .addOption(minFreeDiskMbOption)
.option('--no-cache', 'skip cache when building the template.')
.alias('ct')
.action(
@@ -65,6 +66,7 @@ export const createCommand = new commander.Command('create')
readyCmd?: string
cpuCount?: number
memoryMb?: number
+ minFreeDiskMb?: number
noCache?: boolean
}
) => {
@@ -101,6 +103,7 @@ export const createCommand = new commander.Command('create')
const readyCmd = opts.readyCmd
const cpuCount = opts.cpuCount
const memoryMB = opts.memoryMb
+ const minFreeDiskMb = opts.minFreeDiskMb
// Get Dockerfile content
const { dockerfileContent, dockerfileRelativePath } = getDockerfile(
@@ -142,6 +145,7 @@ export const createCommand = new commander.Command('create')
alias: templateName,
cpuCount: cpuCount,
memoryMB: memoryMB,
+ minFreeDiskMb,
skipCache: opts.noCache,
apiKey: apiKey,
domain: domain,
diff --git a/packages/cli/src/options.ts b/packages/cli/src/options.ts
index b29fcaab6..17ca696f4 100644
--- a/packages/cli/src/options.ts
+++ b/packages/cli/src/options.ts
@@ -18,6 +18,27 @@ export function parsePositiveInt(label: string): (value: string) => number {
}
}
+/**
+ * Parse a CLI option as a non-negative integer.
+ */
+export function parseNonNegativeInt(label: string): (value: string) => number {
+ return (value) => {
+ if (value.trim() === '') {
+ throw new commander.InvalidArgumentError(
+ `${label} must be a non-negative integer. You provided ${asLocal(value)}.`
+ )
+ }
+
+ const parsed = Number(value)
+ if (!Number.isInteger(parsed) || parsed < 0) {
+ throw new commander.InvalidArgumentError(
+ `${label} must be a non-negative integer. You provided ${asLocal(value)}.`
+ )
+ }
+ return parsed
+ }
+}
+
export const pathOption = new commander.Option(
'-p, --path <path>',
`change root directory where command is executed to ${asBold(
@@ -88,3 +109,8 @@ export function projectIdFromOptions(opts: {
}
return opts.project ?? opts.team
}
+
+export const minFreeDiskMbOption = new commander.Option(
+ '--min-free-disk-mb <min-free-disk-mb>',
+ 'requested minimum free space after build steps, in MiB. Omit for the team default or use 0 for no minimum growth. Growth is best effort and never shrinks the filesystem.'
+).argParser(parseNonNegativeInt('Minimum free disk in MiB'))
diff --git a/packages/cli/tests/commands/template/create.test.ts b/packages/cli/tests/commands/template/create.test.ts
index 926720e54..1332a80f9 100644
--- a/packages/cli/tests/commands/template/create.test.ts
+++ b/packages/cli/tests/commands/template/create.test.ts
@@ -10,6 +10,27 @@ const domain = process.env.E2B_DOMAIN || 'e2b.app'
const cliPath = path.join(process.cwd(), 'dist', 'index.js')
const templateName = `cli-create-api-key-test-${Date.now()}`
+test('rejects the retired disk flag without a stack trace', () => {
+ const result = spawnSync(
+ 'node',
+ [
+ cliPath,
+ 'template',
+ 'create',
+ 'retired-disk-flag-test',
+ '--min-free-disk-mb',
+ '0',
+ '--free-disk-space-mb',
+ '1024',
+ ],
+ { encoding: 'utf8', timeout: 10_000 }
+ )
+
+ expect(result.status).toBe(1)
+ expect(result.stderr).toContain("unknown option '--free-disk-space-mb'")
+ expect(result.stderr).not.toMatch(/InvalidArgumentError|\n\s+at /)
+})
+
describe('template create cli backend integration', () => {
let testDir: string
diff --git a/packages/cli/tests/options.test.ts b/packages/cli/tests/options.test.ts
new file mode 100644
index 000000000..c1ad8afa3
--- /dev/null
+++ b/packages/cli/tests/options.test.ts
@@ -0,0 +1,27 @@
+import { Command } from 'commander'
+import { describe, expect, test } from 'vitest'
+
+import { parseNonNegativeInt, minFreeDiskMbOption } from '../src/options'
+
+describe('minimum free disk options', () => {
+ test.each(['', ' ', '-1', '1.5', 'abc'])(
+ 'rejects malformed value %j',
+ (value: string) => {
+ expect(() => parseNonNegativeInt('Value')(value)).toThrow(
+ 'Value must be a non-negative integer.'
+ )
+ }
+ )
+
+ test.each([
+ [[], undefined],
+ [['--min-free-disk-mb', '0'], 0],
+ [['--min-free-disk-mb', '20480'], 20480],
+ ] as const)('parses %j', (args: readonly string[], expected: number | undefined) => {
+ const command = new Command().addOption(minFreeDiskMbOption)
+ command.parse([...args], { from: 'user' })
+ expect(command.opts().minFreeDiskMb).toBe(expected)
+ expect(command.helpInformation()).toContain('--min-free-disk-mb')
+ expect(command.helpInformation()).not.toContain('--free-disk-space-mb')
+ })
+})
diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.ts
index 5bccee804..8943b3385 100644
--- a/packages/js-sdk/src/api/schema.gen.ts
+++ b/packages/js-sdk/src/api/schema.gen.ts
@@ -448,6 +448,7 @@ export interface paths {
404: components["responses"]["404"];
409: components["responses"]["409"];
500: components["responses"]["500"];
+ 503: components["responses"]["503"];
};
};
delete?: never;
@@ -2331,6 +2332,11 @@ export interface components {
* @description Memory for the sandbox in MiB
*/
MemoryMB: number;
+ /**
+ * Format: int32
+ * @description Requested minimum free space after the template's build steps, in MiB. Omit to use the team's default. Set to 0 to request no minimum free-disk growth. The filesystem is never shrunk, including inherited or already-larger filesystems. Growth is best effort, so filesystem metadata can leave the available space slightly below the requested minimum.
+ */
+ MinFreeDiskMb: number;
NewSandbox: {
/** @description Allow sandbox to access the internet. When set to false, it behaves the same as specifying denyOut to 0.0.0.0/0 in the network config. */
allow_internet_access?: boolean;
@@ -2913,6 +2919,7 @@ export interface components {
alias?: string;
cpuCount?: components["schemas"]["CPUCount"];
memoryMB?: components["schemas"]["MemoryMB"];
+ minFreeDiskMb?: components["schemas"]["MinFreeDiskMb"];
/** @description Name of the template. Can include a tag with colon separator (e.g. "my-template" or "my-template:v1"). If tag is included, it will be treated as if the tag was provided in the tags array. */
name?: string;
/** @description Tags to assign to the template build */
diff --git a/packages/js-sdk/src/template/buildApi.ts b/packages/js-sdk/src/template/buildApi.ts
index f79321166..489445c4e 100644
--- a/packages/js-sdk/src/template/buildApi.ts
+++ b/packages/js-sdk/src/template/buildApi.ts
@@ -21,6 +21,7 @@ type RequestBuildInput = {
tags?: string[]
cpuCount: number
memoryMB: number
+ minFreeDiskMb?: number
}
type GetFileUploadLinkInput = {
@@ -50,7 +51,7 @@ export type TriggerBuildTemplate = components['schemas']['TemplateBuildStartV2']
export async function requestBuild(
client: ApiClient,
- { name, tags, cpuCount, memoryMB }: RequestBuildInput,
+ { name, tags, cpuCount, memoryMB, minFreeDiskMb }: RequestBuildInput,
signal?: AbortSignal
) {
const requestBuildRes = await client.api.POST('/v3/templates', {
@@ -59,6 +60,7 @@ export async function requestBuild(
tags,
cpuCount,
memoryMB,
+ minFreeDiskMb,
},
signal,
})
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index 1b712c18a..1cc6401b2 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -1078,6 +1078,7 @@ export class TemplateBase
tags: options.tags,
cpuCount: options.cpuCount ?? 2,
memoryMB: options.memoryMB ?? 1024,
+ minFreeDiskMb: options.minFreeDiskMb,
},
config.getSignal(undefined, options.signal)
)
diff --git a/packages/js-sdk/src/template/types.ts b/packages/js-sdk/src/template/types.ts
index 87ff44441..37b12c017 100644
--- a/packages/js-sdk/src/template/types.ts
+++ b/packages/js-sdk/src/template/types.ts
@@ -42,6 +42,12 @@ export type BasicBuildOptions = {
* @default 1024
*/
memoryMB?: number
+ /**
+ * Requested minimum free space for the template filesystem after the build steps
+ * have run, in MiB. Growth is best effort and the filesystem is never shrunk.
+ * Omit to use the team default or set to 0 to request no growth.
+ */
+ minFreeDiskMb?: number
/**
* If true, skips cache and forces a complete rebuild.
* @default false
diff --git a/packages/js-sdk/tests/template/boundOpts.test.ts b/packages/js-sdk/tests/template/boundOpts.test.ts
index 855fb2d8b..dae537549 100644
--- a/packages/js-sdk/tests/template/boundOpts.test.ts
+++ b/packages/js-sdk/tests/template/boundOpts.test.ts
@@ -18,6 +18,7 @@ class BoundTemplate extends TemplateBase {
}
const requests: { url: string; apiKey: string | null }[] = []
+const buildRequestBodies: unknown[] = []
function recordRequest(request: Request) {
requests.push({
@@ -60,6 +61,7 @@ const handlers = [apiUrl, boundApiUrl].flatMap((url) => [
}),
http.post(url('/v3/templates'), async ({ request }) => {
recordRequest(request)
+ buildRequestBodies.push(await request.clone().json())
return HttpResponse.json({
templateID: 'template-id',
buildID: '00000000-0000-0000-0000-000000000000',
@@ -81,6 +83,7 @@ beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterAll(() => server.close())
afterEach(() => {
requests.length = 0
+ buildRequestBodies.length = 0
server.resetHandlers()
})
@@ -163,3 +166,27 @@ test('build options carry the bound options into the build', async () => {
requestTimeoutMs: 42,
})
})
+
+test.each([
+ [{}, undefined],
+ [{ minFreeDiskMb: 0 }, 0],
+ [{ minFreeDiskMb: 20480 }, 20480],
+])('build sends the minimum free disk option %j', async (options, expected) => {
+ await Template.buildInBackground(
+ Template().fromTemplate('parent'),
+ 'minimum',
+ {
+ apiKey: TEST_API_KEY,
+ ...options,
+ }
+ )
+
+ expect(buildRequestBodies).toEqual([
+ {
+ name: 'minimum',
+ cpuCount: 2,
+ memoryMB: 1024,
+ ...(expected === undefined ? {} : { minFreeDiskMb: expected }),
+ },
+ ])
+})
diff --git a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_pause.py b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_pause.py
index 186317b59..a145bc4d3 100644
--- a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_pause.py
+++ b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_pause.py
@@ -52,6 +52,10 @@ def _parse_response(
response_500 = Error.from_dict(response.json())
return response_500
+ if response.status_code == 503:
+ response_503 = Error.from_dict(response.json())
+
+ return response_503
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
diff --git a/packages/python-sdk/e2b/api/client/models/template_build_request_v3.py b/packages/python-sdk/e2b/api/client/models/template_build_request_v3.py
index dd5d42e73..b3e9cd7ff 100644
--- a/packages/python-sdk/e2b/api/client/models/template_build_request_v3.py
+++ b/packages/python-sdk/e2b/api/client/models/template_build_request_v3.py
@@ -20,6 +20,10 @@ class TemplateBuildRequestV3:
team_id (Union[Unset, str]): Identifier of the team
cpu_count (Union[Unset, int]): CPU cores for the sandbox
memory_mb (Union[Unset, int]): Memory for the sandbox in MiB
+ min_free_disk_mb (Union[Unset, int]): Requested minimum free space after the template's build steps, in MiB.
+ Omit to use the team's default. Set to 0 to request no minimum free-disk growth. The filesystem is never shrunk,
+ including inherited or already-larger filesystems. Growth is best effort, so filesystem metadata can leave the
+ available space slightly below the requested minimum.
"""
name: Union[Unset, str] = UNSET
@@ -28,6 +32,7 @@ class TemplateBuildRequestV3:
team_id: Union[Unset, str] = UNSET
cpu_count: Union[Unset, int] = UNSET
memory_mb: Union[Unset, int] = UNSET
+ min_free_disk_mb: Union[Unset, int] = UNSET
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
@@ -45,6 +50,8 @@ class TemplateBuildRequestV3:
memory_mb = self.memory_mb
+ min_free_disk_mb = self.min_free_disk_mb
+
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update({})
@@ -60,6 +67,8 @@ class TemplateBuildRequestV3:
field_dict["cpuCount"] = cpu_count
if memory_mb is not UNSET:
field_dict["memoryMB"] = memory_mb
+ if min_free_disk_mb is not UNSET:
+ field_dict["minFreeDiskMb"] = min_free_disk_mb
return field_dict
@@ -78,6 +87,8 @@ class TemplateBuildRequestV3:
memory_mb = d.pop("memoryMB", UNSET)
+ min_free_disk_mb = d.pop("minFreeDiskMb", UNSET)
+
template_build_request_v3 = cls(
name=name,
tags=tags,
@@ -85,6 +96,7 @@ class TemplateBuildRequestV3:
team_id=team_id,
cpu_count=cpu_count,
memory_mb=memory_mb,
+ min_free_disk_mb=min_free_disk_mb,
)
template_build_request_v3.additional_properties = d
diff --git a/packages/python-sdk/e2b/template_async/build_api.py b/packages/python-sdk/e2b/template_async/build_api.py
index 9a822cd51..328a002f9 100644
--- a/packages/python-sdk/e2b/template_async/build_api.py
+++ b/packages/python-sdk/e2b/template_async/build_api.py
@@ -51,6 +51,7 @@ async def request_build(
tags: Optional[List[str]],
cpu_count: int,
memory_mb: int,
+ min_free_disk_mb: Optional[int],
):
res = await post_v3_templates.asyncio_detailed(
client=client,
@@ -59,6 +60,9 @@ async def request_build(
tags=tags if tags else UNSET,
cpu_count=cpu_count,
memory_mb=memory_mb,
+ min_free_disk_mb=(
+ min_free_disk_mb if min_free_disk_mb is not None else UNSET
+ ),
),
)
diff --git a/packages/python-sdk/e2b/template_async/main.py b/packages/python-sdk/e2b/template_async/main.py
index 250d8aea3..2247f8b0a 100644
--- a/packages/python-sdk/e2b/template_async/main.py
+++ b/packages/python-sdk/e2b/template_async/main.py
@@ -39,6 +39,7 @@ class AsyncTemplate(TemplateBase):
tags: Optional[List[str]] = None,
cpu_count: int = 2,
memory_mb: int = 1024,
+ min_free_disk_mb: Optional[int] = None,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
request_timeout: Optional[float] = None,
@@ -52,6 +53,7 @@ class AsyncTemplate(TemplateBase):
:param tags: Optional tags for the template
:param cpu_count: Number of CPUs allocated to the sandbox
:param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param min_free_disk_mb: Requested minimum free space after the build steps, in MiB. Growth is best effort and the filesystem is never shrunk. Omit to use the team default or set to 0 to request no growth.
:param skip_cache: If True, forces a complete rebuild ignoring cache
:param on_build_logs: Callback function to receive build logs during the build process
"""
@@ -74,6 +76,7 @@ class AsyncTemplate(TemplateBase):
name=name,
cpu_count=cpu_count,
memory_mb=memory_mb,
+ min_free_disk_mb=min_free_disk_mb,
tags=tags,
)
@@ -198,6 +201,7 @@ class AsyncTemplate(TemplateBase):
tags: Optional[List[str]] = None,
cpu_count: int = 2,
memory_mb: int = 1024,
+ min_free_disk_mb: Optional[int] = None,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
**opts: Unpack[ApiParams],
@@ -211,6 +215,7 @@ class AsyncTemplate(TemplateBase):
:param tags: Optional additional tags to assign to the template
:param cpu_count: Number of CPUs allocated to the sandbox
:param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param min_free_disk_mb: Requested minimum free space after the build steps, in MiB. Growth is best effort and the filesystem is never shrunk. Omit to use the team default or set to 0 to request no growth.
:param skip_cache: If True, forces a complete rebuild ignoring cache
:param on_build_logs: Callback function to receive build logs during the build process
@@ -256,6 +261,7 @@ class AsyncTemplate(TemplateBase):
tags=tags,
cpu_count=cpu_count,
memory_mb=memory_mb,
+ min_free_disk_mb=min_free_disk_mb,
skip_cache=skip_cache,
on_build_logs=on_build_logs,
# Only honor an explicitly set request_timeout for uploads;
@@ -301,6 +307,7 @@ class AsyncTemplate(TemplateBase):
tags: Optional[List[str]] = None,
cpu_count: int = 2,
memory_mb: int = 1024,
+ min_free_disk_mb: Optional[int] = None,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
**opts: Unpack[ApiParams],
@@ -314,6 +321,7 @@ class AsyncTemplate(TemplateBase):
:param tags: Optional additional tags to assign to the template
:param cpu_count: Number of CPUs allocated to the sandbox
:param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param min_free_disk_mb: Requested minimum free space after the build steps, in MiB. Growth is best effort and the filesystem is never shrunk. Omit to use the team default or set to 0 to request no growth.
:param skip_cache: If True, forces a complete rebuild ignoring cache
:return: BuildInfo containing the template ID and build ID
@@ -350,6 +358,7 @@ class AsyncTemplate(TemplateBase):
tags=tags,
cpu_count=cpu_count,
memory_mb=memory_mb,
+ min_free_disk_mb=min_free_disk_mb,
skip_cache=skip_cache,
on_build_logs=on_build_logs,
# Only honor an explicitly set request_timeout for uploads;
diff --git a/packages/python-sdk/e2b/template_sync/build_api.py b/packages/python-sdk/e2b/template_sync/build_api.py
index 2bc918ab2..735dcf797 100644
--- a/packages/python-sdk/e2b/template_sync/build_api.py
+++ b/packages/python-sdk/e2b/template_sync/build_api.py
@@ -49,6 +49,7 @@ def request_build(
tags: Optional[List[str]],
cpu_count: int,
memory_mb: int,
+ min_free_disk_mb: Optional[int],
):
res = post_v3_templates.sync_detailed(
client=client,
@@ -57,6 +58,9 @@ def request_build(
tags=tags if tags else UNSET,
cpu_count=cpu_count,
memory_mb=memory_mb,
+ min_free_disk_mb=(
+ min_free_disk_mb if min_free_disk_mb is not None else UNSET
+ ),
),
)
diff --git a/packages/python-sdk/e2b/template_sync/main.py b/packages/python-sdk/e2b/template_sync/main.py
index 9d397b41b..1481966e0 100644
--- a/packages/python-sdk/e2b/template_sync/main.py
+++ b/packages/python-sdk/e2b/template_sync/main.py
@@ -39,6 +39,7 @@ class Template(TemplateBase):
tags: Optional[List[str]] = None,
cpu_count: int = 2,
memory_mb: int = 1024,
+ min_free_disk_mb: Optional[int] = None,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
request_timeout: Optional[float] = None,
@@ -52,6 +53,7 @@ class Template(TemplateBase):
:param tags: Optional tags for the template
:param cpu_count: Number of CPUs allocated to the sandbox
:param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param min_free_disk_mb: Requested minimum free space after the build steps, in MiB. Growth is best effort and the filesystem is never shrunk. Omit to use the team default or set to 0 to request no growth.
:param skip_cache: If True, forces a complete rebuild ignoring cache
:param on_build_logs: Callback function to receive build logs during the build process
"""
@@ -74,6 +76,7 @@ class Template(TemplateBase):
name=name,
cpu_count=cpu_count,
memory_mb=memory_mb,
+ min_free_disk_mb=min_free_disk_mb,
tags=tags,
)
@@ -198,6 +201,7 @@ class Template(TemplateBase):
tags: Optional[List[str]] = None,
cpu_count: int = 2,
memory_mb: int = 1024,
+ min_free_disk_mb: Optional[int] = None,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
**opts: Unpack[ApiParams],
@@ -211,6 +215,7 @@ class Template(TemplateBase):
:param tags: Optional additional tags to assign to the template
:param cpu_count: Number of CPUs allocated to the sandbox
:param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param min_free_disk_mb: Requested minimum free space after the build steps, in MiB. Growth is best effort and the filesystem is never shrunk. Omit to use the team default or set to 0 to request no growth.
:param skip_cache: If True, forces a complete rebuild ignoring cache
:param on_build_logs: Callback function to receive build logs during the build process
@@ -257,6 +262,7 @@ class Template(TemplateBase):
tags=tags,
cpu_count=cpu_count,
memory_mb=memory_mb,
+ min_free_disk_mb=min_free_disk_mb,
skip_cache=skip_cache,
on_build_logs=on_build_logs,
# Only honor an explicitly set request_timeout for uploads;
@@ -302,6 +308,7 @@ class Template(TemplateBase):
tags: Optional[List[str]] = None,
cpu_count: int = 2,
memory_mb: int = 1024,
+ min_free_disk_mb: Optional[int] = None,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
**opts: Unpack[ApiParams],
@@ -315,6 +322,7 @@ class Template(TemplateBase):
:param tags: Optional additional tags to assign to the template
:param cpu_count: Number of CPUs allocated to the sandbox
:param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param min_free_disk_mb: Requested minimum free space after the build steps, in MiB. Growth is best effort and the filesystem is never shrunk. Omit to use the team default or set to 0 to request no growth.
:param skip_cache: If True, forces a complete rebuild ignoring cache
:return: BuildInfo containing the template ID and build ID
@@ -351,6 +359,7 @@ class Template(TemplateBase):
tags=tags,
cpu_count=cpu_count,
memory_mb=memory_mb,
+ min_free_disk_mb=min_free_disk_mb,
skip_cache=skip_cache,
on_build_logs=on_build_logs,
# Only honor an explicitly set request_timeout for uploads;
diff --git a/packages/python-sdk/tests/async/template_async/test_bound_api_params.py b/packages/python-sdk/tests/async/template_async/test_bound_api_params.py
index a6d521947..767961884 100644
--- a/packages/python-sdk/tests/async/template_async/test_bound_api_params.py
+++ b/packages/python-sdk/tests/async/template_async/test_bound_api_params.py
@@ -1,9 +1,12 @@
from unittest.mock import AsyncMock
+from types import SimpleNamespace
import pytest
import e2b.template_async.main as template_async_main
+import e2b.template_async.build_api as template_async_build_api
from e2b import AsyncTemplate, Template, TemplateTagInfo
+from e2b.api.client.types import UNSET
from e2b.connection_config import ApiParams
from e2b.template.types import BuildInfo
@@ -133,7 +136,7 @@ async def test_build_resolves_build_impl_and_config_off_cls(configs, monkeypatch
assert (
await BoundAsyncTemplate.build_in_background(
- Template().from_base_image(), "my-template"
+ Template().from_base_image(), "my-template", min_free_disk_mb=0
)
is build_info
)
@@ -141,6 +144,7 @@ async def test_build_resolves_build_impl_and_config_off_cls(configs, monkeypatch
mock_build.assert_awaited_once()
assert configs[0].api_key == BOUND_API_KEY
assert configs[0].domain == BOUND_DOMAIN
+ assert mock_build.call_args.kwargs["min_free_disk_mb"] == 0
@pytest.mark.asyncio
@@ -167,3 +171,45 @@ async def test_bound_request_timeout_reaches_the_build(configs, monkeypatch):
)
assert mock_build.call_args.kwargs["request_timeout"] == 12.5
+
+
[email protected]("method", ["build", "build_in_background"])
+ "options, expected",
+ [
+ ({}, None),
+ ({"min_free_disk_mb": 0}, 0),
+ ({"min_free_disk_mb": 20480}, 20480),
+ ],
+)
+async def test_minimum_free_disk_option(
+ configs, monkeypatch, method, options, expected
+):
+ bodies = []
+
+ async def request(*, client, body):
+ bodies.append(body)
+ return SimpleNamespace(
+ status_code=202,
+ parsed=SimpleNamespace(
+ template_id="template-id", build_id="build-id", tags=[]
+ ),
+ )
+
+ monkeypatch.setattr(
+ template_async_build_api.post_v3_templates, "asyncio_detailed", request
+ )
+ monkeypatch.setattr(template_async_main, "trigger_build", AsyncMock())
+ monkeypatch.setattr(template_async_main, "wait_for_build_finish", AsyncMock())
+ await getattr(AsyncTemplate, method)(
+ Template().from_template("parent"), "minimum", **options
+ )
+ expected_body = {"name": "minimum", "cpuCount": 2, "memoryMB": 1024}
+ if expected is not None:
+ expected_body["minFreeDiskMb"] = expected
+ assert [body.to_dict() for body in bodies] == [expected_body]
+ if expected is None:
+ assert bodies[0].min_free_disk_mb is UNSET
+ else:
+ assert bodies[0].min_free_disk_mb == expected
diff --git a/packages/python-sdk/tests/async/template_async/test_stacktrace.py b/packages/python-sdk/tests/async/template_async/test_stacktrace.py
index 63c3e5e7a..1bfc4fadc 100644
--- a/packages/python-sdk/tests/async/template_async/test_stacktrace.py
+++ b/packages/python-sdk/tests/async/template_async/test_stacktrace.py
@@ -51,7 +51,12 @@ failure_map: dict[str, Optional[int]] = {
@pytest.fixture(autouse=True)
def mock_template_build(monkeypatch):
async def mock_request_build(
- client, name: str, tags: Optional[List[str]], cpu_count: int, memory_mb: int
+ client,
+ name: str,
+ tags: Optional[List[str]],
+ cpu_count: int,
+ memory_mb: int,
+ min_free_disk_mb: Optional[int],
):
return SimpleNamespace(template_id=name, build_id=str(uuid4()), tags=tags or [])
diff --git a/packages/python-sdk/tests/sync/template_sync/test_bound_api_params.py b/packages/python-sdk/tests/sync/template_sync/test_bound_api_params.py
index 1e4da0724..c0dc1546f 100644
--- a/packages/python-sdk/tests/sync/template_sync/test_bound_api_params.py
+++ b/packages/python-sdk/tests/sync/template_sync/test_bound_api_params.py
@@ -1,9 +1,12 @@
from unittest.mock import Mock
+from types import SimpleNamespace
import pytest
import e2b.template_sync.main as template_sync_main
+import e2b.template_sync.build_api as template_sync_build_api
from e2b import Template, TemplateTagInfo
+from e2b.api.client.types import UNSET
from e2b.connection_config import ApiParams
from e2b.template.types import BuildInfo
@@ -114,13 +117,16 @@ def test_build_resolves_build_impl_and_config_off_cls(configs, monkeypatch):
monkeypatch.setattr(BoundTemplate, "_build", staticmethod(mock_build))
assert (
- BoundTemplate.build_in_background(Template().from_base_image(), "my-template")
+ BoundTemplate.build_in_background(
+ Template().from_base_image(), "my-template", min_free_disk_mb=0
+ )
is build_info
)
mock_build.assert_called_once()
assert configs[0].api_key == BOUND_API_KEY
assert configs[0].domain == BOUND_DOMAIN
+ assert mock_build.call_args.kwargs["min_free_disk_mb"] == 0
def test_bound_request_timeout_reaches_the_build(configs, monkeypatch):
@@ -144,3 +150,40 @@ def test_bound_request_timeout_reaches_the_build(configs, monkeypatch):
TimeoutTemplate.build_in_background(Template().from_base_image(), "my-template")
assert mock_build.call_args.kwargs["request_timeout"] == 12.5
+
+
[email protected]("method", ["build", "build_in_background"])
+ "options, expected",
+ [
+ ({}, None),
+ ({"min_free_disk_mb": 0}, 0),
+ ({"min_free_disk_mb": 20480}, 20480),
+ ],
+)
+def test_minimum_free_disk_option(configs, monkeypatch, method, options, expected):
+ bodies = []
+
+ def request(*, client, body):
+ bodies.append(body)
+ return SimpleNamespace(
+ status_code=202,
+ parsed=SimpleNamespace(
+ template_id="template-id", build_id="build-id", tags=[]
+ ),
+ )
+
+ monkeypatch.setattr(
+ template_sync_build_api.post_v3_templates, "sync_detailed", request
+ )
+ monkeypatch.setattr(template_sync_main, "trigger_build", Mock())
+ monkeypatch.setattr(template_sync_main, "wait_for_build_finish", Mock())
+ getattr(Template, method)(Template().from_template("parent"), "minimum", **options)
+ expected_body = {"name": "minimum", "cpuCount": 2, "memoryMB": 1024}
+ if expected is not None:
+ expected_body["minFreeDiskMb"] = expected
+ assert [body.to_dict() for body in bodies] == [expected_body]
+ if expected is None:
+ assert bodies[0].min_free_disk_mb is UNSET
+ else:
+ assert bodies[0].min_free_disk_mb == expected
diff --git a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
index f416c84ee..dd18d8fba 100644
--- a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
+++ b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
@@ -51,7 +51,12 @@ failure_map: dict[str, Optional[int]] = {
@pytest.fixture(autouse=True)
def mock_template_build(monkeypatch):
def mock_request_build(
- client, name: str, tags: Optional[List[str]], cpu_count: int, memory_mb: int
+ client,
+ name: str,
+ tags: Optional[List[str]],
+ cpu_count: int,
+ memory_mb: int,
+ min_free_disk_mb: Optional[int],
):
return SimpleNamespace(template_id=name, build_id=str(uuid4()), tags=tags or [])
diff --git a/spec/infra-ref b/spec/infra-ref
index 564edb1f3..ce24be88d 100644
--- a/spec/infra-ref
+++ b/spec/infra-ref
@@ -1 +1 @@
-8a3f69da6f822c2de2b310dd1076d2c309eef919
+debf6bec7a59db73e3407d93ef94da5c82429089
diff --git a/spec/openapi.yml b/spec/openapi.yml
index 7018094d2..e7787b451 100644
--- a/spec/openapi.yml
+++ b/spec/openapi.yml
@@ -386,6 +386,17 @@ components:
minimum: 0
description: Disk size for the sandbox in MiB
+ MinFreeDiskMb:
+ type: integer
+ format: int32
+ minimum: 0
+ description: >-
+ Requested minimum free space after the template's build steps, in MiB.
+ Omit to use the team's default. Set to 0 to request no minimum free-disk
+ growth. The filesystem is never shrunk, including inherited or already-larger
+ filesystems. Growth is best effort, so filesystem metadata can leave the
+ available space slightly below the requested minimum.
+
EnvdVersion:
type: string
description: Version of the envd running in the sandbox
@@ -1517,6 +1528,8 @@ components:
$ref: "#/components/schemas/CPUCount"
memoryMB:
$ref: "#/components/schemas/MemoryMB"
+ minFreeDiskMb:
+ $ref: "#/components/schemas/MinFreeDiskMb"
TemplateBuildRequestV2:
required:
@@ -1759,7 +1772,6 @@ components:
type: string
description: |
Status of the node.
- - draining: the node is bound to be shut down. It will not accept new sandboxes and will stop once all existing sandboxes are done.
- standby: the node is not actively used, but it can return to ready and continue serving traffic.
enum:
- ready
@@ -1767,12 +1779,14 @@ components:
- connecting
- unhealthy
- standby
+ - shutting_down
x-enum-varnames:
- NodeStatusReady
- NodeStatusDraining
- NodeStatusConnecting
- NodeStatusUnhealthy
- NodeStatusStandby
+ - NodeStatusShuttingDown
NodeStatusChange:
required:
@@ -2867,6 +2881,8 @@ paths:
$ref: "#/components/responses/401"
"500":
$ref: "#/components/responses/500"
+ "503":
+ $ref: "#/components/responses/503"
/sandboxes/{sandboxID}/resume:
post: