Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(runtime): runtime-wide concurrency limit (MUL-8328) (#9795)

Multica Evee8b6a97643cc
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index d3cbaf969c..d50098e8c2 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -2426,6 +2426,8 @@ export class ApiClient {
custom_name?: string;
/** Apply custom_name to every runtime on the same machine. */
apply_to_machine?: boolean;
+ /** Runtime-wide concurrency cap; `null` removes it, omit to leave unchanged. */
+ max_concurrent_tasks?: number | null;
},
): Promise<AgentRuntime> {
const raw = await this.fetch<unknown>(`/api/runtimes/${runtimeId}`, {
diff --git a/packages/core/runtimes/mutations.ts b/packages/core/runtimes/mutations.ts
index bb43c0ff79..846d596215 100644
--- a/packages/core/runtimes/mutations.ts
+++ b/packages/core/runtimes/mutations.ts
@@ -90,6 +90,8 @@ export function useUpdateRuntime(wsId: string) {
// Empty string clears the custom name; omit to leave unchanged.
custom_name?: string;
apply_to_machine?: boolean;
+ // null removes the runtime-wide concurrency cap; omit to leave unchanged.
+ max_concurrent_tasks?: number | null;
};
}) => api.updateRuntime(runtimeId, patch),
onSettled: () => {
diff --git a/packages/core/runtimes/schema.test.ts b/packages/core/runtimes/schema.test.ts
index d9d9b3914f..a90c6a9c66 100644
--- a/packages/core/runtimes/schema.test.ts
+++ b/packages/core/runtimes/schema.test.ts
@@ -16,3 +16,20 @@ describe("runtime sharing response contract", () => {
expect(parseWithFallback({ id: 123 }, AgentRuntimeSchema, EMPTY_RUNTIME, { endpoint: "test" })).toEqual(EMPTY_RUNTIME);
});
});
+
+describe("runtime concurrency cap response contract", () => {
+ it("preserves a cap from a new server", () => {
+ expect(AgentRuntimeSchema.parse({ id: "r", workspace_id: "w", max_concurrent_tasks: 2 }).max_concurrent_tasks).toBe(2);
+ });
+ it("treats an older server that omits the field as no cap", () => {
+ expect(AgentRuntimeSchema.parse({ id: "r", workspace_id: "w" }).max_concurrent_tasks).toBeNull();
+ });
+ it("keeps an explicit null as no cap", () => {
+ expect(AgentRuntimeSchema.parse({ id: "r", workspace_id: "w", max_concurrent_tasks: null }).max_concurrent_tasks).toBeNull();
+ });
+ it.each(["2", 1.5, true, {}, [1]])("degrades a malformed cap to no cap without dropping the runtime: %j", (max_concurrent_tasks) => {
+ const parsed = AgentRuntimeSchema.parse({ id: "r", workspace_id: "w", name: "Claude", max_concurrent_tasks });
+ expect(parsed.max_concurrent_tasks).toBeNull();
+ expect(parsed.name).toBe("Claude");
+ });
+});
diff --git a/packages/core/runtimes/schema.ts b/packages/core/runtimes/schema.ts
index 53604e8b41..1553d99aaf 100644
--- a/packages/core/runtimes/schema.ts
+++ b/packages/core/runtimes/schema.ts
@@ -17,6 +17,7 @@ export const AgentRuntimeSchema = z.object({
visibility: z.enum(["private", "public"]).catch("private"),
shared_with: z.array(z.string().uuid()).catch([]),
profile_id: z.string().nullable().catch(null),
+ max_concurrent_tasks: z.number().int().nullable().catch(null),
last_seen_at: z.string().nullable().catch(null),
created_at: z.string().catch(""),
updated_at: z.string().catch(""),
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 8106f0907a..d313c78e17 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -86,6 +86,12 @@ export interface RuntimeDevice {
* a missing value as `null` (built-in).
*/
profile_id?: string | null;
+ /**
+ * Runtime-wide cap on tasks running at once across every agent bound to
+ * this runtime (GitHub #9626). `null` means no runtime cap; each agent's
+ * own limit still applies. Older backends omit the field.
+ */
+ max_concurrent_tasks?: number | null;
last_seen_at: string | null;
created_at: string;
updated_at: string;
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index f449bb7076..6718be154b 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -165,6 +165,10 @@
"no_agents": "No agents are bound to this runtime yet.",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "Visibility",
+ "concurrency_title": "Concurrency",
+ "concurrency_none": "No limit",
+ "concurrency_hint": "Max runs at once across all agents on this runtime ({{min}}–{{max}}). Leave empty for no limit.",
+ "toast_concurrency_failed": "Failed to update concurrency limit",
"visibility_label": {
"private": "Private",
"public": "Public",
diff --git a/packages/views/locales/fr/runtimes.json b/packages/views/locales/fr/runtimes.json
index d725526f9c..3897bc0e63 100644
--- a/packages/views/locales/fr/runtimes.json
+++ b/packages/views/locales/fr/runtimes.json
@@ -165,6 +165,10 @@
"no_agents": "Aucun agent n'est encore associé à ce runtime.",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "Visibilité",
+ "concurrency_title": "Concurrence",
+ "concurrency_none": "Aucune limite",
+ "concurrency_hint": "Nombre maximal d'exécutions simultanées pour tous les agents de ce runtime ({{min}}–{{max}}). Laissez vide pour ne pas limiter.",
+ "toast_concurrency_failed": "Échec de la mise à jour de la limite de concurrence",
"visibility_label": {
"private": "Privé",
"public": "Public",
diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.json
index 60c0b73c69..687e789a35 100644
--- a/packages/views/locales/ja/runtimes.json
+++ b/packages/views/locales/ja/runtimes.json
@@ -162,6 +162,10 @@
"no_agents": "まだこのランタイムに紐づいたエージェントがありません。",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "公開範囲",
+ "concurrency_title": "同時実行数",
+ "concurrency_none": "制限なし",
+ "concurrency_hint": "このランタイム上のすべてのエージェントで同時に行える実行の最大数({{min}}–{{max}})。空欄にすると制限なし。",
+ "toast_concurrency_failed": "同時実行数の上限を更新できませんでした",
"visibility_label": {
"private": "非公開",
"public": "公開",
diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.json
index 8da5efc9df..5f154298b9 100644
--- a/packages/views/locales/ko/runtimes.json
+++ b/packages/views/locales/ko/runtimes.json
@@ -162,6 +162,10 @@
"no_agents": "아직 이 런타임에 연결된 에이전트가 없습니다.",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "공개 범위",
+ "concurrency_title": "동시 실행",
+ "concurrency_none": "제한 없음",
+ "concurrency_hint": "이 런타임의 모든 에이전트가 동시에 진행할 수 있는 최대 실행 수({{min}}-{{max}}). 비워 두면 제한이 없습니다.",
+ "toast_concurrency_failed": "동시 실행 제한을 업데이트하지 못했습니다",
"visibility_label": {
"private": "비공개",
"public": "공개",
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index 49ed1f31a3..34ccae9020 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -162,6 +162,10 @@
"no_agents": "还没有智能体绑定到这个运行时。",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "可见性",
+ "concurrency_title": "并发",
+ "concurrency_none": "不限制",
+ "concurrency_hint": "此运行时上所有智能体同时进行的运行总数上限({{min}}–{{max}})。留空表示不限制。",
+ "toast_concurrency_failed": "更新并发上限失败",
"visibility_label": {
"private": "私有",
"public": "公开",
diff --git a/packages/views/locales/zh-Hant/runtimes.json b/packages/views/locales/zh-Hant/runtimes.json
index f8cf6225aa..3bf023e7e4 100644
--- a/packages/views/locales/zh-Hant/runtimes.json
+++ b/packages/views/locales/zh-Hant/runtimes.json
@@ -162,6 +162,10 @@
"no_agents": "還沒有 AI 代理繫結到這個執行時。",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "可見性",
+ "concurrency_title": "並行",
+ "concurrency_none": "不限制",
+ "concurrency_hint": "此執行時上所有 AI 代理同時進行的執行總數上限({{min}}–{{max}})。留空表示不限制。",
+ "toast_concurrency_failed": "更新並行上限失敗",
"visibility_label": {
"private": "私有",
"public": "公開",
diff --git a/packages/views/runtimes/components/runtime-concurrency-field.test.tsx b/packages/views/runtimes/components/runtime-concurrency-field.test.tsx
new file mode 100644
index 0000000000..f511f783c4
--- /dev/null
+++ b/packages/views/runtimes/components/runtime-concurrency-field.test.tsx
@@ -0,0 +1,116 @@
+// @vitest-environment jsdom
+
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import type { AgentRuntime } from "@multica/core/types";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enRuntimes from "../../locales/en/runtimes.json";
+import {
+ RuntimeConcurrencyField,
+ parseRuntimeConcurrencyDraft,
+} from "./runtime-concurrency-field";
+
+const mockUpdateRuntime = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@multica/core/api")>(),
+ api: {
+ updateRuntime: (...args: unknown[]) => mockUpdateRuntime(...args),
+ },
+}));
+
+vi.mock("sonner", () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+function makeRuntime(max: number | null): AgentRuntime {
+ return {
+ id: "rt-1",
+ workspace_id: "ws-1",
+ daemon_id: null,
+ name: "Claude",
+ runtime_mode: "local",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "",
+ metadata: {},
+ owner_id: "user-me",
+ visibility: "private",
+ shared_with: [],
+ max_concurrent_tasks: max,
+ last_seen_at: null,
+ created_at: "",
+ updated_at: "",
+ };
+}
+
+function renderField(runtime: AgentRuntime, canEdit = true) {
+ const qc = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
+ return render(
+ <I18nProvider locale="en" resources={{ en: { runtimes: enRuntimes } }}>
+ <QueryClientProvider client={qc}>
+ <RuntimeConcurrencyField runtime={runtime} canEdit={canEdit} />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+}
+
+describe("parseRuntimeConcurrencyDraft", () => {
+ it("maps empty to no limit and validates the range", () => {
+ expect(parseRuntimeConcurrencyDraft("")).toBeNull();
+ expect(parseRuntimeConcurrencyDraft(" ")).toBeNull();
+ expect(parseRuntimeConcurrencyDraft("1")).toBe(1);
+ expect(parseRuntimeConcurrencyDraft("50")).toBe(50);
+ expect(parseRuntimeConcurrencyDraft("0")).toBeUndefined();
+ expect(parseRuntimeConcurrencyDraft("51")).toBeUndefined();
+ expect(parseRuntimeConcurrencyDraft("1.5")).toBeUndefined();
+ });
+});
+
+describe("RuntimeConcurrencyField", () => {
+ beforeEach(() => {
+ mockUpdateRuntime.mockReset();
+ mockUpdateRuntime.mockResolvedValue(makeRuntime(1));
+ });
+
+ it("saves a new limit on Enter", async () => {
+ renderField(makeRuntime(null));
+ const input = screen.getByLabelText("Concurrency");
+ fireEvent.change(input, { target: { value: "1" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+ await waitFor(() =>
+ expect(mockUpdateRuntime).toHaveBeenCalledWith("rt-1", { max_concurrent_tasks: 1 }),
+ );
+ });
+
+ it("clears the limit when emptied", async () => {
+ renderField(makeRuntime(3));
+ const input = screen.getByLabelText("Concurrency");
+ fireEvent.change(input, { target: { value: "" } });
+ fireEvent.blur(input);
+ await waitFor(() =>
+ expect(mockUpdateRuntime).toHaveBeenCalledWith("rt-1", { max_concurrent_tasks: null }),
+ );
+ });
+
+ it("reverts an out-of-range value without saving", () => {
+ renderField(makeRuntime(3));
+ const input = screen.getByLabelText("Concurrency") as HTMLInputElement;
+ fireEvent.change(input, { target: { value: "99" } });
+ fireEvent.blur(input);
+ expect(mockUpdateRuntime).not.toHaveBeenCalled();
+ expect(input.value).toBe("3");
+ });
+
+ it("is read-only without edit permission", () => {
+ renderField(makeRuntime(null), false);
+ expect(screen.queryByLabelText("Concurrency")).toBeNull();
+ expect(screen.getByText("No limit")).toBeTruthy();
+ });
+});
diff --git a/packages/views/runtimes/components/runtime-concurrency-field.tsx b/packages/views/runtimes/components/runtime-concurrency-field.tsx
new file mode 100644
index 0000000000..b15b9e751c
--- /dev/null
+++ b/packages/views/runtimes/components/runtime-concurrency-field.tsx
@@ -0,0 +1,119 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import type { AgentRuntime } from "@multica/core/types";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ AGENT_MAX_CONCURRENT_TASKS_MAX,
+ AGENT_MAX_CONCURRENT_TASKS_MIN,
+} from "@multica/core/agents";
+import { useUpdateRuntime } from "@multica/core/runtimes/mutations";
+import { isImeComposing } from "@multica/core/utils";
+import { Input } from "@multica/ui/components/ui/input";
+import { useT } from "../../i18n";
+
+/**
+ * Parses the field draft. Empty means "no limit" (null); otherwise an integer
+ * in the same range as an agent's own limit. Returns undefined for anything
+ * else so the caller can revert the draft.
+ */
+export function parseRuntimeConcurrencyDraft(draft: string): number | null | undefined {
+ const trimmed = draft.trim();
+ if (trimmed === "") return null;
+ const next = Number(trimmed);
+ if (
+ !Number.isInteger(next) ||
+ next < AGENT_MAX_CONCURRENT_TASKS_MIN ||
+ next > AGENT_MAX_CONCURRENT_TASKS_MAX
+ ) {
+ return undefined;
+ }
+ return next;
+}
+
+/**
+ * Runtime-wide concurrency cap (GitHub #9626): bounds the combined running
+ * tasks of every agent bound to this runtime, e.g. several agents sharing
+ * one local GPU. Empty means no runtime cap.
+ */
+export function RuntimeConcurrencyField({
+ runtime,
+ canEdit,
+}: {
+ runtime: AgentRuntime;
+ canEdit: boolean;
+}) {
+ const { t } = useT("runtimes");
+ const wsId = useWorkspaceId();
+ const updateRuntime = useUpdateRuntime(wsId);
+ const value = runtime.max_concurrent_tasks ?? null;
+ const toDraft = (v: number | null) => (v === null ? "" : String(v));
+ const [draft, setDraft] = useState(toDraft(value));
+
+ useEffect(() => setDraft(toDraft(value)), [value]);
+
+ if (!canEdit) {
+ return (
+ <span className="font-mono text-caption tabular-nums text-muted-foreground">
+ {value ?? t(($) => $.detail.concurrency_none)}
+ </span>
+ );
+ }
+
+ const commit = () => {
+ const next = parseRuntimeConcurrencyDraft(draft);
+ if (next === undefined) {
+ setDraft(toDraft(value));
+ return;
+ }
+ if (next === value) return;
+ updateRuntime.mutate(
+ { runtimeId: runtime.id, patch: { max_concurrent_tasks: next } },
+ {
+ onError: (err) => {
+ setDraft(toDraft(value));
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.detail.toast_concurrency_failed),
+ );
+ },
+ },
+ );
+ };
+
+ return (
+ <div>
+ <Input
+ id="runtime-concurrency"
+ type="number"
+ name="runtime-concurrency"
+ autoComplete="off"
+ inputMode="numeric"
+ min={AGENT_MAX_CONCURRENT_TASKS_MIN}
+ max={AGENT_MAX_CONCURRENT_TASKS_MAX}
+ placeholder={t(($) => $.detail.concurrency_none)}
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={commit}
+ onKeyDown={(event) => {
+ if (isImeComposing(event)) return;
+ if (event.key === "Enter") {
+ event.preventDefault();
+ commit();
+ }
+ }}
+ disabled={updateRuntime.isPending}
+ aria-label={t(($) => $.detail.concurrency_title)}
+ className="font-mono tabular-nums"
+ />
+ <p className="mt-1 text-caption text-muted-foreground">
+ {t(($) => $.detail.concurrency_hint, {
+ min: AGENT_MAX_CONCURRENT_TASKS_MIN,
+ max: AGENT_MAX_CONCURRENT_TASKS_MAX,
+ })}
+ </p>
+ </div>
+ );
+}
diff --git a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
index 0989552265..b5088f1643 100644
--- a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
+++ b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
@@ -104,6 +104,8 @@ vi.mock("@multica/core/runtimes", async () => ({
vi.mock("@multica/core/agents", () => ({
useWorkspacePresenceMap: () => ({ byAgent: new Map() }),
+ AGENT_MAX_CONCURRENT_TASKS_MIN: 1,
+ AGENT_MAX_CONCURRENT_TASKS_MAX: 50,
}));
vi.mock("@multica/core/paths", () => ({
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index 829d2f01ec..1c0bbff479 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -54,6 +54,7 @@ import { ProviderLogo } from "./provider-logo";
import { UsageSection } from "./usage-section";
import { DeleteRuntimeDialog } from "./delete-runtime-dialog";
import { RuntimeAccessEditor, RuntimeAccessReadout } from "./runtime-access-editor";
+import { RuntimeConcurrencyField } from "./runtime-concurrency-field";
import { DeleteRuntimeProfileDialog } from "./delete-runtime-profile-dialog";
import { runtimeRowLabel } from "./runtime-machines";
import { useT, useTimeAgo } from "../../i18n";
@@ -191,6 +192,7 @@ export function RuntimeDetail({
device={device}
cliVersion={cliVersion}
canEditVisibility={!!isRuntimeOwner}
+ canEditRuntime={!!canEditRuntime}
/>
}
>
@@ -306,6 +308,7 @@ function RuntimeProperties({
device,
cliVersion,
canEditVisibility,
+ canEditRuntime,
}: {
runtime: AgentRuntime;
health: ReturnType<typeof deriveRuntimeHealth>;
@@ -319,6 +322,8 @@ function RuntimeProperties({
* though they may still rename or delete the runtime.
*/
canEditVisibility: boolean;
+ /** Runtime owner or workspace admin; gates the concurrency cap. */
+ canEditRuntime: boolean;
}) {
const { t } = useT("runtimes");
const { t: tLayout } = useT("layout");
@@ -383,6 +388,11 @@ function RuntimeProperties({
)}
</div>
</ObjectPanelSection>
+ <ObjectPanelSection title={t(($) => $.detail.concurrency_title)}>
+ <div className="pr-0.5 pt-1">
+ <RuntimeConcurrencyField runtime={runtime} canEdit={canEditRuntime} />
+ </div>
+ </ObjectPanelSection>
</div>
);
}
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 4d7a82e5e6..421212601b 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,7 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "606_agent_task_queue_runtime_active_index": "idx_agent_task_queue_runtime_active",
"604_wecom_install_session_begin_rate_idx": "idx_wecom_install_session_begin_rate",
"603_wecom_install_session_agent_pending_idx": "idx_wecom_install_session_agent_pending",
"602_wecom_install_session_request_idx": "idx_wecom_install_session_request",
diff --git a/server/cmd/multica/cmd_runtime.go b/server/cmd/multica/cmd_runtime.go
index 1d81fb814a..edda26bbf8 100644
--- a/server/cmd/multica/cmd_runtime.go
+++ b/server/cmd/multica/cmd_runtime.go
@@ -7,11 +7,13 @@ import (
"fmt"
"net/http"
"os"
+ "strconv"
"strings"
"time"
"github.com/spf13/cobra"
+ "github.com/multica-ai/multica/server/internal/agentconfig"
"github.com/multica-ai/multica/server/internal/cli"
)
@@ -57,6 +59,16 @@ var runtimeRenameCmd = &cobra.Command{
RunE: runRuntimeRename,
}
+var runtimeConcurrencyCmd = &cobra.Command{
+ Use: "concurrency <runtime-id> <limit|none>",
+ Short: "Set or clear a runtime-wide concurrency limit",
+ Long: "Limit how many runs may be in progress at once across every agent bound to this runtime.\n\n" +
+ "Each agent's own limit still applies; this caps their combined work, e.g. when several " +
+ "agents share one local GPU. Pass \"none\" to remove the limit.",
+ Args: exactArgs(2),
+ RunE: runRuntimeConcurrency,
+}
+
var runtimeDeleteCmd = &cobra.Command{
Use: "delete <runtime-id>",
Short: "Delete a runtime from the workspace",
@@ -74,6 +86,7 @@ func init() {
runtimeCmd.AddCommand(runtimeActivityCmd)
runtimeCmd.AddCommand(runtimeUpdateCmd)
runtimeCmd.AddCommand(runtimeRenameCmd)
+ runtimeCmd.AddCommand(runtimeConcurrencyCmd)
runtimeCmd.AddCommand(runtimeDeleteCmd)
// runtime list
@@ -95,6 +108,9 @@ func init() {
runtimeRenameCmd.Flags().Bool("machine", false, "Apply the name to every runtime on the same machine")
runtimeRenameCmd.Flags().String("output", "table", "Output format: table or json")
+ // runtime concurrency
+ runtimeConcurrencyCmd.Flags().String("output", "table", "Output format: table or json")
+
// runtime delete
runtimeDeleteCmd.Flags().Bool("cascade", false, "Unbind active agents from the runtime, cancel their runs, then delete the runtime")
runtimeDeleteCmd.Flags().String("output", "table", "Output format: table or json")
@@ -293,6 +309,51 @@ func runRuntimeRename(cmd *cobra.Command, args []string) error {
return nil
}
+// parseRuntimeConcurrencyArg maps the CLI argument onto the PATCH value:
+// "none" clears the limit (JSON null), otherwise an integer in the agent
+// limit range.
+func parseRuntimeConcurrencyArg(arg string) (any, error) {
+ if strings.EqualFold(strings.TrimSpace(arg), "none") {
+ return nil, nil
+ }
+ n, err := strconv.Atoi(strings.TrimSpace(arg))
+ if err != nil || n < int(agentconfig.MinMaxConcurrentTasks) || n > int(agentconfig.MaxMaxConcurrentTasks) {
+ return nil, fmt.Errorf("limit must be \"none\" or an integer between %d and %d", agentconfig.MinMaxConcurrentTasks, agentconfig.MaxMaxConcurrentTasks)
+ }
+ return n, nil
+}
+
+func runRuntimeConcurrency(cmd *cobra.Command, args []string) error {
+ limit, err := parseRuntimeConcurrencyArg(args[1])
+ if err != nil {
+ return err
+ }
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ var rt map[string]any
+ body := map[string]any{"max_concurrent_tasks": limit}
+ if err := client.PatchJSON(ctx, "/api/runtimes/"+args[0], body, &rt); err != nil {
+ return fmt.Errorf("set runtime concurrency: %w", err)
+ }
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, rt)
+ }
+ if limit == nil {
+ fmt.Fprintln(os.Stderr, "Runtime concurrency limit removed.")
+ } else {
+ fmt.Fprintf(os.Stderr, "Runtime concurrency limit set to %d.\n", limit)
+ }
+ return nil
+}
+
func runRuntimeUpdate(cmd *cobra.Command, args []string) error {
client, err := newAPIClient(cmd)
if err != nil {
diff --git a/server/cmd/multica/cmd_runtime_concurrency_test.go b/server/cmd/multica/cmd_runtime_concurrency_test.go
new file mode 100644
index 0000000000..05ba6f847b
--- /dev/null
+++ b/server/cmd/multica/cmd_runtime_concurrency_test.go
@@ -0,0 +1,36 @@
+package main
+
+import "testing"
+
+func TestParseRuntimeConcurrencyArg(t *testing.T) {
+ tests := []struct {
+ arg string
+ want any
+ wantErr bool
+ }{
+ {arg: "none", want: nil},
+ {arg: "NONE", want: nil},
+ {arg: "1", want: 1},
+ {arg: " 50 ", want: 50},
+ {arg: "0", wantErr: true},
+ {arg: "51", wantErr: true},
+ {arg: "two", wantErr: true},
+ {arg: "", wantErr: true},
+ }
+ for _, tt := range tests {
+ got, err := parseRuntimeConcurrencyArg(tt.arg)
+ if tt.wantErr {
+ if err == nil {
+ t.Errorf("parseRuntimeConcurrencyArg(%q) = %v, want error", tt.arg, got)
+ }
+ continue
+ }
+ if err != nil {
+ t.Errorf("parseRuntimeConcurrencyArg(%q) error: %v", tt.arg, err)
+ continue
+ }
+ if got != tt.want {
+ t.Errorf("parseRuntimeConcurrencyArg(%q) = %v, want %v", tt.arg, got, tt.want)
+ }
+ }
+}
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index b0124b1aad..9352eaa37a 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -15,6 +15,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/agentconfig"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
@@ -46,10 +47,13 @@ type AgentRuntimeResponse struct {
SharedWith []string `json:"shared_with"`
// ProfileID is set when this runtime is an instance of a custom
// runtime_profile (MUL-3284); null for built-in runtimes.
- ProfileID *string `json:"profile_id"`
- LastSeenAt *string `json:"last_seen_at"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
+ ProfileID *string `json:"profile_id"`
+ // MaxConcurrentTasks caps tasks running at once across every agent bound
+ // to this runtime (GitHub #9626); null means no runtime-wide cap.
+ MaxConcurrentTasks *int32 `json:"max_concurrent_tasks"`
+ LastSeenAt *string `json:"last_seen_at"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
}
func runtimeToResponse(rt db.AgentRuntime) AgentRuntimeResponse {
@@ -62,24 +66,25 @@ func runtimeToResponse(rt db.AgentRuntime) AgentRuntimeResponse {
}
return AgentRuntimeResponse{
- ID: uuidToString(rt.ID),
- WorkspaceID: uuidToString(rt.WorkspaceID),
- DaemonID: textToPtr(rt.DaemonID),
- Name: rt.Name,
- CustomName: textToPtr(rt.CustomName),
- RuntimeMode: rt.RuntimeMode,
- Provider: rt.Provider,
- LaunchHeader: agent.LaunchHeader(rt.Provider),
- Status: rt.Status,
- DeviceInfo: rt.DeviceInfo,
- Metadata: metadata,
- OwnerID: uuidToPtr(rt.OwnerID),
- Visibility: rt.Visibility,
- SharedWith: runtimeSharedWithStrings(rt.SharedWith),
- ProfileID: uuidToPtr(rt.ProfileID),
- LastSeenAt: timestampToPtr(rt.LastSeenAt),
- CreatedAt: timestampToString(rt.CreatedAt),
- UpdatedAt: timestampToString(rt.UpdatedAt),
+ ID: uuidToString(rt.ID),
+ WorkspaceID: uuidToString(rt.WorkspaceID),
+ DaemonID: textToPtr(rt.DaemonID),
+ Name: rt.Name,
+ CustomName: textToPtr(rt.CustomName),
+ RuntimeMode: rt.RuntimeMode,
+ Provider: rt.Provider,
+ LaunchHeader: agent.LaunchHeader(rt.Provider),
+ Status: rt.Status,
+ DeviceInfo: rt.DeviceInfo,
+ Metadata: metadata,
+ OwnerID: uuidToPtr(rt.OwnerID),
+ Visibility: rt.Visibility,
+ SharedWith: runtimeSharedWithStrings(rt.SharedWith),
+ ProfileID: uuidToPtr(rt.ProfileID),
+ MaxConcurrentTasks: int4ToPtr(rt.MaxConcurrentTasks),
+ LastSeenAt: timestampToPtr(rt.LastSeenAt),
+ CreatedAt: timestampToString(rt.CreatedAt),
+ UpdatedAt: timestampToString(rt.UpdatedAt),
}
}
@@ -478,6 +483,27 @@ type UpdateAgentRuntimeRequest struct {
// runtime per provider) instead of just this one. Ignored when the
// runtime has no daemon_id.
ApplyToMachine bool `json:"apply_to_machine,omitempty"`
+ // MaxConcurrentTasks sets the runtime-wide concurrency cap (GitHub
+ // #9626): an integer in the agent limit range, or null to remove the
+ // cap. Absent leaves it unchanged. Owner / workspace admin only.
+ MaxConcurrentTasks json.RawMessage `json:"max_concurrent_tasks,omitempty"`
+ maxConcurrentTasks pgtype.Int4
+}
+
+// parseRuntimeMaxConcurrentTasks decodes the tri-state PATCH field: JSON null
+// clears the cap, an integer within the agent limit range sets it.
+func parseRuntimeMaxConcurrentTasks(raw json.RawMessage) (pgtype.Int4, error) {
+ if strings.TrimSpace(string(raw)) == "null" {
+ return pgtype.Int4{}, nil
+ }
+ var v int32
+ if err := json.Unmarshal(raw, &v); err != nil {
+ return pgtype.Int4{}, errors.New("max_concurrent_tasks must be an integer or null")
+ }
+ if err := agentconfig.ValidateMaxConcurrentTasks(v); err != nil {
+ return pgtype.Int4{}, fmt.Errorf("max_concurrent_tasks %w", err)
+ }
+ return pgtype.Int4{Int32: v, Valid: true}, nil
}
// maxRuntimeCustomNameLen caps a runtime's custom name. Default names are
@@ -537,6 +563,13 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {
return
}
}
+ if req.MaxConcurrentTasks != nil {
+ req.maxConcurrentTasks, err = parseRuntimeMaxConcurrentTasks(req.MaxConcurrentTasks)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ }
changed := false
@@ -615,6 +648,23 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {
}
}
+ if req.MaxConcurrentTasks != nil {
+ updated, err := h.updateRuntimeMaxConcurrentTasks(r.Context(), runtimeUUID, req.maxConcurrentTasks)
+ if err != nil {
+ slog.Error("UpdateAgentRuntimeMaxConcurrentTasks failed", "error", err, "runtime_id", runtimeID)
+ writeError(w, http.StatusInternalServerError, "failed to update runtime")
+ return
+ }
+ rt = updated
+ changed = true
+ // Raising or removing the cap can make queued work claimable right
+ // away; nudge the runtime's daemon instead of waiting for its next
+ // poll.
+ if h.TaskService != nil {
+ h.TaskService.NotifyRuntimeCapacityChanged(rt.ID)
+ }
+ }
+
if changed {
// Notify connected clients that runtime metadata changed so the
// list/detail pages refresh — matches the pattern used by
@@ -627,6 +677,35 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, runtimeToResponse(rt))
}
+// updateRuntimeMaxConcurrentTasks writes the runtime-wide cap and then waits
+// on the runtime claim lock before committing. Claims read the cap only after
+// taking that lock, so once this returns no claim can still commit against
+// the old value (a claim queued behind the lock reads the new one). The row
+// is updated before the lock is taken; see LockRuntimeClaimCapacity for why
+// that order cannot deadlock with claims or runtime teardown.
+func (h *Handler) updateRuntimeMaxConcurrentTasks(ctx context.Context, runtimeID pgtype.UUID, limit pgtype.Int4) (db.AgentRuntime, error) {
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return db.AgentRuntime{}, fmt.Errorf("begin transaction: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ updated, err := qtx.UpdateAgentRuntimeMaxConcurrentTasks(ctx, db.UpdateAgentRuntimeMaxConcurrentTasksParams{
+ MaxConcurrentTasks: limit,
+ ID: runtimeID,
+ })
+ if err != nil {
+ return db.AgentRuntime{}, err
+ }
+ if err := qtx.LockRuntimeClaimCapacity(ctx, runtimeID); err != nil {
+ return db.AgentRuntime{}, fmt.Errorf("lock runtime claim capacity: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.AgentRuntime{}, fmt.Errorf("commit: %w", err)
+ }
+ return updated, nil
+}
+
func canEditRuntime(member db.Member, rt db.AgentRuntime) bool {
if roleAllowed(member.Role, "owner", "admin") {
return true
diff --git a/server/internal/handler/runtime_concurrency_test.go b/server/internal/handler/runtime_concurrency_test.go
new file mode 100644
index 0000000000..cfd4d1d0c5
--- /dev/null
+++ b/server/internal/handler/runtime_concurrency_test.go
@@ -0,0 +1,133 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestUpdateAgentRuntime_MaxConcurrentTasks covers the runtime-wide cap
+// (GitHub #9626): a PATCH sets it, JSON null clears it, an absent field
+// leaves it unchanged, out-of-range / non-integer values are rejected before
+// any write, and a plain member cannot change someone else's runtime.
+func TestUpdateAgentRuntime_MaxConcurrentTasks(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ runtimeID, runtimeOwnerID, plainMemberID := runtimeVisibilityFixture(t)
+
+ decode := func(t *testing.T, body []byte) AgentRuntimeResponse {
+ t.Helper()
+ var resp AgentRuntimeResponse
+ if err := json.Unmarshal(body, &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ return resp
+ }
+
+ w := patchRuntimeCustomName(runtimeOwnerID, runtimeID, map[string]any{})
+ if w.Code != http.StatusOK {
+ t.Fatalf("empty PATCH: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if resp := decode(t, w.Body.Bytes()); resp.MaxConcurrentTasks != nil {
+ t.Fatalf("new runtime should have no cap, got %d", *resp.MaxConcurrentTasks)
+ }
+
+ w = patchRuntimeCustomName(runtimeOwnerID, runtimeID, map[string]any{"max_concurrent_tasks": 1})
+ if w.Code != http.StatusOK {
+ t.Fatalf("set cap: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if resp := decode(t, w.Body.Bytes()); resp.MaxConcurrentTasks == nil || *resp.MaxConcurrentTasks != 1 {
+ t.Fatalf("cap after set: got %v, want 1", resp.MaxConcurrentTasks)
+ }
+
+ // A PATCH for another field must not touch the cap.
+ w = patchRuntimeCustomName(runtimeOwnerID, runtimeID, map[string]any{"custom_name": "GPU box"})
+ if w.Code != http.StatusOK {
+ t.Fatalf("rename: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if resp := decode(t, w.Body.Bytes()); resp.MaxConcurrentTasks == nil || *resp.MaxConcurrentTasks != 1 {
+ t.Fatalf("cap after unrelated PATCH: got %v, want 1", resp.MaxConcurrentTasks)
+ }
+
+ for _, bad := range []any{0, 51, -1, 1.5, "2", true} {
+ w = patchRuntimeCustomName(runtimeOwnerID, runtimeID, map[string]any{"max_concurrent_tasks": bad})
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("cap=%v: expected 400, got %d: %s", bad, w.Code, w.Body.String())
+ }
+ }
+
+ w = patchRuntimeCustomName(plainMemberID, runtimeID, map[string]any{"max_concurrent_tasks": 5})
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("plain member: expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+
+ w = patchRuntimeCustomName(runtimeOwnerID, runtimeID, map[string]any{"max_concurrent_tasks": nil})
+ if w.Code != http.StatusOK {
+ t.Fatalf("clear cap: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if resp := decode(t, w.Body.Bytes()); resp.MaxConcurrentTasks != nil {
+ t.Fatalf("cap after clear: got %d, want null", *resp.MaxConcurrentTasks)
+ }
+}
+
+// TestUpdateAgentRuntime_MaxConcurrentTasksWaitsForInFlightClaim: the cap
+// update must not commit while a claim on the same runtime holds the claim
+// lock, so once PATCH returns no claim can still commit against the old cap.
+func TestUpdateAgentRuntime_MaxConcurrentTasksWaitsForInFlightClaim(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ runtimeID, _, _ := runtimeVisibilityFixture(t)
+ rtUUID := util.MustParseUUID(runtimeID)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ claimTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ defer claimTx.Rollback(context.Background())
+ if err := db.New(claimTx).LockRuntimeClaimCapacity(ctx, rtUUID); err != nil {
+ t.Fatalf("lock: %v", err)
+ }
+
+ done := make(chan error, 1)
+ go func() {
+ _, err := testHandler.updateRuntimeMaxConcurrentTasks(ctx, rtUUID, pgtype.Int4{Int32: 1, Valid: true})
+ done <- err
+ }()
+
+ select {
+ case err := <-done:
+ t.Fatalf("cap update returned (err=%v) while a claim held the runtime lock", err)
+ case <-time.After(300 * time.Millisecond):
+ }
+ var visible pgtype.Int4
+ if err := testPool.QueryRow(ctx, `SELECT max_concurrent_tasks FROM agent_runtime WHERE id = $1`, rtUUID).Scan(&visible); err != nil {
+ t.Fatalf("read cap: %v", err)
+ }
+ if visible.Valid {
+ t.Fatalf("cap %d visible before the in-flight claim finished", visible.Int32)
+ }
+
+ if err := claimTx.Commit(ctx); err != nil {
+ t.Fatalf("commit claim tx: %v", err)
+ }
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("cap update: %v", err)
+ }
+ case <-ctx.Done():
+ t.Fatal("cap update did not finish after the claim committed")
+ }
+}
diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.go
index f12546ca1f..9a19eb7670 100644
--- a/server/internal/metrics/business.go
+++ b/server/internal/metrics/business.go
@@ -810,6 +810,7 @@ func claimDecisionSeries() []claimDecisionSeriesKey {
claimTaskOutcomes := []claimDecisionSeriesKey{
{"", "claimed", "claimed"},
{"", "no_capacity", "agent_concurrency_cap"},
+ {"", "runtime_no_capacity", "runtime_concurrency_cap"},
{"", "no_runtime", "agent_unbound"},
{"", "runtime_mismatch", "agent_rebound"},
{"", "error_get_agent", "error"},
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 86718feab0..016ce3fc20 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -3660,6 +3660,42 @@ func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.U
return nil
}
+ // Runtime-wide cap (GitHub #9626): several agents can share one
+ // runtime (e.g. one local GPU), so the per-agent cap alone cannot
+ // keep their combined work bounded.
+ //
+ // The lock is taken before the cap is read, on every claim. The cap
+ // update (UpdateAgentRuntimeMaxConcurrentTasks in the handler) takes
+ // the same lock before committing, so once a PATCH returns, no claim
+ // can still commit against the old value: a claim either finished
+ // before the update got the lock, or reads the new value after it.
+ // Reading the cap first and locking only when it is set would let a
+ // claim that waited on the lock (or read NULL) dispatch against a
+ // stale cap. Claims on one runtime are already short and nearly
+ // serial (one daemon per runtime), so the extra lock is cheap.
+ if err := qtx.LockRuntimeClaimCapacity(ctx, claimRuntimeID); err != nil {
+ outcome = claimOutcomeErrorCountRunning
+ return fmt.Errorf("lock runtime claim capacity: %w", err)
+ }
+ runtimeCap, err := qtx.GetAgentRuntimeMaxConcurrentTasks(ctx, claimRuntimeID)
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ outcome = claimOutcomeErrorCountRunning
+ return fmt.Errorf("get runtime concurrency cap: %w", err)
+ }
+ if err == nil && runtimeCap.Valid {
+ runtimeRunning, err := qtx.CountActiveTasksByRuntime(ctx, claimRuntimeID)
+ if err != nil {
+ outcome = claimOutcomeErrorCountRunning
+ return fmt.Errorf("count runtime running tasks: %w", err)
+ }
+ if runtimeRunning >= int64(runtimeCap.Int32) {
+ decisionDetail = claimDecisionDetail{running: runtimeRunning, maxConcurrent: int64(runtimeCap.Int32)}
+ outcome = claimOutcomeRuntimeNoCapacity
+ return nil
+ }
+ }
+ countRunningMs = time.Since(t0).Milliseconds()
+
t0 = time.Now()
reclaimCheckAfter = t0.Add(claimResponseRecoveryWindow + ReclaimCheckHintSafetyMargin)
task, err := qtx.ClaimAgentTask(ctx, db.ClaimAgentTaskParams{
@@ -7399,6 +7435,13 @@ func (s *TaskService) NotifyTaskFinished(task db.AgentTaskQueue) {
s.notifyRuntimeMayHaveWork(task.RuntimeID, "")
}
+// NotifyRuntimeCapacityChanged wakes a runtime's daemon after its
+// runtime-wide concurrency cap was raised or removed (GitHub #9626), since
+// queued work held back by the old cap may now be claimable.
+func (s *TaskService) NotifyRuntimeCapacityChanged(runtimeID pgtype.UUID) {
+ s.notifyRuntimeMayHaveWork(runtimeID, "")
+}
+
// notifyTasksFinished is the batch form used by bulk terminal transitions.
// Coalesce by runtime so cancelling many tasks on one machine produces one
// cache bump and one websocket hint rather than a burst of identical work.
diff --git a/server/internal/service/task_claim_decision.go b/server/internal/service/task_claim_decision.go
index 2b5c9941fd..ab41d8030a 100644
--- a/server/internal/service/task_claim_decision.go
+++ b/server/internal/service/task_claim_decision.go
@@ -42,6 +42,7 @@ const (
claimOutcomeClaimed = "claimed"
claimOutcomeNoTasks = "no_tasks"
claimOutcomeNoCapacity = "no_capacity"
+ claimOutcomeRuntimeNoCapacity = "runtime_no_capacity"
claimOutcomeNoRuntime = "no_runtime"
claimOutcomeRuntimeMismatch = "runtime_mismatch"
claimOutcomeErrorGetAgent = "error_get_agent"
@@ -72,16 +73,17 @@ const (
// this attempt (cause unknown — fence or lost race), the latter says the
// candidate query itself saw nothing claimable.
const (
- claimReasonClaimed = "claimed"
- claimReasonNoVisibleCandidates = "no_visible_candidates"
- claimReasonCandidatesUnclaimed = "candidates_unclaimed"
- claimReasonUnknownCandidates = "unknown_candidates"
- claimReasonAgentConcurrencyCap = "agent_concurrency_cap"
- claimReasonAgentUnbound = "agent_unbound"
- claimReasonAgentRebound = "agent_rebound"
- claimReasonEmptyCache = "empty_cache"
- claimReasonStaleDispatchRecover = "stale_dispatch_recovered"
- claimReasonError = "error"
+ claimReasonClaimed = "claimed"
+ claimReasonNoVisibleCandidates = "no_visible_candidates"
+ claimReasonCandidatesUnclaimed = "candidates_unclaimed"
+ claimReasonUnknownCandidates = "unknown_candidates"
+ claimReasonAgentConcurrencyCap = "agent_concurrency_cap"
+ claimReasonRuntimeConcurrencyCap = "runtime_concurrency_cap"
+ claimReasonAgentUnbound = "agent_unbound"
+ claimReasonAgentRebound = "agent_rebound"
+ claimReasonEmptyCache = "empty_cache"
+ claimReasonStaleDispatchRecover = "stale_dispatch_recovered"
+ claimReasonError = "error"
)
// Claim poll paths, as seen by the counter's claim_path label. Distinct from
@@ -104,8 +106,8 @@ type claimScope struct {
candidates int
}
-// claimDecisionDetail carries the capacity numbers behind a no_capacity
-// decision. Left zero for every other outcome.
+// claimDecisionDetail carries the capacity numbers behind a no_capacity or
+// runtime_no_capacity decision. Left zero for every other outcome.
type claimDecisionDetail struct {
running int64
maxConcurrent int64
@@ -126,6 +128,8 @@ func claimReasonFor(outcome string, scope claimScope) string {
return claimReasonNoVisibleCandidates
case claimOutcomeNoCapacity:
return claimReasonAgentConcurrencyCap
+ case claimOutcomeRuntimeNoCapacity:
+ return claimReasonRuntimeConcurrencyCap
case claimOutcomeRuntimeMismatch:
return claimReasonAgentRebound
case claimOutcomeNoRuntime:
@@ -180,7 +184,7 @@ func (s *TaskService) recordClaimDecision(agentID, runtimeID pgtype.UUID, outcom
"runtime_id", util.UUIDToString(runtimeID),
"candidates", scope.candidates,
}
- if outcome == claimOutcomeNoCapacity {
+ if outcome == claimOutcomeNoCapacity || outcome == claimOutcomeRuntimeNoCapacity {
attrs = append(attrs, "running", detail.running, "max", detail.maxConcurrent)
}
slog.Debug("task claim decision", attrs...)
diff --git a/server/internal/service/task_claim_decision_test.go b/server/internal/service/task_claim_decision_test.go
index 3dcc8f6d4c..8517e55d69 100644
--- a/server/internal/service/task_claim_decision_test.go
+++ b/server/internal/service/task_claim_decision_test.go
@@ -28,6 +28,7 @@ func TestClaimDecisionReasonFor(t *testing.T) {
{name: "claimed stays claimed", outcome: claimOutcomeClaimed, scope: claimScope{claimPath: claimPathAgent}, want: claimReasonClaimed},
{name: "claimed via runtime poll", outcome: claimOutcomeClaimed, scope: claimScope{claimPath: claimPathRuntime, candidates: 3}, want: claimReasonClaimed},
{name: "no capacity maps to concurrency cap", outcome: claimOutcomeNoCapacity, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonAgentConcurrencyCap},
+ {name: "runtime no capacity maps to runtime cap", outcome: claimOutcomeRuntimeNoCapacity, scope: claimScope{claimPath: claimPathBatch}, want: claimReasonRuntimeConcurrencyCap},
{name: "no runtime maps to unbound agent", outcome: claimOutcomeNoRuntime, scope: claimScope{claimPath: claimPathAgent}, want: claimReasonAgentUnbound},
{name: "runtime mismatch maps to rebound agent", outcome: claimOutcomeRuntimeMismatch, scope: claimScope{claimPath: claimPathRuntime}, want: claimReasonAgentRebound},
diff --git a/server/internal/service/task_runtime_concurrency_db_test.go b/server/internal/service/task_runtime_concurrency_db_test.go
new file mode 100644
index 0000000000..3c6868de19
--- /dev/null
+++ b/server/internal/service/task_runtime_concurrency_db_test.go
@@ -0,0 +1,305 @@
+package service
+
+import (
+ "context"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// DB-backed coverage for the runtime-wide concurrency cap (GitHub #9626).
+// Reuses the claim-decision fixture (one runtime, one agent) and adds more
+// agents on the same runtime so the per-agent cap is never what blocks.
+
+// addRuntimeAgentWithTask binds another agent to the fixture runtime and
+// queues one task for it on its own issue, so per-(issue, agent)
+// serialization cannot be the fence under test.
+func (f *claimDecisionFixture) addRuntimeAgentWithTask(t *testing.T, name string) string {
+ t.Helper()
+ agentID := f.fx.Agent(t, name, util.UUIDToString(f.runtimeID), testutil.Cols{
+ "owner_id": f.fx.UserID,
+ "max_concurrent_tasks": 5,
+ })
+ issueID := f.fx.Issue(t, name+" issue")
+ return f.fx.Task(t, agentID, testutil.Cols{
+ "runtime_id": util.UUIDToString(f.runtimeID),
+ "issue_id": issueID,
+ "status": "queued",
+ })
+}
+
+func (f *claimDecisionFixture) setRuntimeCap(t *testing.T, limit *int32) {
+ t.Helper()
+ var v pgtype.Int4
+ if limit != nil {
+ v = pgtype.Int4{Int32: *limit, Valid: true}
+ }
+ if _, err := f.pool.Exec(context.Background(),
+ `UPDATE agent_runtime SET max_concurrent_tasks = $2 WHERE id = $1`, f.runtimeID, v,
+ ); err != nil {
+ t.Fatalf("set runtime cap: %v", err)
+ }
+}
+
+func int32Ptr(v int32) *int32 { return &v }
+
+// With a cap of 1, two agents that each have spare per-agent capacity still
+// get only one task between them; the second attempt is attributed to the
+// runtime cap. Finishing the first task frees the slot.
+func TestRuntimeConcurrencyCapLimitsAcrossAgents(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+ f.insertTask(t, "queued")
+ f.addRuntimeAgentWithTask(t, "runtime-cap-agent-b")
+ f.setRuntimeCap(t, int32Ptr(1))
+ ctx := context.Background()
+
+ claimed, err := f.svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{f.runtimeID}, 8)
+ if err != nil {
+ t.Fatalf("ClaimTasksForRuntimes: %v", err)
+ }
+ if len(claimed) != 1 {
+ t.Fatalf("claimed %d tasks, want 1 under runtime cap 1", len(claimed))
+ }
+ if got := claimDecisionCount(t, f.metrics, claimPathBatch, claimOutcomeRuntimeNoCapacity, claimReasonRuntimeConcurrencyCap); got != 1 {
+ t.Fatalf("claim_decision_total{batch,runtime_no_capacity,runtime_concurrency_cap} = %v, want 1", got)
+ }
+
+ again, err := f.svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{f.runtimeID}, 8)
+ if err != nil {
+ t.Fatalf("second ClaimTasksForRuntimes: %v", err)
+ }
+ if len(again) != 0 {
+ t.Fatalf("second poll claimed %d tasks while the runtime is full, want 0", len(again))
+ }
+
+ if _, err := f.pool.Exec(ctx,
+ `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, claimed[0].ID,
+ ); err != nil {
+ t.Fatalf("complete first task: %v", err)
+ }
+ next, err := f.svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{f.runtimeID}, 8)
+ if err != nil {
+ t.Fatalf("third ClaimTasksForRuntimes: %v", err)
+ }
+ if len(next) != 1 {
+ t.Fatalf("after the slot freed, claimed %d tasks, want 1", len(next))
+ }
+ if next[0].AgentID == claimed[0].AgentID {
+ t.Fatalf("expected the other agent's task to be claimed next")
+ }
+}
+
+// No cap (NULL, the default for every existing runtime) keeps today's
+// behavior: each agent claims within its own limit.
+func TestRuntimeConcurrencyCapNullIsUnlimited(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+ f.insertTask(t, "queued")
+ f.addRuntimeAgentWithTask(t, "runtime-nocap-agent-b")
+
+ claimed, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)
+ if err != nil {
+ t.Fatalf("ClaimTasksForRuntimes: %v", err)
+ }
+ if len(claimed) != 2 {
+ t.Fatalf("claimed %d tasks, want 2 with no runtime cap", len(claimed))
+ }
+}
+
+// The count-then-claim window is serialized per runtime: while another
+// transaction holds the runtime claim lock and has an uncommitted task start,
+// a claim must wait for it and then see the slot as taken. Without the lock
+// the claim would not see the uncommitted row and would overshoot the cap.
+func TestRuntimeConcurrencyCapClaimWaitsForLockHolder(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+ f.insertTask(t, "queued")
+ otherTaskID := f.addRuntimeAgentWithTask(t, "runtime-lock-agent-b")
+ f.setRuntimeCap(t, int32Ptr(1))
+ ctx := context.Background()
+
+ tx, err := f.pool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ defer tx.Rollback(ctx)
+ if err := db.New(tx).LockRuntimeClaimCapacity(ctx, f.runtimeID); err != nil {
+ t.Fatalf("lock: %v", err)
+ }
+ if _, err := tx.Exec(ctx,
+ `UPDATE agent_task_queue SET status = 'running', dispatched_at = now(), started_at = now() WHERE id = $1`,
+ util.MustParseUUID(otherTaskID),
+ ); err != nil {
+ t.Fatalf("start other task in tx: %v", err)
+ }
+
+ type result struct {
+ task *db.AgentTaskQueue
+ err error
+ }
+ done := make(chan result, 1)
+ go func() {
+ task, err := f.svc.ClaimTask(ctx, f.agentID)
+ done <- result{task, err}
+ }()
+
+ select {
+ case r := <-done:
+ t.Fatalf("claim returned (claimed=%v, err=%v) while another transaction held the runtime claim lock", r.task != nil, r.err)
+ case <-time.After(300 * time.Millisecond):
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatalf("commit: %v", err)
+ }
+ select {
+ case r := <-done:
+ if r.err != nil {
+ t.Fatalf("ClaimTask: %v", r.err)
+ }
+ if r.task != nil {
+ t.Fatalf("claimed %s although the runtime was full", util.UUIDToString(r.task.ID))
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("claim did not finish after the lock holder committed")
+ }
+}
+
+// Regression for review on #9795: a claim queued behind the runtime lock
+// must use the cap that is current when it gets the lock, not the value it
+// would have read before waiting. Cap 2 with one task running; a claim waits
+// on the lock; the cap is lowered to 1 and saved; the claim must then refuse.
+func TestRuntimeConcurrencyCapLoweredWhileClaimWaits(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+ f.insertTask(t, "running")
+ otherTaskID := f.addRuntimeAgentWithTask(t, "runtime-lowered-agent")
+ f.setRuntimeCap(t, int32Ptr(2))
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ var otherAgentID pgtype.UUID
+ if err := f.pool.QueryRow(ctx, `SELECT agent_id FROM agent_task_queue WHERE id = $1`, otherTaskID).Scan(&otherAgentID); err != nil {
+ t.Fatalf("load other agent: %v", err)
+ }
+
+ tx, err := f.pool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ defer tx.Rollback(context.Background())
+ if err := db.New(tx).LockRuntimeClaimCapacity(ctx, f.runtimeID); err != nil {
+ t.Fatalf("lock: %v", err)
+ }
+
+ type result struct {
+ task *db.AgentTaskQueue
+ err error
+ }
+ done := make(chan result, 1)
+ go func() {
+ task, err := f.svc.ClaimTask(ctx, otherAgentID)
+ done <- result{task, err}
+ }()
+ waitForAdvisoryLockWaiter(ctx, t, f)
+
+ // Same query PATCH uses; the save completes while the claim is queued.
+ if _, err := db.New(f.pool).UpdateAgentRuntimeMaxConcurrentTasks(ctx, db.UpdateAgentRuntimeMaxConcurrentTasksParams{
+ ID: f.runtimeID, MaxConcurrentTasks: pgtype.Int4{Int32: 1, Valid: true},
+ }); err != nil {
+ t.Fatalf("lower cap: %v", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatalf("commit: %v", err)
+ }
+
+ select {
+ case r := <-done:
+ if r.err != nil {
+ t.Fatalf("ClaimTask: %v", r.err)
+ }
+ if r.task != nil {
+ t.Fatal("dispatched a second task after cap=1 was saved while one task was running")
+ }
+ case <-ctx.Done():
+ t.Fatal(ctx.Err())
+ }
+}
+
+// waitForAdvisoryLockWaiter blocks until some session in this database is
+// waiting on an advisory lock, i.e. the claim under test is queued.
+func waitForAdvisoryLockWaiter(ctx context.Context, t *testing.T, f *claimDecisionFixture) {
+ t.Helper()
+ for {
+ var waiting bool
+ if err := f.pool.QueryRow(ctx, `SELECT EXISTS (
+ SELECT 1 FROM pg_locks
+ WHERE locktype = 'advisory' AND NOT granted
+ AND database = (SELECT oid FROM pg_database WHERE datname = current_database()))`).Scan(&waiting); err != nil {
+ t.Fatalf("poll pg_locks: %v", err)
+ }
+ if waiting {
+ return
+ }
+ select {
+ case <-ctx.Done():
+ t.Fatal("claim did not wait on the runtime lock")
+ case <-time.After(10 * time.Millisecond):
+ }
+ }
+}
+
+// Concurrent claims from different agents must not overshoot the cap.
+func TestRuntimeConcurrencyCapConcurrentClaims(t *testing.T) {
+ f := newClaimDecisionFixture(t, 5)
+ f.insertTask(t, "queued")
+ const extraAgents = 5
+ for i := 0; i < extraAgents; i++ {
+ f.addRuntimeAgentWithTask(t, "runtime-race-agent-"+string(rune('a'+i)))
+ }
+ f.setRuntimeCap(t, int32Ptr(2))
+
+ var (
+ wg sync.WaitGroup
+ mu sync.Mutex
+ total int
+ errs []error
+ )
+ for i := 0; i < extraAgents+1; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ task, err := f.svc.ClaimTaskForRuntime(context.Background(), f.runtimeID)
+ mu.Lock()
+ defer mu.Unlock()
+ if err != nil {
+ errs = append(errs, err)
+ return
+ }
+ if task != nil {
+ total++
+ }
+ }()
+ }
+ wg.Wait()
+ if len(errs) > 0 {
+ t.Fatalf("concurrent claims returned errors: %v", errs)
+ }
+
+ var active int64
+ if err := f.pool.QueryRow(context.Background(),
+ `SELECT count(*) FROM agent_task_queue WHERE runtime_id = $1 AND status IN ('dispatched','running','waiting_local_directory')`,
+ f.runtimeID,
+ ).Scan(&active); err != nil {
+ t.Fatalf("count active: %v", err)
+ }
+ if active > 2 {
+ t.Fatalf("runtime has %d active tasks, cap is 2", active)
+ }
+ if total > 2 {
+ t.Fatalf("claimed %d tasks concurrently, cap is 2", total)
+ }
+}
diff --git a/server/migrations/605_agent_runtime_max_concurrent_tasks.down.sql b/server/migrations/605_agent_runtime_max_concurrent_tasks.down.sql
new file mode 100644
index 0000000000..33156be23a
--- /dev/null
+++ b/server/migrations/605_agent_runtime_max_concurrent_tasks.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_runtime DROP COLUMN IF EXISTS max_concurrent_tasks;
diff --git a/server/migrations/605_agent_runtime_max_concurrent_tasks.up.sql b/server/migrations/605_agent_runtime_max_concurrent_tasks.up.sql
new file mode 100644
index 0000000000..c5ee52ddd4
--- /dev/null
+++ b/server/migrations/605_agent_runtime_max_concurrent_tasks.up.sql
@@ -0,0 +1,15 @@
+-- Optional runtime-wide concurrency cap (GitHub #9626, #7015). An agent's
+-- max_concurrent_tasks only bounds that agent; several agents bound to the
+-- same runtime can still run at the same time. When set, the claim path also
+-- refuses work once the runtime has this many dispatched / running /
+-- waiting_local_directory tasks across all of its agents.
+--
+-- NULL means "no runtime cap", so every existing row keeps today's behavior.
+-- Range (1..50) is validated in the handler, matching the agent limit; there
+-- is no CHECK constraint so the ALTER stays a catalog-only change with no
+-- table scan. Not written by the registration / heartbeat upserts, so a daemon
+-- restart never clears it.
+--
+-- No index on this column: it is read by primary key only. The per-runtime
+-- running count is served by idx_agent_task_queue_runtime_active (606).
+ALTER TABLE agent_runtime ADD COLUMN IF NOT EXISTS max_concurrent_tasks INTEGER;
diff --git a/server/migrations/606_agent_task_queue_runtime_active_index.down.sql b/server/migrations/606_agent_task_queue_runtime_active_index.down.sql
new file mode 100644
index 0000000000..980eb49bca
--- /dev/null
+++ b/server/migrations/606_agent_task_queue_runtime_active_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_runtime_active;
diff --git a/server/migrations/606_agent_task_queue_runtime_active_index.up.sql b/server/migrations/606_agent_task_queue_runtime_active_index.up.sql
new file mode 100644
index 0000000000..7144458158
--- /dev/null
+++ b/server/migrations/606_agent_task_queue_runtime_active_index.up.sql
@@ -0,0 +1,14 @@
+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction
+-- or share a multi-command migration file.
+--
+-- Serves CountActiveTasksByRuntime, the runtime-wide concurrency cap check
+-- (GitHub #9626) that runs on every claim for a runtime with a cap set. The
+-- (runtime_id, id) index from migration 273 has no status column, so that
+-- count had to read every historical task row on the runtime and filter by
+-- status; cost grew with the runtime's history while the claim held the agent
+-- row lock and the runtime claim lock. Partial on the capacity-bearing
+-- statuses, so it only holds the few in-flight rows per runtime and stays
+-- small no matter how much history accumulates.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_runtime_active
+ ON agent_task_queue (runtime_id)
+ WHERE status IN ('dispatched', 'running', 'waiting_local_directory');
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 464bf0ed09..613baf2cb5 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -81,24 +81,25 @@ type AgentMcpServer struct {
}
type AgentRuntime struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- DaemonID pgtype.Text `json:"daemon_id"`
- Name string `json:"name"`
- RuntimeMode string `json:"runtime_mode"`
- Provider string `json:"provider"`
- Status string `json:"status"`
- DeviceInfo string `json:"device_info"`
- Metadata []byte `json:"metadata"`
- LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- OwnerID pgtype.UUID `json:"owner_id"`
- LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`
- Visibility string `json:"visibility"`
- ProfileID pgtype.UUID `json:"profile_id"`
- CustomName pgtype.Text `json:"custom_name"`
- SharedWith []pgtype.UUID `json:"shared_with"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DaemonID pgtype.Text `json:"daemon_id"`
+ Name string `json:"name"`
+ RuntimeMode string `json:"runtime_mode"`
+ Provider string `json:"provider"`
+ Status string `json:"status"`
+ DeviceInfo string `json:"device_info"`
+ Metadata []byte `json:"metadata"`
+ LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+ LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`
+ Visibility string `json:"visibility"`
+ ProfileID pgtype.UUID `json:"profile_id"`
+ CustomName pgtype.Text `json:"custom_name"`
+ SharedWith []pgtype.UUID `json:"shared_with"`
+ MaxConcurrentTasks pgtype.Int4 `json:"max_concurrent_tasks"`
}
type AgentSkill struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 2011025936..924b4afcc2 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -254,6 +254,21 @@ func (q *Queries) CountActiveAgentsByRuntime(ctx context.Context, runtimeID pgty
return count, err
}
+const countActiveTasksByRuntime = `-- name: CountActiveTasksByRuntime :one
+SELECT count(*) FROM agent_task_queue
+WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
+`
+
+// Capacity-bearing tasks on a runtime across all agents. Same status set as
+// CountRunningTasks (per agent). Served by the partial index
+// idx_agent_task_queue_runtime_active (migration 606).
+func (q *Queries) CountActiveTasksByRuntime(ctx context.Context, runtimeID pgtype.UUID) (int64, error) {
+ row := q.db.QueryRow(ctx, countActiveTasksByRuntime, runtimeID)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
const countTasksByRuntime = `-- name: CountTasksByRuntime :one
SELECT count(*) FROM agent_task_queue WHERE runtime_id = $1
`
@@ -432,7 +447,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context, arg FailTasks
}
const findLegacyRuntimesByDaemonID = `-- name: FindLegacyRuntimesByDaemonID :many
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks FROM agent_runtime
WHERE workspace_id = $1
AND provider = $2
AND LOWER(daemon_id) = LOWER($3)
@@ -487,6 +502,7 @@ func (q *Queries) FindLegacyRuntimesByDaemonID(ctx context.Context, arg FindLega
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
); err != nil {
return nil, err
}
@@ -546,7 +562,7 @@ func (q *Queries) ForceOfflineRuntimesByIDs(ctx context.Context, runtimeIds []pg
}
const getAgentRuntime = `-- name: GetAgentRuntime :one
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks FROM agent_runtime
WHERE id = $1
`
@@ -572,12 +588,13 @@ func (q *Queries) GetAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRun
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
)
return i, err
}
const getAgentRuntimeForWorkspace = `-- name: GetAgentRuntimeForWorkspace :one
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks FROM agent_runtime
WHERE id = $1 AND workspace_id = $2
`
@@ -608,6 +625,7 @@ func (q *Queries) GetAgentRuntimeForWorkspace(ctx context.Context, arg GetAgentR
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
)
return i, err
}
@@ -661,8 +679,22 @@ func (q *Queries) GetAgentRuntimeHeartbeatLeases(ctx context.Context, ids []pgty
return items, nil
}
+const getAgentRuntimeMaxConcurrentTasks = `-- name: GetAgentRuntimeMaxConcurrentTasks :one
+SELECT max_concurrent_tasks FROM agent_runtime
+WHERE id = $1
+`
+
+// Claim-path read of the runtime cap. Plain read (no row lock), always made
+// after LockRuntimeClaimCapacity so it sees the latest committed value.
+func (q *Queries) GetAgentRuntimeMaxConcurrentTasks(ctx context.Context, id pgtype.UUID) (pgtype.Int4, error) {
+ row := q.db.QueryRow(ctx, getAgentRuntimeMaxConcurrentTasks, id)
+ var max_concurrent_tasks pgtype.Int4
+ err := row.Scan(&max_concurrent_tasks)
+ return max_concurrent_tasks, err
+}
+
const getAgentRuntimes = `-- name: GetAgentRuntimes :many
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks FROM agent_runtime
WHERE id = ANY($1::uuid[])
`
@@ -699,6 +731,7 @@ func (q *Queries) GetAgentRuntimes(ctx context.Context, ids []pgtype.UUID) ([]Ag
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
); err != nil {
return nil, err
}
@@ -769,7 +802,7 @@ func (q *Queries) ListAgentRuntimeIDsByWorkspace(ctx context.Context, workspaceI
}
const listAgentRuntimes = `-- name: ListAgentRuntimes :many
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks FROM agent_runtime
WHERE workspace_id = $1
ORDER BY created_at ASC
`
@@ -802,6 +835,7 @@ func (q *Queries) ListAgentRuntimes(ctx context.Context, workspaceID pgtype.UUID
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
); err != nil {
return nil, err
}
@@ -814,7 +848,7 @@ func (q *Queries) ListAgentRuntimes(ctx context.Context, workspaceID pgtype.UUID
}
const listAgentRuntimesByOwner = `-- name: ListAgentRuntimesByOwner :many
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks FROM agent_runtime
WHERE workspace_id = $1 AND owner_id = $2
ORDER BY created_at ASC
`
@@ -852,6 +886,7 @@ func (q *Queries) ListAgentRuntimesByOwner(ctx context.Context, arg ListAgentRun
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
); err != nil {
return nil, err
}
@@ -1143,7 +1178,7 @@ func (q *Queries) ListRuntimeOwnersByDaemon(ctx context.Context, arg ListRuntime
}
const listSharedAgentRuntimesForUpdate = `-- name: ListSharedAgentRuntimesForUpdate :many
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks FROM agent_runtime
WHERE workspace_id = $1 AND $2::uuid = ANY(shared_with)
ORDER BY id
FOR NO KEY UPDATE
@@ -1182,6 +1217,7 @@ func (q *Queries) ListSharedAgentRuntimesForUpdate(ctx context.Context, arg List
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
); err != nil {
return nil, err
}
@@ -1245,7 +1281,7 @@ func (q *Queries) ListStaleOfflineRuntimeGCCandidates(ctx context.Context, arg L
}
const listVisibleAgentRuntimes = `-- name: ListVisibleAgentRuntimes :many
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks FROM agent_runtime
WHERE workspace_id = $1
AND (owner_id = $2 OR visibility = 'public' OR (visibility = 'private' AND $2 = ANY(shared_with)))
ORDER BY created_at ASC
@@ -1287,6 +1323,7 @@ func (q *Queries) ListVisibleAgentRuntimes(ctx context.Context, arg ListVisibleA
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
); err != nil {
return nil, err
}
@@ -1299,7 +1336,7 @@ func (q *Queries) ListVisibleAgentRuntimes(ctx context.Context, arg ListVisibleA
}
const lockAgentRuntime = `-- name: LockAgentRuntime :one
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with FROM agent_runtime
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks FROM agent_runtime
WHERE id = $1
FOR UPDATE
`
@@ -1339,12 +1376,13 @@ func (q *Queries) LockAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRu
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
)
return i, err
}
const lockAgentRuntimeForAccessChange = `-- name: LockAgentRuntimeForAccessChange :one
-SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with FROM agent_runtime WHERE id = $1 FOR NO KEY UPDATE
+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks FROM agent_runtime WHERE id = $1 FOR NO KEY UPDATE
`
// Binding and visibility writers share this lock and recheck access under it.
@@ -1372,10 +1410,30 @@ func (q *Queries) LockAgentRuntimeForAccessChange(ctx context.Context, id pgtype
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
)
return i, err
}
+const lockRuntimeClaimCapacity = `-- name: LockRuntimeClaimCapacity :exec
+SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':runtime_claim_capacity', 0))
+`
+
+// Transaction-scoped advisory lock that serializes claims on one runtime
+// with each other and with cap updates, so two agents claiming concurrently
+// cannot both see running < cap, and no claim commits against a cap that a
+// finished update already replaced. An advisory lock (not FOR UPDATE on the
+// runtime row) because claimTask already holds the agent row lock, while
+// runtime teardown / access changes lock the runtime row first and then
+// agent rows; taking the runtime row here would invert that order and risk
+// a deadlock. Lock order: claims take agent row -> this lock; cap updates
+// take runtime row (FOR NO KEY UPDATE) -> this lock. A claim never waits on
+// the runtime row, so the two cannot form a cycle.
+func (q *Queries) LockRuntimeClaimCapacity(ctx context.Context, runtimeID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, lockRuntimeClaimCapacity, runtimeID)
+ return err
+}
+
const lockRuntimeRevocationChatSessions = `-- name: LockRuntimeRevocationChatSessions :many
SELECT cs.id FROM chat_session cs
WHERE EXISTS (
@@ -1547,7 +1605,7 @@ const markAgentRuntimeOnline = `-- name: MarkAgentRuntimeOnline :one
UPDATE agent_runtime
SET status = 'online', last_seen_at = now(), updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks
`
// Used on the offline→online transition (and on first heartbeat after
@@ -1575,6 +1633,7 @@ func (q *Queries) MarkAgentRuntimeOnline(ctx context.Context, id pgtype.UUID) (A
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
)
return i, err
}
@@ -2049,7 +2108,7 @@ const updateAgentRuntimeCustomName = `-- name: UpdateAgentRuntimeCustomName :one
UPDATE agent_runtime
SET custom_name = $1, updated_at = now()
WHERE id = $2
-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks
`
type UpdateAgentRuntimeCustomNameParams struct {
@@ -2084,6 +2143,7 @@ func (q *Queries) UpdateAgentRuntimeCustomName(ctx context.Context, arg UpdateAg
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
)
return i, err
}
@@ -2094,7 +2154,7 @@ SET custom_name = $1, updated_at = now()
WHERE workspace_id = $2
AND daemon_id = $3
AND ($4::uuid IS NULL OR owner_id = $4)
-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks
`
type UpdateAgentRuntimeCustomNameByDaemonParams struct {
@@ -2143,6 +2203,7 @@ func (q *Queries) UpdateAgentRuntimeCustomNameByDaemon(ctx context.Context, arg
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
); err != nil {
return nil, err
}
@@ -2154,11 +2215,56 @@ func (q *Queries) UpdateAgentRuntimeCustomNameByDaemon(ctx context.Context, arg
return items, nil
}
+const updateAgentRuntimeMaxConcurrentTasks = `-- name: UpdateAgentRuntimeMaxConcurrentTasks :one
+UPDATE agent_runtime
+SET max_concurrent_tasks = $1, updated_at = now()
+WHERE id = $2
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks
+`
+
+type UpdateAgentRuntimeMaxConcurrentTasksParams struct {
+ MaxConcurrentTasks pgtype.Int4 `json:"max_concurrent_tasks"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// Sets or clears (NULL) the runtime-wide concurrency cap (GitHub #9626).
+// Kept out of the registration upserts so a daemon re-registering never
+// clobbers it. Gated at the handler to runtime owner / workspace admin.
+// The handler runs this and then LockRuntimeClaimCapacity in one
+// transaction, so the new value commits only after every in-flight claim
+// on the runtime has finished.
+func (q *Queries) UpdateAgentRuntimeMaxConcurrentTasks(ctx context.Context, arg UpdateAgentRuntimeMaxConcurrentTasksParams) (AgentRuntime, error) {
+ row := q.db.QueryRow(ctx, updateAgentRuntimeMaxConcurrentTasks, arg.MaxConcurrentTasks, arg.ID)
+ var i AgentRuntime
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.DaemonID,
+ &i.Name,
+ &i.RuntimeMode,
+ &i.Provider,
+ &i.Status,
+ &i.DeviceInfo,
+ &i.Metadata,
+ &i.LastSeenAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.OwnerID,
+ &i.LegacyDaemonID,
+ &i.Visibility,
+ &i.ProfileID,
+ &i.CustomName,
+ &i.SharedWith,
+ &i.MaxConcurrentTasks,
+ )
+ return i, err
+}
+
const updateAgentRuntimeVisibility = `-- name: UpdateAgentRuntimeVisibility :one
UPDATE agent_runtime
SET visibility = $1, shared_with = $2::uuid[], updated_at = now()
WHERE id = $3
-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks
`
type UpdateAgentRuntimeVisibilityParams struct {
@@ -2194,6 +2300,7 @@ func (q *Queries) UpdateAgentRuntimeVisibility(ctx context.Context, arg UpdateAg
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
)
return i, err
}
@@ -2226,7 +2333,7 @@ DO UPDATE SET
updated_at = now()
WHERE $10::uuid IS NULL
OR agent_runtime.owner_id = $10::uuid
-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, (xmax = 0) AS inserted
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks, (xmax = 0) AS inserted
`
type UpsertAgentRuntimeParams struct {
@@ -2243,25 +2350,26 @@ type UpsertAgentRuntimeParams struct {
}
type UpsertAgentRuntimeRow struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- DaemonID pgtype.Text `json:"daemon_id"`
- Name string `json:"name"`
- RuntimeMode string `json:"runtime_mode"`
- Provider string `json:"provider"`
- Status string `json:"status"`
- DeviceInfo string `json:"device_info"`
- Metadata []byte `json:"metadata"`
- LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- OwnerID pgtype.UUID `json:"owner_id"`
- LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`
- Visibility string `json:"visibility"`
- ProfileID pgtype.UUID `json:"profile_id"`
- CustomName pgtype.Text `json:"custom_name"`
- SharedWith []pgtype.UUID `json:"shared_with"`
- Inserted bool `json:"inserted"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DaemonID pgtype.Text `json:"daemon_id"`
+ Name string `json:"name"`
+ RuntimeMode string `json:"runtime_mode"`
+ Provider string `json:"provider"`
+ Status string `json:"status"`
+ DeviceInfo string `json:"device_info"`
+ Metadata []byte `json:"metadata"`
+ LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+ LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`
+ Visibility string `json:"visibility"`
+ ProfileID pgtype.UUID `json:"profile_id"`
+ CustomName pgtype.Text `json:"custom_name"`
+ SharedWith []pgtype.UUID `json:"shared_with"`
+ MaxConcurrentTasks pgtype.Int4 `json:"max_concurrent_tasks"`
+ Inserted bool `json:"inserted"`
}
// (xmax = 0) AS inserted distinguishes a fresh insert (true) from an upsert
@@ -2312,6 +2420,7 @@ func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntime
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
&i.Inserted,
)
return i, err
@@ -2347,7 +2456,7 @@ DO UPDATE SET
updated_at = now()
WHERE $11::uuid IS NULL
OR agent_runtime.owner_id = $11::uuid
-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, (xmax = 0) AS inserted
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, shared_with, max_concurrent_tasks, (xmax = 0) AS inserted
`
type UpsertAgentRuntimeWithProfileParams struct {
@@ -2365,25 +2474,26 @@ type UpsertAgentRuntimeWithProfileParams struct {
}
type UpsertAgentRuntimeWithProfileRow struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- DaemonID pgtype.Text `json:"daemon_id"`
- Name string `json:"name"`
- RuntimeMode string `json:"runtime_mode"`
- Provider string `json:"provider"`
- Status string `json:"status"`
- DeviceInfo string `json:"device_info"`
- Metadata []byte `json:"metadata"`
- LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- OwnerID pgtype.UUID `json:"owner_id"`
- LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`
- Visibility string `json:"visibility"`
- ProfileID pgtype.UUID `json:"profile_id"`
- CustomName pgtype.Text `json:"custom_name"`
- SharedWith []pgtype.UUID `json:"shared_with"`
- Inserted bool `json:"inserted"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DaemonID pgtype.Text `json:"daemon_id"`
+ Name string `json:"name"`
+ RuntimeMode string `json:"runtime_mode"`
+ Provider string `json:"provider"`
+ Status string `json:"status"`
+ DeviceInfo string `json:"device_info"`
+ Metadata []byte `json:"metadata"`
+ LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+ LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`
+ Visibility string `json:"visibility"`
+ ProfileID pgtype.UUID `json:"profile_id"`
+ CustomName pgtype.Text `json:"custom_name"`
+ SharedWith []pgtype.UUID `json:"shared_with"`
+ MaxConcurrentTasks pgtype.Int4 `json:"max_concurrent_tasks"`
+ Inserted bool `json:"inserted"`
}
// Custom-runtime registration: a daemon resolved a workspace runtime_profile's
@@ -2428,6 +2538,7 @@ func (q *Queries) UpsertAgentRuntimeWithProfile(ctx context.Context, arg UpsertA
&i.ProfileID,
&i.CustomName,
&i.SharedWith,
+ &i.MaxConcurrentTasks,
&i.Inserted,
)
return i, err
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index 25fb913d09..82c86103a4 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -686,3 +686,41 @@ SELECT * FROM agent_runtime
WHERE workspace_id = @workspace_id AND @user_id::uuid = ANY(shared_with)
ORDER BY id
FOR NO KEY UPDATE;
+
+-- name: UpdateAgentRuntimeMaxConcurrentTasks :one
+-- Sets or clears (NULL) the runtime-wide concurrency cap (GitHub #9626).
+-- Kept out of the registration upserts so a daemon re-registering never
+-- clobbers it. Gated at the handler to runtime owner / workspace admin.
+-- The handler runs this and then LockRuntimeClaimCapacity in one
+-- transaction, so the new value commits only after every in-flight claim
+-- on the runtime has finished.
+UPDATE agent_runtime
+SET max_concurrent_tasks = sqlc.narg('max_concurrent_tasks'), updated_at = now()
+WHERE id = @id
+RETURNING *;
+
+-- name: GetAgentRuntimeMaxConcurrentTasks :one
+-- Claim-path read of the runtime cap. Plain read (no row lock), always made
+-- after LockRuntimeClaimCapacity so it sees the latest committed value.
+SELECT max_concurrent_tasks FROM agent_runtime
+WHERE id = $1;
+
+-- name: LockRuntimeClaimCapacity :exec
+-- Transaction-scoped advisory lock that serializes claims on one runtime
+-- with each other and with cap updates, so two agents claiming concurrently
+-- cannot both see running < cap, and no claim commits against a cap that a
+-- finished update already replaced. An advisory lock (not FOR UPDATE on the
+-- runtime row) because claimTask already holds the agent row lock, while
+-- runtime teardown / access changes lock the runtime row first and then
+-- agent rows; taking the runtime row here would invert that order and risk
+-- a deadlock. Lock order: claims take agent row -> this lock; cap updates
+-- take runtime row (FOR NO KEY UPDATE) -> this lock. A claim never waits on
+-- the runtime row, so the two cannot form a cycle.
+SELECT pg_advisory_xact_lock(hashtextextended(sqlc.arg('runtime_id')::uuid::text || ':runtime_claim_capacity', 0));
+
+-- name: CountActiveTasksByRuntime :one
+-- Capacity-bearing tasks on a runtime across all agents. Same status set as
+-- CountRunningTasks (per agent). Served by the partial index
+-- idx_agent_task_queue_runtime_active (migration 606).
+SELECT count(*) FROM agent_task_queue
+WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory');