Repository navigation
fix: accelerate fresh provisioning and trace E2B create stages #16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
193 changes: 193 additions & 0 deletions
193
services/core/internal/execution/runtime_fresh_hint_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,193 @@ | ||
| package execution | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "sync" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| v1 "github.com/MiniMax-AI/OpenAgentCore/contracts/agents-api/v1" | ||
| "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/deployment" | ||
| "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/identity" | ||
| "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/runtimegateway" | ||
| "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/sandbox" | ||
| "github.com/MiniMax-AI/OpenAgentCore/services/core/internal/sessions" | ||
| "github.com/google/uuid" | ||
| ) | ||
|
|
||
| type freshHintProvider struct { | ||
| sandbox.SandboxProvider | ||
| creates atomic.Int32 | ||
| created chan struct{} | ||
| } | ||
|
|
||
| type hintSessionReader struct { | ||
| sessions.Reader | ||
| environment sessions.Environment | ||
| } | ||
|
|
||
| func (r hintSessionReader) GetSessionEnvironment(ctx context.Context, _, _ string) (sessions.Environment, error) { | ||
| return r.environment, ctx.Err() | ||
| } | ||
|
|
||
| func TestFreshHintRoutesAndPreservesLifecycleGuards(t *testing.T) { | ||
| for _, scenario := range []string{"direct", "node", "closed", "switching", "cancelled", "self_hosted", "released_placement", "lookup_failed", "suspended"} { | ||
| t.Run(scenario, func(t *testing.T) { | ||
| m := testRuntimeManager(t) | ||
| m.config = RuntimeProvider{InstallationID: uuid.NewString()} | ||
| nodeID := "" | ||
| if scenario == "node" || scenario == "released_placement" { | ||
| m.config.ProviderKind = "docker" | ||
| nodeID = uuid.NewString() | ||
| } | ||
| node, err := m.node(nodeID) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| environment := sessions.Environment{ID: uuid.NewString(), Configuration: json.RawMessage(`{"type":"openai_hosted"}`)} | ||
| if scenario == "self_hosted" { | ||
| environment.Configuration = json.RawMessage(`{"type":"self_hosted","workspace_directory":"/workspace"}`) | ||
| } | ||
| if scenario == "suspended" { | ||
| environment.Initialization = "complete" | ||
| m.config.Suspension = &RuntimeSuspensionPolicy{} | ||
| } | ||
| reader := &strictDeploymentReader{t: t, | ||
| environmentAllocation: func(context.Context, deployment.AllocationKey) (deployment.Allocation, error) { | ||
| if scenario == "lookup_failed" { | ||
| return deployment.Allocation{}, errors.New("database unavailable") | ||
| } | ||
| if scenario == "suspended" { | ||
| return deployment.Allocation{ProviderKey: m.config.InstallationID, State: "running", CreateSettled: true, ComputePhase: "suspended"}, nil | ||
| } | ||
| return deployment.Allocation{}, deployment.ErrNotFound | ||
| }, | ||
| lifecyclePlacement: func(context.Context, deployment.AllocationKey) (deployment.LifecyclePlacement, error) { | ||
| return deployment.LifecyclePlacement{Provider: m.config.ProviderKind, PlacementNodeID: nodeID, PlacementReleased: scenario == "released_placement"}, nil | ||
| }, | ||
| } | ||
| m.deploymentService, _ = deploymentOperations(t, &strictDeploymentStorage{t: t}, reader, &strictExecutionStorage{t: t}) | ||
| worker := &Worker{runtimes: m, dispatcher: &Dispatcher{SessionsReader: hintSessionReader{environment: environment}, DeploymentReader: reader}} | ||
| ctx, cancel := context.WithCancel(t.Context()) | ||
| defer cancel() | ||
| switch scenario { | ||
| case "closed": | ||
| m.closed = true | ||
| case "switching": | ||
| m.switching = true | ||
| case "cancelled": | ||
| cancel() | ||
| } | ||
| worker.hintRuntimeWake(ctx, sessions.Session{TenantID: uuid.NewString(), ID: uuid.NewString()}) | ||
| want := 0 | ||
| if scenario == "direct" || scenario == "node" || scenario == "suspended" { | ||
| want = 1 | ||
| } | ||
| if got := len(node.lifecycle.wakeHints); got != want { | ||
| t.Fatalf("hints = %d, want %d", got, want) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func (p *freshHintProvider) Create(_ context.Context, b sandbox.Bootstrap) (sandbox.Info, error) { | ||
| p.creates.Add(1) | ||
| select { | ||
| case p.created <- struct{}{}: | ||
| default: | ||
| } | ||
| return sandbox.Info{Reference: b.Reference, ProviderID: b.AllocationID, State: "running", BootstrapComplete: true, CreateSettled: true}, nil | ||
| } | ||
|
|
||
| func TestFreshEnvironmentHintProvisionsWithoutMaintenanceTick(t *testing.T) { | ||
| for _, mode := range []string{"create", "stream", "recovered_input", "recovered_initial"} { | ||
| t.Run(mode, func(t *testing.T) { | ||
| s, owner, deployments, reader, pool := resetManagerStoreDB(t, nil) | ||
| installation := initializeE2BDeployment(t, owner) | ||
| sessionReader, _ := testSessions(t, pool, testCredentialCipher(t)) | ||
| provider := &freshHintProvider{created: make(chan struct{}, 1)} | ||
| m := testRuntimeManager(t) | ||
| m.store, m.sessions, m.sessionExecution = owner.Store, sessionReader, owner.Sessions | ||
| m.deployment, m.deploymentService, m.deploymentReader = owner.Deployment, deployments, reader | ||
| m.lease, m.registry = owner.Lease, runtimegateway.NewRegistry() | ||
| m.config = RuntimeProvider{InstallationID: installation, CoreURL: fixturePublicURL + "/api/v1", Provider: provider} | ||
| worker := &Worker{admission: s, lease: owner.Lease, runtimes: m, dispatcher: &Dispatcher{SessionsReader: sessionReader, DeploymentReader: reader, notifications: &executionNotifications{}}, scheduleWake: make(chan struct{}, 1)} | ||
| node, err := m.node("") | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| ctx, cancel := context.WithCancel(t.Context()) | ||
| done, scans := make(chan error, 1), make(chan struct{}, 4) | ||
| // No value is ever sent to ticks: provisioning must come from a hint. | ||
| ticks := make(chan time.Time) | ||
| go func() { | ||
| done <- runRuntimeMaintenance(ctx, ticks, node.lifecycle.wakeHints, func(ctx context.Context) error { | ||
| err := node.lifecycle.reconcile(ctx) | ||
| scans <- struct{}{} | ||
| return err | ||
| }) | ||
| }() | ||
| t.Cleanup(func() { cancel(); <-done }) | ||
| <-scans // Startup scan finishes before any Session is committed. | ||
| tenant := uuid.NewString() | ||
| input := sessions.CreateSession{Creator: identity.Subject{Kind: "service_account", ID: "fixture"}, Engine: "codex", IdempotencyKey: uuid.NewString(), Configuration: json.RawMessage(`{"agent":{"model":"test-model"},"environment":{"type":"openai_hosted"}}`), ModelProvider: &v1.ModelProviderInput{Protocol: "responses", BaseURL: "https://model.fixture.example/v1", APIKey: "fixture-key"}, ModelProviderSource: v1.ModelProviderSourceSession} | ||
| messages := []sessions.Input{{Kind: "message", Payload: json.RawMessage(`{"input":[{"role":"user","content":[{"type":"input_text","text":"fixture"}]}]}`)}} | ||
| if mode == "recovered_initial" { | ||
| input.InitialInputs = messages | ||
| } | ||
| var session sessions.Session | ||
| switch mode { | ||
| case "create": | ||
| session, err = worker.CreateSession(ctx, tenant, input) | ||
| case "stream": | ||
| var creation sessions.Creation | ||
| creation, err = worker.CreateSessionStream(ctx, tenant, input) | ||
| session = creation.Session | ||
| case "recovered_input", "recovered_initial": | ||
| session, err = s.CreateSession(ctx, tenant, input) | ||
| } | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if mode == "recovered_input" || mode == "recovered_initial" { | ||
| key := uuid.NewString() | ||
| if mode == "recovered_initial" { | ||
| if err := pool.QueryRow(ctx, "SELECT idempotency_key FROM environment_input_reservations WHERE session_id=$1 AND is_initial", session.ID).Scan(&key); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| } | ||
| inputDone := make(chan error, 20) | ||
| inputCtx, stopInput := context.WithCancel(ctx) | ||
| for range 20 { | ||
| go func() { | ||
| _, inputErr := worker.submitEnvironmentInputs(inputCtx, session, key, messages) | ||
| inputDone <- inputErr | ||
| }() | ||
| } | ||
| t.Cleanup(func() { | ||
| stopInput() | ||
| for range 20 { | ||
| <-inputDone | ||
| } | ||
| }) | ||
| } | ||
| select { | ||
| case <-provider.created: | ||
| case <-time.After(2 * time.Second): | ||
| t.Fatal("committed Environment waited for a maintenance tick") | ||
| } | ||
| var requests sync.WaitGroup | ||
| for range 20 { | ||
| requests.Go(func() { worker.hintRuntimeWake(ctx, session) }) | ||
| } | ||
| requests.Wait() | ||
| <-scans // Wait for the hinted scan to settle its durable allocation. | ||
| if got := provider.creates.Load(); got != 1 { | ||
| t.Fatalf("concurrent hints issued %d Creates", got) | ||
| } | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| package e2b | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "io" | ||
|
|
||
| obslog "github.com/MiniMax-AI/OpenAgentCore/internal/obs/log" | ||
| ) | ||
|
|
||
| type createObservation struct { | ||
| Event string `json:"event"` | ||
| Stage string `json:"stage"` | ||
| DurationUS *int64 `json:"duration_us"` | ||
| Completed *bool `json:"completed"` | ||
| } | ||
|
|
||
| // Helper stderr is untrusted. Only fixed stage names and bounded numeric fields | ||
| // reach the logger; arbitrary SDK diagnostics are never forwarded. | ||
| func parseCreateObservations(raw []byte) []createObservation { | ||
| var out []createObservation | ||
| seen := make(map[string]bool) | ||
| for _, line := range bytes.Split(raw, []byte{'\n'}) { | ||
| if len(line) > 256 { | ||
| continue | ||
| } | ||
| var value createObservation | ||
| decoder := json.NewDecoder(bytes.NewReader(line)) | ||
| decoder.DisallowUnknownFields() | ||
| if decoder.Decode(&value) != nil || value.Event != "e2b_create_stage" || value.DurationUS == nil || value.Completed == nil { | ||
| continue | ||
| } | ||
| var extra any | ||
| if decoder.Decode(&extra) != io.EOF || *value.DurationUS < 0 || *value.DurationUS > 1_800_000_000 || seen[value.Stage] { | ||
| continue | ||
| } | ||
| switch value.Stage { | ||
| case "sandbox_create", "ownership_check", "template_check", "bootstrap_write", "bootstrap_run", "ready_inspect": | ||
| seen[value.Stage] = true | ||
| out = append(out, value) | ||
| } | ||
| } | ||
| return out | ||
| } | ||
|
|
||
| func observeHelperCreate(ctx context.Context, q Request, raw []byte) { | ||
| if q.Operation != "create" { | ||
| return | ||
| } | ||
| for _, value := range parseCreateObservations(raw) { | ||
| obslog.Info(ctx, "e2b create stage", "stage", value.Stage, | ||
| "duration_ms", float64(*value.DurationUS)/1000, "completed", *value.Completed, | ||
| "environment_id", q.Reference.EnvironmentID, "allocation_id", q.Reference.AllocationID) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This row preserves a transient development branch rather than a current deployment requirement, so it becomes stale when that branch is renamed or deleted. Remove it and retain only current release and deployment facts; the repository documentation rules explicitly prohibit process history and task chronology.
AGENTS.md reference: AGENTS.md:L59-L59
Useful? React with 👍 / 👎.