Troubleshoot hosted agents on your own AKS cluster

Use this guide to diagnose and resolve common issues when deploying and operating Microsoft Foundry hosted agents on your own Azure Kubernetes Service (AKS) cluster (bring your own AKS / BYO AKS).

Prerequisites

  • Azure CLI authenticated to your Azure subscription (az login).
  • kubectl configured to target the affected AKS cluster.
  • Read access to the Foundry Account, AKS cluster, Storage Account, and Managed Identities.

Gather diagnostic context

Before investigating a specific symptom, set your target resource variables and confirm that kubectl points to the right cluster:

SUBSCRIPTION_ID="<YOUR_SUBSCRIPTION_ID>"
RESOURCE_GROUP="<YOUR_RESOURCE_GROUP>"
ACCOUNT_NAME="<YOUR_FOUNDRY_ACCOUNT_NAME>"
AKS_RG="<YOUR_AKS_RESOURCE_GROUP>"
AKS_NAME="<YOUR_AKS_CLUSTER_NAME>"
STORAGE_ACCOUNT_NAME="<YOUR_STORAGE_ACCOUNT_NAME>"

ACCOUNT_ID="/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.CognitiveServices/accounts/${ACCOUNT_NAME}"
AKS_ID="/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${AKS_RG}/providers/Microsoft.ContainerService/managedClusters/${AKS_NAME}"
SA_ID="/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.Storage/storageAccounts/${STORAGE_ACCOUNT_NAME}"

# Verify kubectl points to the intended AKS cluster
kubectl config current-context

1. Account provisioning and cluster readiness failures

Symptoms:

  • Creating a Foundry Account with agentHostingConfigurations fails or times out.
  • Errors mention AKS prerequisites, Managed Identity permissions, federated credentials, Trusted Access, Storage access, or Pod scheduling failures.

If provisioning or an update fails with one of the following error messages, apply the matching fix. For other errors, work through the checks in this section.

Error message Fix
The Foundry account, AKS managed cluster, and Storage account must be in the same subscription. Use an AKS cluster and a storage account in the Foundry account's subscription.
The AKS cluster must be in the same region as the Foundry account. Create the Foundry account in the AKS cluster's region.
The AKS cluster does not expose an OIDC issuer. or The AKS cluster must have the OIDC issuer enabled. Enable the OIDC issuer on the AKS cluster.
The AKS cluster must have Workload Identity enabled. Enable Workload Identity on the AKS cluster.
The AKS cluster must use Azure CNI Overlay or Azure CNI Pod Subnet networking. Use Azure CNI Overlay, or Azure CNI with a podSubnetId configured on every node pool.
The AKS cluster must have an agent pool configured with workloadRuntime=KataVmIsolation. Add a node pool with workloadRuntime set to KataVmIsolation. See AKS and node pool requirements.
A KataVmIsolation agent pool must have node label agents.ai.azure.com/sandbox-node=true. Set the node label agents.ai.azure.com/sandbox-node=true on a KataVmIsolation node pool.
hostingManagementIdentityResourceId must reference a user-assigned identity attached to the Foundry account. Attach the hosting-management identity to the Foundry account in identity.userAssignedIdentities.
hostingManagementIdentityResourceId and workloadIdentityResourceId must reference different user-assigned identities. Use two different user-assigned managed identities.
The hosting-management identity is not authorized to read the configured AKS cluster. Assign the Reader role on the AKS cluster to the hosting-management identity.
The hosting-management identity is not authorized to manage federated identity credentials on the configured workload identity. Assign the Managed Identity Federated Identity Credential Contributor role on the workload identity to the hosting-management identity.
The configured workload identity contains a conflicting federated identity credential. Remove the existing credential and retry provisioning. Remove the conflicting federated identity credential from the workload identity, and then retry.
Updating or removing agentHostingConfigurations is not supported. or agentHostingConfigurations cannot be updated using PATCH. You can't change or remove the hosting configuration of an existing Foundry account. To use a different cluster, identity, or storage account, create a new Foundry account.
agentHostingConfigurations requires api-version 2026-07-15-preview or later. Use API version 2026-07-15-preview or later.

1.1 Verify AKS cluster and node pool prerequisites

Confirm your AKS cluster meets all BYO AKS requirements:

az aks show --ids "$AKS_ID" \
  --query "{location:location,provisioningState:provisioningState,powerState:powerState.code,oidc:oidcIssuerProfile,workloadIdentity:securityProfile.workloadIdentity,networkPlugin:networkProfile.networkPlugin,networkPluginMode:networkProfile.networkPluginMode,serviceCidr:networkProfile.serviceCidr}" \
  --output json

az aks nodepool list --subscription "$SUBSCRIPTION_ID" \
  --resource-group "$AKS_RG" --cluster-name "$AKS_NAME" \
  --query "[].{name:name,state:provisioningState,powerState:powerState.code,count:count,vmSize:vmSize,workloadRuntime:workloadRuntime,nodeLabels:nodeLabels,podSubnetId:podSubnetId,enableAutoScaling:enableAutoScaling,maxCount:maxCount,maxPods:maxPods}" \
  --output json

Verify the following requirements:

  • Region & Subscription: Your AKS cluster and storage account must be in the same subscription as the Foundry account. Your AKS cluster must also be in the same region as the Foundry account.
  • Power state: The AKS cluster and node pools must be Running (Succeeded).
  • OIDC & Workload Identity: Both oidcIssuerProfile.enabled (with a non-empty issuerUrl) and securityProfile.workloadIdentity.enabled must be true.
  • Networking & Service CIDR: Use Azure CNI Overlay, or Azure CNI with a podSubnetId configured on every node pool. For this preview, configure your Kubernetes IPv4 Service CIDR so it doesn't overlap RFC 6598 Shared Address Space or IPv4 link-local addresses (169.254.0.0/16).
  • Kata node pool: At least one node pool must have workloadRuntime: "KataVmIsolation" and the node label agents.ai.azure.com/sandbox-node=true.

1.2 Verify Managed Identities and RBAC

BYO AKS requires two distinct user-assigned managed identities (UAMIs):

  1. Hosting-management identity: Attached to the Foundry Account (identity.userAssignedIdentities) to manage the AKS extension and federated credentials.
  2. Workload identity: Used at runtime by system components in foundry-system to access your Storage Account. Do not attach the workload identity to the Foundry Account.

Verify role assignments for both identities:

MGMT_PRINCIPAL_ID="<HOSTING_MANAGEMENT_MI_PRINCIPAL_ID>"
WORKLOAD_PRINCIPAL_ID="<WORKLOAD_MI_PRINCIPAL_ID>"
WORKLOAD_MI_ID="<WORKLOAD_MI_ARM_ID>"

# Hosting-management MI on AKS (requires Kubernetes Extension Contributor + Reader)
az role assignment list --assignee-object-id "$MGMT_PRINCIPAL_ID" --scope "$AKS_ID" \
  --include-inherited --query "[].{role:roleDefinitionName,scope:scope}" --output table

# Hosting-management MI on Workload MI (requires Managed Identity Federated Identity Credential Contributor + Read)
az role assignment list --assignee-object-id "$MGMT_PRINCIPAL_ID" --scope "$WORKLOAD_MI_ID" \
  --include-inherited --query "[].{role:roleDefinitionName,scope:scope}" --output table

# Workload MI on Storage Account (requires Storage Blob Data Contributor)
az role assignment list --assignee-object-id "$WORKLOAD_PRINCIPAL_ID" --scope "$SA_ID" \
  --include-inherited --query "[].{role:roleDefinitionName,scope:scope}" --output table

Also ensure the user or service principal creating the Foundry Account has Microsoft.ContainerService/managedClusters/write, Microsoft.ManagedIdentity/userAssignedIdentities/federatedIdentityCredentials/write, Microsoft.Storage/storageAccounts/write, and Microsoft.ManagedIdentity/userAssignedIdentities/assign/action (on the hosting-management identity).

1.3 Verify Storage network reachability from AKS

A common provisioning failure is Storage returning 403 during runtime initialization because AKS can't reach the Blob endpoint.

az storage account show --ids "$SA_ID" \
  --query "{publicNetworkAccess:publicNetworkAccess,defaultAction:networkRuleSet.defaultAction,privateEndpoints:privateEndpointConnections[].properties.privateLinkServiceConnectionState.status,blobEndpoint:primaryEndpoints.blob,allowBlobPublicAccess:allowBlobPublicAccess}" \
  --output json
Storage setting What to verify
publicNetworkAccess: Disabled Verify an approved Blob Private Endpoint exists in a reachable VNet/subnet and that DNS inside AKS resolves <storage>.blob.core.windows.net to the private IP.
publicNetworkAccess: Enabled, defaultAction: Deny Verify the AKS egress public IP is allowlisted or the effective AKS subnet has a Storage service endpoint and matching virtual network rule.
allowBlobPublicAccess: false Disables anonymous Blob access only. It doesn't block workload identity authentication. Don't enable anonymous access as a workaround.

Test DNS and HTTPS reachability directly from a running pod in foundry-system (workstation tests don't validate AKS network paths):

BLOB_ENDPOINT=$(az storage account show --ids "$SA_ID" --query primaryEndpoints.blob --output tsv)
BLOB_HOST=${BLOB_ENDPOINT#https://}; BLOB_HOST=${BLOB_HOST%%/*}
CONTROLLER_POD=$(kubectl get pods -n foundry-system -l app.kubernetes.io/component=controller -o jsonpath='{.items[0].metadata.name}')

kubectl exec -n foundry-system "$CONTROLLER_POD" -- getent hosts "$BLOB_HOST"
kubectl exec -n foundry-system "$CONTROLLER_POD" -- curl -I --connect-timeout 5 "$BLOB_ENDPOINT"

1.4 Verify AKS capacity and pod scheduling

Check whether foundry-system pods are stuck in Pending:

kubectl get pods -n foundry-system -o wide
kubectl get events -n foundry-system --sort-by=.lastTimestamp

If pods report FailedScheduling (Insufficient cpu, Insufficient memory, or Too many pods):

  • Confirm your eligible node pools have available capacity or autoscaling headroom (maxCount).
  • Check regional VM family quota if scale-out fails:
LOCATION=$(az aks show --ids "$AKS_ID" --query location --output tsv)
az vm list-usage --subscription "$SUBSCRIPTION_ID" --location "$LOCATION" --output table

2. Inbound networking and ingress connectivity

Symptoms:

  • Agent invocations fail before reaching your container with connection timeouts, TLS errors, or 502/503/504 gateway errors.

2.1 Verify Azure VNet, NSG, UDR, and Firewall rules

Ingress mode / direction Required Azure network configuration
Public Ingress (Inbound) AKS subnet NSG and Azure Firewall must allow inbound TCP 443 to the foundry-router Public Load Balancer IP from Service Tag AzureMachineLearning (or AzureCloud in regions where required), with no L7 proxy or WAF terminating TLS in front of the Load Balancer.
Private Ingress (Inbound) Your Foundry delegated subnet (Microsoft.App/environments) must be able to reach the AKS node pool subnet over TCP 443 (same VNet or peered VNets with status Connected). NSGs, UDRs, and firewalls must allow delegated subnet CIDR -> foundry-router Internal LB IP on TCP 443 without asymmetric routing.
Router Auth (Outbound) The AKS node pool subnet must allow outbound TCP 443 to Microsoft Entra ID JWKS endpoints (login.microsoftonline.com) without TLS MITM inspection.

2.2 Check Router Load Balancer and NetworkPolicies

# Confirm foundry-router has an assigned External/Internal LB IP (not <pending>) and Pods are Ready
kubectl -n foundry-system get svc foundry-router
kubectl -n foundry-system get pods -l app.kubernetes.io/component=router -o wide

# Check for custom NetworkPolicies that may block traffic between Router, Controller, and Sandbox pods
kubectl -n foundry-system get networkpolicy

3. Agent invocation, streaming, and session file failures

Symptoms:

  • Calls to /invocations, /responses, WebSockets (/invocations_ws), or session file APIs (/files*) return 4xx or 5xx errors, drop mid-stream, or time out.

3.1 Common HTTP status codes and causes

HTTP Status / Error Code Likely Cause Recommended Action
400 content_filter / SSE content_filter Content safety guardrails blocked the input or agent output. Review prompt/response content against your configured safety filters.
400 image_pull_failed AKS couldn't pull your agent container image. Verify that AKS can reach your container registry, such as Azure Container Registry. Check image-pull permissions or secrets.
409 sandbox_runtime_incompatible Preserved session runtime or snapshot layout is incompatible with the current cluster runtime. Start a new session or verify recent extension/runtime updates.
424 session_not_ready The sandbox pod failed to become ready in time or exited during startup. Inspect sandbox pod events and container logs (see Section 3.2). Ensure your container listens on port 8088 and returns 200 on GET /readiness.
429 aks_quota_exceeded AKS lacks node/pod capacity or hit VM quota while scheduling the sandbox pod. Check node pool capacity, autoscaler events, and VM quota (see Section 1.4).
502 file_service_error Session file operation failed (for example, disk full ENOSPC or permission error inside the sandbox). Check sandbox storage/disk usage and file paths.
502 upstream_response_not_inspectable Output exceeded guardrail inspection limits (unsupported Content-Encoding or non-streaming body > 1 MiB). Use streaming or ensure standard uncompressed JSON responses.
503 backend_unavailable / 503 Sandbox is unavailable, starting up, or the container returned 503. Retry after a brief pause; if persistent, inspect sandbox pod readiness and router logs.
504 (Timeout) Request exceeded the route idle timeout (300 seconds with no data) or upstream timeout. Optimize agent response latency or stream intermediate events so the connection doesn't sit idle for > 300s.

To isolate latency between infrastructure setup, container readiness, and agent execution, add the x-ms-debug-latency-enabled: true header to /responses or /invocations requests and inspect the x-ms-debug-latency-* response headers. For details, see Debug a hosted agent.

3.2 Inspect sandbox resources and pod logs in AKS

Identify your project's sandbox namespace and inspect the sandbox Deployment, Service, EndpointSlice, Pod, and Events:

kubectl get namespaces
SANDBOX_NS="<YOUR_PROJECT_SANDBOX_NAMESPACE>"

kubectl -n "$SANDBOX_NS" get deploy,svc,pods -o wide

For an affected sandbox pod:

SANDBOX_POD="<AFFECTED_SANDBOX_POD>"
kubectl -n "$SANDBOX_NS" describe pod "$SANDBOX_POD"
kubectl -n "$SANDBOX_NS" get events --field-selector "involvedObject.kind=Pod,involvedObject.name=$SANDBOX_POD" --sort-by=.lastTimestamp

# Inspect your agent container logs
kubectl -n "$SANDBOX_NS" logs "$SANDBOX_POD" --tail=100

4. Outbound egress, TLS/Private CA, and Agent Identity issues

4.1 Sandbox pod stuck in Init or outbound calls fail with 403

If a sandbox pod is stuck in Init:0/1 or Init:Error:

kubectl logs -n "$SANDBOX_NS" "$SANDBOX_POD" -c sandbox-agent --tail=100

Common causes:

  • CoreDNS blocked: sandbox-agent can't resolve foundry-egress-proxy.foundry-system.svc within 15 seconds. Check kube-dns health in kube-system and ensure no custom NetworkPolicy blocks UDP/TCP port 53.
  • Proxy DaemonSet not ready on the node: Verify foundry-egress-proxy has a 1/1 Running pod on the same node as your sandbox pod:
    kubectl get pods -n foundry-system -l app.kubernetes.io/component=egress-proxy -o wide
    
  • CNI SNAT / Masquerading (403 Forbidden on all outbound calls): Your AKS CNI must preserve the sandbox pod's source IPv4 address for intra-cluster Pod-to-ClusterIP traffic. Disable intra-cluster SNAT/masquerading for ClusterIP traffic.
  • Node sandbox density limit: Ensure active sandbox pods per AKS node don't exceed 250.

4.2 Egress policy denials, protocol restrictions, and limits

  • 403 egress_policy_denied: Your agent version's egress_policy blocked the target host/method/path. If customer OTLP telemetry is enabled, query dependencies | where name startswith "Network egress decision:" in your Application Insights workspace to inspect policyAction, enforcement, and decisionReasonCode, or temporarily switch enforcementMode to AUDIT.
  • Non-80/443 ports, UDP, or raw IP literals fail: Attaching any customer or RAI egress policy enables full inspection mode, which requires HTTP/HTTPS (80/443) traffic with DNS hostnames in TLS SNI. Direct non-80/443 TCP/UDP and raw-IP :443 passthrough are only available when no customer/RAI egress policy is attached (deploy a new agent version and start a new session to change policy attachment).
  • 421 Misdirected Request: Over HTTPS, the HTTP Host header must match the TLS SNI hostname.
  • 429 Too Many Requests: Reuse HTTP/1.1 keep-alive or HTTP/2 connection pools inside your agent container (limits: 64 concurrent TLS connections and 600 new TLS handshakes/min per sandbox pod).
  • Upstream DNS resolution failures: For this preview, use target hostnames that return IPv4 A records. IPv6-only AAAA records aren't supported. Don't use hostnames that resolve to IPv4 loopback (127.0.0.0/8), RFC 6598 Shared Address Space, or IPv4 link-local addresses (169.254.0.0/16).
  • Unsupported egress constructs (400 Bad Request): valueRef.secretRef (egress_secret_reference_not_supported), credential_rules (egress_policy_not_supported), and policies with > 500 rules (egress_policy_rule_limit_exceeded) aren't supported on BYO AKS.

4.3 Egress TLS and Private CA trust (CERTIFICATE_VERIFY_FAILED)

When egress inspection is active, foundry-egress-proxy performs TLS interception using the cluster's MITM CA, and sandbox-agent injects the combined CA bundle into /var/run/foundry/trust/ca-bundle.pem via SSL_CERT_FILE, REQUESTS_CA_BUNDLE, CURL_CA_BUNDLE, GRPC_DEFAULT_SSL_ROOTS_FILE_PATH, and NODE_EXTRA_CA_CERTS.

If your workload fails with CERTIFICATE_VERIFY_FAILED or unable to get local issuer certificate:

  • Don't overwrite CA env vars: Ensure your Dockerfile and entrypoint scripts don't overwrite SSL_CERT_FILE, REQUESTS_CA_BUNDLE, or NODE_EXTRA_CA_CERTS.
  • Language-specific trust stores:
    • Java/JVM: Import /var/run/foundry/trust/egress-roots.pem into your JVM truststore (cacerts) at container startup.
    • Rust: Build with rustls-tls-native-roots or native-tls instead of static webpki-roots.
    • Python: Don't hardcode verify=certifi.where() in requests/httpx; use verify=os.environ.get("SSL_CERT_FILE", True).
    • Node.js: If passing ca to https.Agent, include tls.rootCertificates plus /var/run/foundry/trust/ca-bundle.pem.
  • Certificate pinning: Disable thumbprint pinning in SDKs when traversing TLS inspection.
  • Private CA (trustBundle) requirements: Ensure all uploaded Private CA certificates are valid PEM (CA:TRUE, unexpired, complete intermediate + root chain, no private keys). Account-level Private CA bindings are immutable per session—start a new session after updating your Account's Private CA.
  • Cluster-wide CA bundle (egress-proxy-ca-bundle-extension): If using the foundry-system/egress-proxy-ca-bundle-extension Secret, ensure it contains at most 64 valid PEM CA certificates and is <= 256 KiB.

4.4 Agent Identity token acquisition (DefaultAzureCredential)

In a hosted agent, DefaultAzureCredential uses the hosted-agent token service to acquire tokens. The runtime provides the token service URL in IDENTITY_ENDPOINT.

  • Don't set AZURE_CLIENT_ID to a cluster/node UAMI: Only the Foundry-managed Agent Identity is allowed. Remove custom AZURE_CLIENT_ID overrides from your container.
  • Don't hardcode IMDS or overwrite MSI env vars: Don't call 169.254.169.254 directly or modify IDENTITY_ENDPOINT / IDENTITY_HEADER.
  • Exclude the token service from the proxy: If your container sets HTTP_PROXY, add only the host portion of IDENTITY_ENDPOINT to NO_PROXY. Keep existing entries and include 127.0.0.1 and localhost.
  • Reuse credential instances: Reuse a singleton DefaultAzureCredential across requests to avoid 429 throttling.
  • Outbound Entra connectivity: Ensure your AKS node pool subnet allows outbound HTTPS (443) to login.microsoftonline.com so foundry-identity-proxy can exchange tokens.
  • Downstream Azure 401/403: Grant least-privilege data-plane RBAC (such as Storage Blob Data Reader or Cognitive Services OpenAI User) to the Agent Identity Principal ID (note that published agents have a distinct identity from unpublished drafts) and allow 5–10 minutes for RBAC propagation.
  • Cluster recreated or Blueprint deleted (AADSTS70021* / AADSTS53003): If you recreated your AKS cluster (changing its OIDC issuer URL) or deleted/disabled the Agent Identity Blueprint in Microsoft Entra ID, restore the Blueprint in Entra ID or reconcile your Capability Host and republish a new Agent Version.

5. Auto-suspend and resume issues

Hosted agent sandboxes on BYO AKS automatically suspend after 15 minutes (900 seconds) of inactivity by default:

  1. The sandbox deployment scales to replicas: 0 and commits its workspace state to Azure Blob Storage.
  2. When a new request arrives for a suspended session, Foundry restores the snapshot and starts a new pod before forwarding the request.

Common scenarios:

  • Slow first request after idle: Expected when resuming a suspended sandbox. Duration depends on snapshot size, image pull time, and container /readiness startup time.
  • Sandbox stays running past 15 minutes: Check whether health probes or active streams are refreshing activity, or whether snapshot capture is still in progress.
  • In-progress request interrupted: Check if your agent had a silent gap (> 15 minutes) without active HTTP/streaming traffic, or inspect pod events for OOMKilled/evictions.

Check the sandbox replica count and snapshot state:

SANDBOX_ID="<SANDBOX_DEPLOYMENT_NAME>"
kubectl -n "$SANDBOX_NS" get deploy "$SANDBOX_ID" \
  -o 'custom-columns=NAME:.metadata.name,DESIRED:.spec.replicas,READY:.status.readyReplicas,SNAPSHOT_STATUS:.status.conditions[?(@.type=="agents.ai.azure.com/SnapshotState")].reason'
  • Generation<N>Snapshotting: Suspend is actively capturing and uploading the snapshot.
  • Generation<N>Committed with DESIRED: 0: Sandbox is cleanly suspended.

6. Project deletion, account soft-deletion, and recovery

6.1 Project deletion stuck or residue remains

Deleting a Foundry Project triggers asynchronous cleanup of both Foundry service data and AKS/Storage runtime resources:

  • Don't submit overlapping delete requests while deletion is already in progress.
  • Check whether project namespaces or PersistentVolumes remain in AKS:
kubectl get namespaces
kubectl get pv -l app.kubernetes.io/managed-by=foundry-controller

If you have Storage Blob Data Reader permissions on the snapshot container, you can inspect any remaining blobs under the project namespace prefix:

az storage blob list --account-name "$STORAGE_ACCOUNT_NAME" \
  --container-name "foundry-sandbox-snapshots" \
  --prefix "<PROJECT_NAMESPACE>/" --auth-mode login \
  --query "[].{name:name,lastModified:properties.lastModified}" --output table

Warning

Don't manually force-delete PersistentVolumes or strip Kubernetes finalizers. If cleanup remains stuck, contact Azure Support with the Azure Resource Manager resource ID for the project and the correlation ID.

6.2 Account soft-deletion blocked

Before soft-deleting a Foundry Account, all child Foundry Projects must be deleted. If account deletion fails:

  1. Verify no active projects remain under the account.
  2. Ensure the AKS cluster is running and reachable so the hosted-agent extension can uninstall cleanly.
  3. Check the Azure Activity Log for the failing operation and correlation ID.

6.3 Soft-deleted account recovery

Recovering a soft-deleted Foundry Account configured with Bring Your Own AKS is currently not supported.

Contact Azure Support

If the issue persists after completing these checks, open an Azure Support request and include:

  • Resource IDs: Azure Resource Manager resource IDs for the Foundry account, Foundry project (if applicable), AKS cluster, and storage account.
  • Operation & request details: UTC timestamp window, region, operation attempted, HTTP status code, error code/message, and correlation/request IDs (apim-request-id, x-request-id, or x-ms-client-request-id).
  • Session details (for runtime issues): Agent name/version and session/response/invocation ID.
  • Redacted cluster summary: Output of the read-only kubectl status and events commands above. Never include kubeconfig files, access tokens, secrets, or sensitive prompt/response payloads.