Skip to content

fix(local): let Docker assign the RAPID host port - #9388

Open
tomaDev wants to merge 3 commits into
aws:developfrom
tomaDev:fix/docker-assigned-rapid-port
Open

tomaDev wants to merge 3 commits into
aws:developfrom
tomaDev:fix/docker-assigned-rapid-port

Conversation

@tomaDev

@tomaDev tomaDev commented Nov 1, 2026 •

Copy link
Copy Markdown

Which issue(s) does this change fix?

Fixes #9387

Why is this change necessary?

find_free_port picks the RAPID host port before Docker binds it, so concurrent containers can pick the same port and fail with port is already allocated. For start-lambda Event invokes, the function silently never runs.

How does it address the issue?

Publish the RAPID port with no host port so Docker assigns it at start, then read it back after start(). This removes the now-unused find_free_port and NoFreePortsError. With the #9387 repro (20 rounds of 50 concurrent invokes), develop failed in 7 rounds and this PR in 0.

What side effects does this change have?

The host port comes from Docker's dynamic range instead of 5000–8999. Follow-up: ContainerNotStartableException is no longer raised, so its handlers are now dead code.

Mandatory Checklist

PRs will only be reviewed after checklist is complete

  • Review the generative AI contribution guidelines
  • Add input/output type hints to new functions/methods
  • Write design document if needed (Do I need to write a design document?): not needed, bug fix
  • Write/update unit tests
  • Write/update integration tests: not added; the race is probabilistic, so it's verified with the repro above instead
  • Write/update functional tests if needed: not needed
  • make pr passes: schema, black-check, lint and test-all pass (coverage 94.15%)
  • make update-reproducible-reqs if dependencies were changed: no dependency changes
  • Write documentation: no user-facing change

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

🤖 Generated with Claude Code

@tomaDev
tomaDev requested a review from a team as a code owner November 1, 2026 11:42
@github-actions github-actions Bot added area/local/start-api sam local start-api command area/local/invoke sam local invoke command area/local/start-invoke pr/external stage/needs-triage Automatically applied to new issues and PRs, indicating they haven't been looked at. labels Nov 1, 2026

@aws-sam-tooling-bot aws-sam-tooling-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Lambda Tooling PR Reviewer: No high-confidence issues found.

1 lower-confidence observation: these passed verification at a lower score, so check before acting

1. [CONCURRENCY] samcli/local/docker/container.py:464: Clearing rapid_port_host before reload() lets concurrent readers of a running container see None

_read_rapid_port_host sets self.rapid_port_host = None, then makes a Docker API round-trip, and only then writes the port back. DurableLambdaContainer.wait_for_result calls self.start() on every invocation, and warm runtimes share one already-running container across request threads. During that round-trip, another thread can read None in get_port() (giving the emulator http://localhost:None) or in _make_http_request. To check, run concurrent durable invokes against a warm container. A fix is to compute the port into a local variable and assign self.rapid_port_host once, after reload() returns.

@aws-sam-tooling-bot

aws-sam-tooling-bot Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

🧪 Hands-on test plan (not run: external contributor)

Commit 03b6453. A maintainer can run these checks; nothing here has been tested.

Summary: Run the touched unit tests, then exercise sam local invoke and sam local start-lambda against real Docker: basic invoke, concurrent RequestResponse and Event invokes (the reported race), EAGER warm containers with a check of the published host port range, a 0.0.0.0 host interface, and a container that exits immediately. Comparing with the merge base shows the port range change and may show the race.

For a maintainer to check:

  • The run pulls public AWS Lambda base images from public.ecr.aws (normal sam local behavior) and starts up to ~20 Lambda containers at once in S3.

Planned checks (6):

  1. Unit tests for the changed modules and their callers (docker container/utils, lambdafn runtime, local commands) pass with the new port handling.
  2. Main path: sam local invoke still reaches the container through the Docker-assigned host port.
  3. The reported race: concurrent RequestResponse and Event invokes against sam local start-lambda (one container per invoke) must all succeed and every …
  4. Warm containers (EAGER): the port read at start stays valid across repeated invokes, and the published host port now comes from Docker's dynamic rang…
  5. Non-default --container-host-interface 0.0.0.0 (the interface DurableLambdaContainer forces): the assigned port is read from the first binding and is…
  6. Error path the PR changes: a container that exits right away (arm64 function on an x86_64 host without qemu, which fails with exec format error) has …
Commands
python3 -m venv .venv
. .venv/bin/activate && pip install --upgrade pip && SAM_CLI_DEV=1 pip install -e '.[dev]'
mkdir -p /tmp/rpt/arm && cat > /tmp/rpt/app.py <<'EOF'
import time

def handler(event, context):
    print("RAN-MARKER")
    time.sleep(1)
    return {"ok": True}
EOF
cp /tmp/rpt/app.py /tmp/rpt/arm/app.py && echo '{}' > /tmp/rpt/event.json && cp /tmp/rpt/event.json /tmp/rpt/arm/event.json
cat > /tmp/rpt/template.yaml <<'EOF'
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  HelloFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: .
      Handler: app.handler
      Runtime: python3.12
      Timeout: 30
EOF
cat > /tmp/rpt/arm/template.yaml <<'EOF'
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  ArmFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: .
      Handler: app.handler
      Runtime: python3.12
      Architectures:
        - arm64
      Timeout: 30
EOF
. .venv/bin/activate && cd /tmp/rpt && SAM_CLI_TELEMETRY=0 sam local invoke HelloFunction -e event.json --region us-east-1 || true
# S1
. .venv/bin/activate && pytest -q tests/unit/local/docker tests/unit/local/lambdafn tests/unit/commands/local
# S2
. .venv/bin/activate && cd /tmp/rpt && SAM_CLI_TELEMETRY=0 sam local invoke HelloFunction -e event.json --region us-east-1 > invoke.out 2> invoke.err; echo "exit=$?"; cat invoke.out; grep -c RAN-MARKER invoke.err; grep -E 'Traceback|NoneType|Timed out' invoke.err || echo no-errors
# S3
cat > /tmp/rpt/conc.sh <<'EOF'
#!/bin/bash
cd /tmp/rpt
URL=http://127.0.0.1:3001/2015-03-31/functions/HelloFunction/invocations
SAM_CLI_TELEMETRY=0 sam local start-lambda --port 3001 --region us-east-1 > sl.log 2>&1 &
SL=$!
trap 'kill $SL 2>/dev/null' EXIT
for i in $(seq 1 120); do curl -s -o /dev/null http://127.0.0.1:3001/ && break; sleep 1; done
: > codes.txt
for r in 1 2 3; do
  seq 1 20 | xargs -P 20 -I{} curl -s -o /dev/null -w '%{http_code}\n' -X POST -d '{}' "$URL" >> codes.txt
done
: > ev_codes.txt
seq 1 20 | xargs -P 20 -I{} curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'X-Amz-Invocation-Type: Event' -d '{}' "$URL" >> ev_codes.txt
sleep 45
echo "sync_total=$(wc -l < codes.txt) sync_non200=$(grep -vc '^200$' codes.txt)"
echo "event_total=$(wc -l < ev_codes.txt) event_non202=$(grep -vc '^202$' ev_codes.txt)"
echo "ran_markers=$(grep -c RAN-MARKER sl.log)"
echo "port_allocated_errors=$(grep -c 'port is already allocated' sl.log)"
echo "tracebacks=$(grep -c Traceback sl.log)"
EOF
chmod +x /tmp/rpt/conc.sh
. .venv/bin/activate && timeout 290 /tmp/rpt/conc.sh; tail -n 40 /tmp/rpt/sl.log
# S4
cat > /tmp/rpt/eager.sh <<'EOF'
#!/bin/bash
cd /tmp/rpt
SAM_CLI_TELEMETRY=0 sam local start-lambda --port 3002 --region us-east-1 --warm-containers EAGER > eager.log 2>&1 &
SL=$!
trap 'kill $SL 2>/dev/null' EXIT
for i in $(seq 1 180); do curl -s -o /dev/null http://127.0.0.1:3002/ && break; sleep 1; done
URL=http://127.0.0.1:3002/2015-03-31/functions/HelloFunction/invocations
for n in 1 2 3; do curl -s -w ' code=%{http_code}\n' -X POST -d '{}' "$URL"; done
echo PORTS:; docker ps --format '{{.Ports}}' | grep -- '->8080/tcp'
echo "tracebacks=$(grep -c Traceback eager.log)"
EOF
chmod +x /tmp/rpt/eager.sh
. .venv/bin/activate && timeout 280 /tmp/rpt/eager.sh
# S5
. .venv/bin/activate && cd /tmp/rpt && SAM_CLI_TELEMETRY=0 sam local invoke HelloFunction -e event.json --region us-east-1 --container-host-interface 0.0.0.0 > iface.out 2> iface.err; echo "exit=$?"; cat iface.out; grep -E 'Traceback|NoneType|Timed out' iface.err || echo no-errors
# S6
uname -m; ls /proc/sys/fs/binfmt_misc/ 2>/dev/null | grep -i aarch64 || echo no-arm-emulation
. .venv/bin/activate && cd /tmp/rpt/arm && SAM_CLI_TELEMETRY=0 SAM_CLI_CONTAINER_CONNECTION_TIMEOUT=10 timeout 240 sam local invoke ArmFunction -e event.json --region us-east-1 > arm.out 2> arm.err; echo "exit=$?"; tail -n 25 arm.err; grep -E 'NoneType|TypeError|in
… (truncated)

🤖 Automated hands-on test — not a review approval · model claude-opus-5.5 · commit 03b6453

History (2)
Commit Result When (UTC) Build
03b6453 Plan only (not run) 2026-11-01 12:07
8db2b90 Plan only (not run) 2026-11-01 11:47

@tomaDev

tomaDev commented Nov 1, 2026

Copy link
Copy Markdown
Author

@bnusunny this changes the same port-publishing code as your #9290. Happy to rebase onto it if it lands first, or the other way round. Which order works for you?

@bnusunny

bnusunny commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@tomaDev please wait for #9290

@bnusunny bnusunny left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The design is the right fix for the race. Probing for a free port in __init__ and binding it at start() is a time-of-check/time-of-use (TOCTOU) race, and two containers starting together can pick the same port. Publishing with host port None and reading the assigned port back after start() removes the race entirely. Removing find_free_port/NoFreePortsError is consistent with that. The tests are adequate: create publishes None, start reads the binding, a restart clears the stale port, and _can_connect_to_socket handles None.

Blocking:

  1. Merging onto current develop breaks the build. git merge-tree reports clean, but the merged tree has F821 Undefined name ContainerNotStartableException at samcli/local/docker/container.py:487, and tests/unit/local/docker/test_container.py fails to collect (ImportError: cannot import name 'ContainerNotStartableException' from 'samcli.local.docker.container'). Cause: #9294 (1eee8173, merged 2026-11-06) added a ContainerNotStartableException raise in start() for a missing host interface, and this PR removes that import. Please rebase onto develop and keep the import.
  2. Sequencing. bnusunny asked to wait for #9290, which also edits samcli/local/docker/utils.py / test_utils.py. git merge-tree pr-9290 pr-9388 conflicts in both files. Since this PR deletes find_free_port and #9290 rewrites it, whichever lands second must reconcile. If this one lands, most of #9290's utils.py changes become dead code.

Non-blocking, worth addressing in the same revision:

  • Concurrency window (bot observation, legitimate). _read_rapid_port_host sets rapid_port_host = None and then does a Docker round-trip. DurableLambdaContainer.wait_for_result calls self.start() on every invoke against a warm, already-running container, so a concurrent thread can read None and build http://localhost:None. Fix: compute into a local and assign once after reload().
  • Behaviour change. The RAPID host port moves from 5000–9000 to Docker's ephemeral range (typically 32768+). That is invisible to most users, but call it out in the PR body and the release notes. It matters for anyone with firewall rules or Windows excluded-port ranges tuned to the old range.
  • Engine compatibility. Please confirm that container.ports is populated after reload() on Finch and Podman, which SAM supports via ContainerClientFactory, not only on Docker. The hands-on plan in the bot comment was never run because the author is an external contributor.
  • ContainerNotStartableException "no free ports" test fixtures in tests/unit/commands/local/*/test_cli.py now describe a condition that can't happen. That's fine to keep as generic exception tests, but the message strings are stale.

CI: only the bot reviewer (pass) and hands-on (skipped) ran. The main CI workflows have not run on this head.

Inline comments

  • samcli/local/docker/container.py:33: after rebasing onto develop, keep ContainerNotStartableException in this import. #9294 raises it in start() for a missing host interface (merged tree fails ruff with F821 at line 487).
  • samcli/local/docker/container.py:460: assign once instead of clearing first. Sketch:
    real_container.reload()
    bindings = real_container.ports.get(f"{self.RAPID_PORT_CONTAINER}/tcp")
    self.rapid_port_host = int(bindings[0]["HostPort"]) if bindings else None
    This closes the window where a concurrent durable invoke on a warm container reads None.
  • samcli/local/docker/container.py:464: bindings[0]: with --container-host-interface 0.0.0.0, Docker can return both an IPv4 and an IPv6 binding, and with the userland proxy they have historically been able to differ. Prefer the binding whose HostIp is 0.0.0.0/the requested interface, or add a comment explaining why the first one is always right.
  • samcli/local/docker/container.py:245: please mention the port-range change in the PR description (Docker ephemeral range instead of 5000–9000).
  • samcli/local/docker/container.py:649: good guard. Consider a LOG.debug when the port is unset because the container exited, so a user reading --debug sees why the socket wait times out.

tomaDev and others added 3 commits November 17, 2026 16:13
find_free_port picked a random port in 5000-8999 with a bind-and-close
probe and nothing held it until Docker bound it at start, so containers
starting at the same time could pick the same port and fail with
"port is already allocated".

Publish the RAPID port with no host port so Docker allocates it at
start, then read the assigned port back on every start. A container
that exits before the read has no bindings; the port stays unset and
the socket check reports it as unreachable. Remove find_free_port and
NoFreePortsError, which have no other users.

Fixes aws#9387

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_must_not_keep_previous_rapid_host_port_on_restart already covers
a container with no port bindings after start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assign rapid_port_host once after reload() so concurrent invokes on a
warm container never read None, prefer the binding on the requested
interface, and log at debug when the container has no binding. Update
the stale "no free ports" test strings.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@tomaDev
tomaDev force-pushed the fix/docker-assigned-rapid-port branch from 03b6453 to 403a17c Compare November 17, 2026 14:32
@tomaDev

tomaDev commented Nov 17, 2026

Copy link
Copy Markdown
Author

@bnusunny rebased onto develop after #9290 and #9294:

  • Kept the ContainerNotStartableException import. Removed find_free_port together with fix(local): make port publishing usable when SAM CLI runs in a container #9290's probing helpers and their tests, since nothing calls them now.
  • The port is assigned once after reload(), prefers the binding on the requested interface, and logs at debug when there is none.
  • Updated the stale "no free ports" test strings.
  • The PR description notes the range change.
  • Engines: verified on Docker Desktop 29.9.3 (20 rounds × 50 concurrent invokes: 0 failures, vs 3 of 20 rounds on 1.172.1). Finch: finch-daemon's e2e suite covers an empty HostPort, with inspect returning the assigned port; not run here. Podman isn't a ContainerClientFactory backend; it would go through DockerContainerClient, untested.

@tomaDev
tomaDev requested a review from bnusunny November 17, 2026 14:37
@tomaDev

tomaDev commented Nov 27, 2026

Copy link
Copy Markdown
Author

@bnusunny a gentle ping on this one. The points from your review of
2026-11-13 are addressed in the three commits pushed on 2026-11-17
(summary in my comment above). The branch merges cleanly onto current
develop (982d021, 1.174.1).

Fresh numbers, 20 rounds of 50 concurrent RequestResponse invokes
against sam local start-lambda, runs interleaved:

Docker Desktop 4.100.0 (engine 29.9.3):

  • develop 982d021: 2 of 20 rounds had an invoke fail with
    "Bind for 127.0.0.1: failed: port is already allocated"
  • develop 982d021 + this PR: 0 of 20

Finch 1.19.0 (nerdctl 2.2.2, containerd 2.2.1), SAM confirmed to be
using the Finch client:

  • After reload(), container.ports is populated in the same shape as
    on Docker, e.g. {'8080/tcp': [{'HostIp': '127.0.0.1', 'HostPort': '49154'}]},
    for both 127.0.0.1 and 0.0.0.0 (one IPv4 entry each), and the new
    code reads it correctly.
  • 0 "port is already allocated" errors with this PR. The merge base
    also had 0 on Finch in this sample, so on Finch this shows no
    regression rather than a before/after. Finch does reject a duplicate
    explicit port, at create rather than at start.
  • Unrelated to this change: about 2% of invokes on Finch returned 500
    with ttrpc: closed when the finished container was removed, with
    and without this PR.

Podman is not tested.

Could you approve the CI run on this head? Happy to change anything
else you'd like to see.

@bnusunny bnusunny left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the rebase and the Finch numbers. All the blocking points from my 11-13 review are fixed. I merged this with current develop and checked it: ruff, mypy and unit tests pass, and start-lambda handled 75 concurrent invokes with no "port is already allocated" errors.

One non-blocking thing:

  • The PR body says ContainerNotStartableException is no longer raised, but #9294 still raises it for a missing host interface. Please keep that in mind in the follow-up so those handlers stay.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/local/invoke sam local invoke command area/local/start-api sam local start-api command area/local/start-invoke pr/external stage/needs-triage Automatically applied to new issues and PRs, indicating they haven't been looked at.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: concurrent containers can pick the same host port, so sam local fails with "port is already allocated"

2 participants