Skip to content

fix: race condition in AddToContext#5

Merged
bborbe merged 4 commits intobborbe:masterfrom
openclaw-for-ben:fix/addtocontext-race-condition
Feb 12, 2026
Merged

fix: race condition in AddToContext#5
bborbe merged 4 commits intobborbe:masterfrom
openclaw-for-ben:fix/addtocontext-race-condition

Conversation

@openclaw-for-ben
Copy link
Copy Markdown
Contributor

Problem

The AddToContext function mutated a shared map stored in the context. When multiple goroutines called AddToContext on contexts derived from the same parent, they would corrupt each other's data.

// Old implementation - race condition!
data, ok := v.(map[string]any)
if ok {
    mutex.Lock()
    data[key] = value  // mutating shared map
    mutex.Unlock()
}
return ctx  // returning original context with mutated map

The mutex only protected the write operation, but the map itself was shared across all derived contexts.

Solution

Create a new map for each call, copying existing data:

func AddToContext(ctx context.Context, key string, value any) context.Context {
    newData := map[string]any{key: value}
    if v := ctx.Value(dataCtxKey); v != nil {
        if data, ok := v.(map[string]any); ok {
            for k, v := range data {
                newData[k] = v
            }
        }
    }
    return context.WithValue(ctx, dataCtxKey, newData)
}

This ensures no shared mutable state. The global mutex has been removed as it's no longer needed.

The previous implementation mutated a shared map stored in the context,
which could cause data corruption when multiple goroutines called
AddToContext on contexts derived from the same parent.

This fix creates a new map for each call, copying existing data,
ensuring no shared mutable state. The global mutex is no longer needed
and has been removed.
- Test that derived contexts maintain independent data
- Test concurrent access from multiple goroutines (run with -race)
@bborbe bborbe merged commit 3d9e5cd into bborbe:master Feb 12, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants