← Back to Pull requests

fix(execd): stage content replacements so a failed write keeps the old file #2890

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 17, 2026 14:03 UTC
Author

Summary

A failed POST /files/replace can destroy the sandbox's only copy of a file; this change stages the replacement so the endpoint returns an error with the original bytes intact.

Fixes #2889

This is a follow-up to #2433 and #2478. #2433 made /files/upload atomic and explicitly left ordinary /files/replace in place; #2478 fixed the isolated-session file routes. The ordinary and identity-scoped replace routes in FilesystemController still called os.WriteFile, which opens the destination with O_TRUNC before writing.

The handler now feeds the replacement bytes through the existing writeUploadStream, so the content is written to a private staging file in the destination directory, synced, and renamed into place. A failed copy removes the staging file and leaves the destination unchanged. The helper already preserves the destination mode (including setuid/setgid/sticky), owner/group where possible, final-component symlink behavior, and read-only rejection, and the now-unused os.Stat mode capture is removed. Its status/code/message are propagated to the response. A writable destination that cannot be replaced by rename—because a sticky directory protects a file owned by another UID, or the destination is a bind-mounted file—reuses the staged bytes through the existing in-place fallback instead of returning 500. The fallback is limited to permission and EBUSY rename errors; ENOSPC, EDQUOT, and EIO return the rename error without opening the destination, so a full or failing filesystem cannot truncate the old bytes. Destinations that support rename remain atomic.

On Windows, the staging handle is created with FILE_SHARE_DELETE so the pinned descriptor can stay open through the rename. Go's os.OpenFile omits that share mode, and Windows otherwise rejects every rename as a sharing violation.

The Linux regression uses RLIMIT_FSIZE to force a real partial write. The existing success test now uses 0640 and verifies the mode survives. The execd architecture page now states that content replacements are staged too.

Testing

  • Not run (explain why)

  • Unit tests

  • Integration tests

  • e2e / manual verification (OS-level partial-write reproduction, no live sandbox)
  • Pre-fix on base f1e4ac0924b9cb0593076e1254ec79adfd51c86b with the regression test inserted:

    --- FAIL: TestFilesystemControllerReplaceContentFailureKeepsTheReplacedFile (0.00s)
        filesystem_replace_atomic_linux_test.go:72:
            Error: Not equal:
            expected: "previous content\nprevious content\nprevious content\nprevious content\nprevious content\nprevious content\nprevious content\nprevious content\n"
            actual  : "replacement content\nreplacement "
    FAIL github.com/alibaba/opensandbox/execd/pkg/web/controller
    

    Post-fix on reviewed HEAD:

    === RUN   TestFilesystemControllerReplaceContentFailureKeepsTheReplacedFile
    --- PASS: TestFilesystemControllerReplaceContentFailureKeepsTheReplacedFile (0.00s)
    === RUN   TestFilesystemControllerReplaceContent
    --- PASS: TestFilesystemControllerReplaceContent (0.02s)
    === RUN   TestFilesystemControllerReplaceContentSupportsHomePath
    --- PASS: TestFilesystemControllerReplaceContentSupportsHomePath (0.02s)
    PASS
    ok  github.com/alibaba/opensandbox/execd/pkg/web/controller 0.059s
    

    Post-fix for the rename-fallback review on b02f24d8e:

    === RUN   TestWriteUploadStreamFallsBackWhenRenameFails
    --- PASS: TestWriteUploadStreamFallsBackWhenRenameFails (0.00s)
    === RUN   TestFilesystemControllerReplaceContentFallsBackWhenRenameFails
    --- PASS: TestFilesystemControllerReplaceContentFallsBackWhenRenameFails (0.00s)
    PASS
    ok  	github.com/alibaba/opensandbox/execd/pkg/web/controller	0.277s
    

    Checks run locally:

  • go test -count=1 -run '^TestFilesystemControllerReplaceContent' ./pkg/web/controller (Linux and Windows): pass.

  • go test -count=1 -run 'TestWriteUploadStream|TestUploadRenameUnsupported|TestUploadStagingUnsupported|TestFilesystemControllerReplaceContent' ./pkg/web/controller (Windows): pass.

  • TestWriteUploadStreamRenameIOFailureKeepsDestination covers ENOSPC, EDQUOT, and EIO; TestUploadRenameUnsupported covers the permission and EBUSY predicate boundaries.

  • GOOS=linux go test -c ./pkg/web/controller and go vet ./pkg/web/controller: pass.

  • go test -count=1 -skip '^TestFilesystemControllerRenameFilesRejectsEmptyPaths$' ./pkg/web/controller (Linux container, Go 1.25.7): pass in 11.222s.

  • The unmodified base and this branch each fail only TestFilesystemControllerRenameFilesRejectsEmptyPaths in the unfiltered Linux package suite; the failure sets are identical.

  • go build ./..., go vet ./..., GOOS=linux go build ./..., GOOS=linux go vet ./..., GOOS=windows go build ./..., and GOOS=windows go vet ./...: pass.

  • gofmt -l on the four touched Go files in an LF export of the commit: empty.

  • GOOS=linux golangci-lint run -v ./... with golangci-lint 1.64.8: pass.

  • git diff --check <base>...HEAD: clean.

  • cd docs && pnpm docs:build: build complete in 32.90s (existing chunk-size warning only).

  • The full Windows controller suite still reports unrelated failures in rename-validation, isolated-session context, and quoted-filename tests; none touch the changed upload/replace paths. The focused filesystem suite above passes.
  • Not run: a live sandbox request, macOS, and the Kind/e2e suites.

    Breaking Changes

  • None

  • Yes (describe impact and migration path)
  • The wire contract, request fields, response fields, and error status are unchanged. The implementation inherits the staged-write behavior already documented for /files/upload: a successful replacement changes the inode, so hard links and extended attributes follow the documented upload semantics. Destinations that cannot be committed by rename—non-writable directories, sticky-directory ownership, and bind mounts—fall back to the documented in-place write.

    Checklist

  • Linked Issue or clearly described motivation (Fixes #2889)

  • Added/updated docs (if needed)

  • Added/updated tests (if needed)

  • Security impact considered - a failed replacement no longer leaves a partial destination, the staging file is private, and the existing path/symlink/read-only checks remain in the shared helper

  • Backward compatibility considered
  • AI disclosure: this change was drafted with AI assistance at my request, under my direction and review.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: JasonBuildAI Review duration: 19474m
    All Vouch review confidence checks passed
    Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #2890"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.7% · Safe to merge
    27.7%