Repository navigation
Feat: add harness-go framework —— graph engine - #16039
Conversation
📝 WalkthroughWalkthroughThis PR adds graph channel, checkpoint, graph, and Pregel runtime packages plus broad tests across the harness. ChangesGraph harness runtime
Sequence Diagram(s)sequenceDiagram
participant Caller
participant CompiledGraph
participant PregelEngine
participant Registry
participant Checkpointer
Caller->>CompiledGraph: Invoke(input, config)
CompiledGraph->>PregelEngine: RunSync(input)
PregelEngine->>Registry: applyInput / restore checkpoint
PregelEngine->>Registry: read task inputs
PregelEngine->>Registry: applyWrites(task results)
PregelEngine->>Checkpointer: save checkpoint
PregelEngine-->>CompiledGraph: final state
CompiledGraph-->>Caller: result
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Suggested labels
Poem
|
There was a problem hiding this comment.
Actionable comments posted: 4
Note
Due to the large number of review comments, Critical severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/harness/graph/pregel/pregel_pressure_test.go (1)
1854-1860:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winTrailing incomplete comment block.
Lines 1854-1859 contain a duplicate section header comment block that doesn't have any associated test code. This appears to be leftover from copy-paste editing.
🧹 Proposed fix: remove the trailing incomplete block
} - -// ============================================================ - -// ============================================================ -// `#2`: Channel 写入冲突 — LastValue 多写入报错 vs BinaryOperator 合并 -// ============================================================ -🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/pregel_pressure_test.go` around lines 1854 - 1860, The section header comment block starting with the duplicate "// ============================================================" markers at lines 1854-1860 is a trailing incomplete comment block with no associated test code, likely leftover from copy-paste editing. Remove this entire comment block (the three line sequence containing the duplicate headers and the Chinese comment about "Channel 写入冲突") to clean up the file.
🟡 Minor comments (13)
internal/harness/graph/pregel/cache_test.go-32-34 (1)
32-34:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAvoid ultra-short TTL sleep windows in expiration tests.
Using 1ms TTL + 2ms sleep is prone to flaky failures under CI scheduling jitter.
Proposed fix
- cache.Set(ctx, "key3", "value3", 1*time.Millisecond) - time.Sleep(2 * time.Millisecond) + cache.Set(ctx, "key3", "value3", 25*time.Millisecond) + time.Sleep(60 * time.Millisecond)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/cache_test.go` around lines 32 - 34, The test uses excessively short time durations (1 millisecond TTL with 2 millisecond sleep) in the cache.Set() and time.Sleep() calls that are prone to flakiness due to CI scheduling jitter. Replace these ultra-short durations with significantly larger, more reliable time values (such as seconds instead of milliseconds) to ensure the expiration test consistently passes regardless of scheduling variations in the CI environment.internal/harness/graph/pregel/messages.go-336-341 (1)
336-341:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
CollectToMapemitter is not thread-safe.The emitter writes to the
targetmap without synchronization. If multiple emitters run concurrently or if the caller reads the map while emission is in progress, this can cause a data race.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/messages.go` around lines 336 - 341, The CollectToMap function writes to the target map without synchronization, which causes data races when multiple goroutines call the returned emitter concurrently. Protect the map access by using a sync.Mutex. Add a mutex field to wrap or guard the target map, then acquire the lock before performing the append operation to target[node] in the returned emitter function, and release it afterward to ensure thread-safe access.internal/harness/graph/pregel/engine_test.go-115-128 (1)
115-128:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
TestEngine_RecursionLimitdoesn't assert expected behavior.The test logs whether an error occurred but doesn't fail if the recursion limit isn't enforced. The comment says it creates "a loop through node_a only" but the graph structure from
newSimpleGraphalready hasnode_a → node_b → End. Adding another edgenode_a → Enddoesn't create an infinite loop.Consider using a graph that actually loops (like
newLoopGraphfrom the pressure tests) and asserting that an error is returned.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine_test.go` around lines 115 - 128, The TestEngine_RecursionLimit function lacks proper assertions and uses an incorrect graph structure that doesn't actually create an infinite loop. Replace the current graph setup (which just adds an edge to End) with a graph that creates an actual cycle (consider using a pattern similar to newLoopGraph referenced in pressure tests), then add a proper assertion using require.Error to verify that engine.RunSync returns an error when the recursion limit is exceeded. Currently the test only logs the result without failing, so it won't catch if the recursion limit enforcement breaks.internal/harness/graph/pregel/cache_async.go-253-259 (1)
253-259:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
WaitForPendingis a misleading stub.The method just sleeps and always returns
true, providing no actual synchronization. This is confusing for callers who expect it to wait for pending operations. Either implement proper tracking or document this as a TODO/placeholder.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/cache_async.go` around lines 253 - 259, The WaitForPending method in AsyncCachedExecutor is misleading because it doesn't actually track or wait for pending operations—it just sleeps and always returns true. Either implement proper tracking of pending async operations so the method waits for them to complete and returns whether they all finished within the timeout, or clearly document this as a TODO/placeholder with comments explaining that it's not yet fully implemented so callers understand the limitation and don't rely on it for actual synchronization.internal/harness/graph/pregel/stream.go-292-307 (1)
292-307:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winPotential race between
emit()andClose()despite mutex.
emit()usesRLockto checkclosedand send to the channel. However, between releasing the lock after the check (line 298) and the actual send (line 302),Close()could acquire the write lock and close the channel. Consider holding the lock during the entire non-blocking send or using a different synchronization approach.Note: The current code does hold the RLock across the send (deferred unlock), so the race window is when Close() is waiting for RLock holders to release. This is less severe but still worth reviewing for correctness under high contention.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/stream.go` around lines 292 - 307, The emit() method has a potential race condition where it checks the closed flag and sends to the channel under RLock protection, but Close() could still close the channel immediately after emit() releases its lock, causing a panic when sending on a closed channel. To fix this, ensure that the closed flag check and channel send are coordinated with Close() by either: (1) making the closed flag an atomic value that Close() sets before closing the channel, allowing emit() to check it without the lock and return early if Close() has begun, or (2) using a sync.Cond to signal when Close() is about to close the channel so that emit() can coordinate with it. The key is preventing Close() from closing the channel while emit() is actively sending or about to send to it.internal/harness/graph/pregel/remote.go-277-284 (1)
277-284:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
NodeToRemoteRunnableignores thenodeparameter.The function accepts a
node types.NodeFuncbut never uses it. The comment indicates it should "register the node locally and expose it via HTTP", but it only creates aRemoteRunnablepointing to the URL.Either implement the registration logic or remove the unused parameter.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/remote.go` around lines 277 - 284, The NodeToRemoteRunnable function accepts a node parameter of type types.NodeFunc but does not use it anywhere in the function body, which violates the principle of not accepting unused parameters. Either remove the unused node parameter from the function signature since the function only creates and returns a RemoteRunnable with the provided URL, or if the function should actually register the node locally and expose it via HTTP as indicated by the comment, implement that logic to properly use the node parameter before creating the RemoteRunnable.internal/harness/graph/pregel/subgraph.go-301-310 (1)
301-310:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winPotential key collision in
CreateCheckpoint.Adding
"namespace"and"prefix"keys to the checkpoint map could overwrite channel data if any channel happens to be named"namespace"or"prefix".Consider using a nested structure or prefixed metadata keys (e.g.,
"__namespace__").🛡️ Proposed fix
func (r *NamespaceIsolatedRegistry) CreateCheckpoint() map[string]interface{} { baseCheckpoint := r.registry.CreateCheckpoint() // Add namespace metadata with reserved prefix to avoid collisions - baseCheckpoint["namespace"] = r.namespace - baseCheckpoint["prefix"] = r.prefix + baseCheckpoint["__meta_namespace__"] = r.namespace + baseCheckpoint["__meta_prefix__"] = r.prefix return baseCheckpoint }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/subgraph.go` around lines 301 - 310, The CreateCheckpoint method in NamespaceIsolatedRegistry directly adds "namespace" and "prefix" keys to the checkpoint map, which risks colliding with actual channel data if channels use these same key names. To fix this, replace the direct key assignments with prefixed metadata keys (such as "__namespace__" and "__prefix__") or nest the metadata under a reserved key like "__metadata__" that is unlikely to conflict with channel names. This ensures namespace isolation metadata is stored safely without overwriting channel data.internal/harness/graph/interrupt/interrupt_test.go-103-106 (1)
103-106:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAssert
Interrupterrors in side-effect checks instead of ignoring them.These calls are part of test setup semantics; dropping the error weakens the test and can conceal behavior regressions.
Also applies to: 117-120
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/interrupt/interrupt_test.go` around lines 103 - 106, The Interrupt function calls at lines 103-106 and 117-120 in internal/harness/graph/interrupt/interrupt_test.go are ignoring their error return values. At each location, capture the error returned by the Interrupt call and assert it (or check it appropriately for the test context) rather than discarding it. This applies to both the call around line 104 and the call around line 118 - ensure both calls properly handle their returned errors to prevent test regressions from being concealed.internal/harness/graph/channels/binop_test.go-73-74 (1)
73-74:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAvoid dropping
errvalues in test assertions.A few paths ignore
Update/Geterrors, which can mask the real failure mode and make assertions less trustworthy.Also applies to: 97-101, 111-112, 131-131
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/channels/binop_test.go` around lines 73 - 74, Stop ignoring error values returned by the Get() and Update() method calls in the test file by removing the blank identifier assignments. Instead, capture the errors explicitly and add assertions to verify they are nil (for example, change val, _ = ch.Get() to val, err := ch.Get() followed by a check like if err != nil { t.Fatalf(...) }). Apply this pattern to all instances where Get() or Update() errors are currently being discarded, ensuring each call properly validates that no error occurred before proceeding with the test assertions.internal/harness/graph/errors/errors.go-209-220 (1)
209-220:⚠️ Potential issue | 🟡 Minor
FormatErroris not traversing the actual unwrap chain.Line 216 uses the original
errparameter instead of the loop variablecurrent, so the function cannot properly traverse a wrapped error chain. Replace the buggy unwrap logic with the standard library'serrors.Unwrap()method.Suggested fix
import ( "fmt" + "errors" "runtime" "strings" )current := err depth := 0 for current != nil && depth < 10 { // Prevent infinite loops prefix := strings.Repeat(" ", depth) sb.WriteString(fmt.Sprintf("%s%s\n", prefix, current.Error())) - - // Check for wrapped error - if unwrapped := fmt.Sprintf("%v", err); unwrapped != current.Error() { - current = fmt.Errorf("%s", unwrapped) - } else { - current = nil - } + current = errors.Unwrap(current) depth++ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/errors/errors.go` around lines 209 - 220, The FormatError function's error traversal logic is broken because line 216 incorrectly uses the original err parameter instead of the loop variable current when checking for wrapped errors, which prevents proper traversal of the error chain. Replace the buggy unwrap logic (lines 215-219) that uses fmt.Sprintf with the standard library's errors.Unwrap() method, passing current as the argument to properly traverse to the next error in the chain. This will ensure the loop correctly iterates through all wrapped errors rather than repeatedly checking the original error.internal/harness/graph/checkpoint/checkpoint.go-627-632 (1)
627-632:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Listordering does not match its own contract.The code says “most recent first,” but this loop returns oldest→newest within the selected window. Align implementation or contract text.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/checkpoint/checkpoint.go` around lines 627 - 632, The comment in the List function claims to return "most recent checkpoints first," but the implementation actually returns checkpoints in oldest-to-newest order within the selected limit window. Fix this by either reversing the order in which results are populated (iterate backwards through the checkpoints slice starting from the end) to match the documented contract, or update the comment to accurately describe the current behavior of returning oldest-to-newest order. Choose whichever aligns with the intended API contract for the List function.internal/harness/graph/graph/graph_concurrency_test.go-431-435 (1)
431-435:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winExpected-error concurrency tests do not assert their expected outcomes.
InterruptRaceandTimeoutRaceonly log returned errors. If interrupts/timeouts stop occurring, these tests still pass, reducing regression coverage. Please assert the expected class/count of errors.Also applies to: 441-443, 647-657
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/graph/graph_concurrency_test.go` around lines 431 - 435, The InterruptRace and TimeoutRace test functions currently send errors to a channel but do not assert that expected errors of the correct type were actually received, allowing tests to pass even if interrupts or timeouts stop occurring. After the test invocations complete and errors are collected in the errs channel, add explicit assertions to verify that errors of the expected class (interrupt errors for InterruptRace, timeout errors for TimeoutRace) were received and validate the count/frequency of these errors. Apply this fix to InterruptRace test (around lines 431-435), TimeoutRace test (around lines 441-443), and the similar pattern at lines 647-657, ensuring each test explicitly validates that its expected failure mode occurred as intended.internal/harness/graph/checkpoint/concurrency_test.go-197-204 (1)
197-204:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winConflict-path test currently uses the same task ID for both writes.
The second write set (
writes2) is created astask2, butPutWritesis invoked with"task1"again, so the cross-task conflict path is not actually exercised.Suggested fix
- err = manager.PutWrites(ctx, config, writes2, "task1") + err = manager.PutWrites(ctx, config, writes2, "task2")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/checkpoint/concurrency_test.go` around lines 197 - 204, The test creates a second write set called writes2 to simulate a cross-task conflict, but the manager.PutWrites call still uses "task1" as the task identifier instead of "task2". Change the task identifier argument in the manager.PutWrites call from "task1" to "task2" so that writes2 is properly attributed to task2, allowing the cross-task conflict detection path to be actually exercised by the test.
🧹 Nitpick comments (11)
internal/harness/graph/pregel/cache_async.go (1)
243-248: 💤 Low valueFire-and-forget
ASetusescontext.Background(), detaching from caller lifecycle.Using
context.Background()means the cache write will proceed even if the original request was cancelled. This may be intentional for best-effort caching, but could lead to stale writes if the computation was invalidated. Consider documenting this behavior or using a derived context with a timeout.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/cache_async.go` around lines 243 - 248, The fire-and-forget async cache set operation in the conditional block checking e.cachePolicy.Async uses context.Background() which detaches the cache write from the original request's lifecycle, allowing it to continue even if the caller cancels. Either add clear documentation explaining this is intentional best-effort caching behavior and why context.Background() is appropriate here, or replace context.Background() with a derived context that has a reasonable timeout to still provide some lifecycle management while maintaining the async fire-and-forget pattern. Choose the approach that best aligns with your caching strategy and document the reasoning.internal/harness/graph/pregel/stream.go (1)
353-360: 💤 Low value
WriteJSONmay produce unexpected output.
WriteJSONmarshalsdatato JSON bytes, then passes those bytes toWrite, which callsEmitDebug. The debug event will contain[]byte(the JSON) as its data payload, not the original structured object. If the intent is to emit structured JSON, the marshal step is redundant; if the intent is to emit raw JSON bytes, the interface is confusing.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/stream.go` around lines 353 - 360, The WriteJSON method in StreamWriter marshals data to JSON bytes then passes those bytes to Write, which ultimately sends []byte as the data payload in the debug event rather than the original structured object. This creates ambiguity about intent. Remove the json.Marshal call in WriteJSON and pass the original data parameter directly to the Write method instead, allowing the downstream handler to determine how to serialize the data appropriately.internal/harness/graph/pregel/background.go (1)
255-336: 💤 Low value
PriorityQueueis defined but unused.The
PriorityQueuetype and its methods are implemented but theBackgroundExecutoruses a plain buffered channel (taskQueue chan *BackgroundTask) which doesn't respect task priority. Either integrate the priority queue into the executor or remove it to avoid dead code.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/background.go` around lines 255 - 336, The PriorityQueue type and its associated methods (NewPriorityQueue, Push, Pop, Len, heapifyUp, heapifyDown) are implemented but not integrated into the BackgroundExecutor, which still uses a plain buffered channel for taskQueue that doesn't respect priority ordering. Either remove the entire PriorityQueue implementation and its methods to eliminate dead code, or refactor BackgroundExecutor to replace the taskQueue buffered channel with an instance of PriorityQueue and update all task enqueue/dequeue operations to use the queue's Push and Pop methods instead of channel operations.internal/harness/graph/pregel/optimized_test.go (1)
400-424: ⚡ Quick winTest doesn't assert that error occurs for nil registry.
PrepareNextTasksOptimizedis called withnilregistry, which should fail. The test logs the error but doesn't assert it occurred. If the implementation changes to accept nil, this test would silently pass.💚 Proposed fix
tasks, triggers, err := optimized.PrepareNextTasksOptimized( ctx, nil, // registry map[string]bool{}, "", nil, // current state ) - if err != nil { - t.Logf("PrepareNextTasksOptimized error: %v", err) + if err == nil { + t.Error("Expected error for nil registry, got nil") }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/optimized_test.go` around lines 400 - 424, The test function "prepare next tasks with optimization" calls PrepareNextTasksOptimized with a nil registry but only logs the error instead of asserting it. Replace the error logging with an assertion that fails the test if no error occurs. When PrepareNextTasksOptimized returns nil error, the test should fail immediately using t.Fatalf or t.Errorf to ensure the function properly rejects nil registry arguments. This prevents the test from silently passing if the implementation is changed to accept nil registries.internal/harness/graph/pregel/remote.go (1)
179-186: ⚡ Quick winHardcoded timeout and no HTTP client configuration.
NewHTTPPregelProtocolhardcodes a 30-second timeout with no way to customize the HTTP client, unlikeRemoteRunnablewhich acceptsHTTPClientandTimeoutin config. Consider adding similar configuration options for consistency.♻️ Proposed refactor
+// HTTPPregelProtocolConfig configures an HTTP Pregel protocol. +type HTTPPregelProtocolConfig struct { + BaseURL string + Headers map[string]string + Timeout time.Duration + HTTPClient *http.Client +} + // NewHTTPPregelProtocol creates a new HTTP Pregel protocol. -func NewHTTPPregelProtocol(baseURL string, headers map[string]string) *HTTPPregelProtocol { +func NewHTTPPregelProtocol(config *HTTPPregelProtocolConfig) *HTTPPregelProtocol { + timeout := config.Timeout + if timeout == 0 { + timeout = 30 * time.Second + } + client := config.HTTPClient + if client == nil { + client = &http.Client{Timeout: timeout} + } return &HTTPPregelProtocol{ - baseURL: baseURL, - httpClient: &http.Client{Timeout: 30 * time.Second}, - headers: headers, + baseURL: config.BaseURL, + httpClient: client, + headers: config.Headers, } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/remote.go` around lines 179 - 186, The NewHTTPPregelProtocol function hardcodes a 30-second timeout and does not allow customization of the HTTP client, inconsistent with RemoteRunnable which accepts HTTPClient and Timeout configuration. Modify NewHTTPPregelProtocol to accept configuration parameters (such as HTTPClient and Timeout fields in a config struct) instead of hardcoding them, allowing callers to customize the HTTP client behavior and timeout duration to match the flexibility provided by RemoteRunnable.internal/harness/graph/pregel/optimized.go (1)
118-151: 💤 Low value
FinishNotificationlogs to stdout and discards the notification.The method creates a
FinishNotificationstruct but only logs to stdout viafmt.Printfand then discards it (_ = notification). The comment indicates it should send to a stream manager.Consider either implementing the stream manager integration or removing the placeholder logging to avoid polluting stdout.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/optimized.go` around lines 118 - 151, The FinishNotification method in PregelOptimizedEngine creates a notification struct but then discards it using a blank assignment and only logs to stdout via fmt.Printf. Either implement the actual stream manager integration to send the notification to waiting tasks and streams (as indicated by the comment), or remove the placeholder logging and the unused notification variable assignment if stream manager integration is not yet available. Do not leave the struct created but discarded with only stdout logging as a placeholder solution.internal/harness/graph/pregel/read.go (1)
385-441: 💤 Low valueNo synchronization on
ReadContext.Readersmap.
AddReadermodifies theReadersmap whileReadAlliterates over it. If these are called concurrently, a data race occurs.If
ReadContextfollows a "build then use" pattern (allAddReadercalls complete beforeShouldExecute/ReadAll), this is safe. Otherwise, add a mutex.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/read.go` around lines 385 - 441, The ReadContext struct has a data race condition where the Readers map is modified by AddReader while potentially being read concurrently by ReadAll and GetReader. Add a sync.RWMutex field to the ReadContext struct, acquire a write lock in the AddReader method before modifying the Readers map, acquire a read lock in both the ReadAll and GetReader methods before accessing the Readers map, and ensure locks are properly released. This protects against concurrent modifications and reads of the shared map.internal/harness/graph/pregel/engine.go (1)
32-86: ⚖️ Poor tradeoffEngine is not safe for concurrent
Runcalls.The
Enginestruct has mutable fields (currentCheckpoint,channelVersions,versionsSeen,deferredCheckpoints) that are modified duringRunwithout synchronization. The docstring says "reusable across multiple Run calls" but doesn't clarify these must be sequential.Consider either:
- Adding a mutex to protect mutable state
- Documenting that concurrent
Runcalls are not supported- Moving per-run state into a separate
runContextstruct🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine.go` around lines 32 - 86, The Engine struct has mutable fields (currentCheckpoint, channelVersions, versionsSeen, deferredCheckpoints) that are modified during Run execution without synchronization primitives, creating potential data races if Run is called concurrently. The docstring claims the engine is reusable but doesn't address thread safety. Fix this by either: (1) adding a sync.Mutex field to the Engine struct and protecting all access to these mutable fields with lock/unlock calls during Run, (2) updating the NewEngine docstring to explicitly state that Run calls must be sequential and not concurrent, or (3) extracting these per-run mutable fields into a separate context struct that is created fresh for each Run call, keeping only the immutable shared state (like graph and config) in Engine.internal/harness/graph/constants/constants.go (1)
106-141: ⚡ Quick winPrefer making reservation policy immutable.
Because
Reservedis an exported map, any package can mutate it at runtime and silently changeIsReservedbehavior.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/constants/constants.go` around lines 106 - 141, The Reserved map is exported and mutable, allowing external packages to modify the reservation policy at runtime. Make the Reserved map unexported by changing its name from "Reserved" to "reserved" (lowercase), so that only the IsReserved function provides the public interface for checking if a key is reserved. The IsReserved function should remain exported as the only way external packages can access the reservation policy, ensuring the map contents cannot be modified externally.internal/harness/graph/channels/channels_test.go (1)
245-269: ⚡ Quick winAdd checkpoint/restore coverage for after-finish channels.
Current tests validate finish gating, but not checkpoint round-trip of that gate. Add cases for
LastValueAfterFinishandNamedBarrierValueAfterFinishthat assert availability/state is preserved after restore.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/channels/channels_test.go` around lines 245 - 269, The test file lacks checkpoint/restore coverage for after-finish channels. Add test cases for both LastValueAfterFinish and NamedBarrierValueAfterFinish that verify the finish gate state is correctly preserved through a checkpoint and restore cycle. For each channel type, create scenarios that checkpoint the channel after it has been finished, then restore it and assert that the restored channel maintains the same availability and state as the original. This ensures that the finished flag and any related internal state are properly serialized and deserialized.internal/harness/graph/channels/reducer_test.go (1)
107-116: ⚡ Quick winFactory tests miss reducer-enabled behavior and numeric compatibility cases.
Please add
CreateReducerChannel(..., reducer)tests that exercise an existing value + new update, plus at least one non-intnumeric type (e.g.,int64/float32) to catch silent aggregation mismatches.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/channels/reducer_test.go` around lines 107 - 116, The TestCreateReducerChannel test function only verifies the basic case with a nil reducer and int type, missing coverage of actual reducer behavior and numeric type compatibility. Expand the test by adding test cases that pass non-nil reducer functions and exercise scenarios with existing values being updated with new data, plus test with at least one additional numeric type like int64 or float32 to ensure the reducer correctly handles different numeric types and catches potential aggregation mismatches.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 11baa948-58be-4539-9399-f3581f25c9c3
📒 Files selected for processing (74)
internal/harness/graph/channels/any_value.gointernal/harness/graph/channels/barrier.gointernal/harness/graph/channels/base.gointernal/harness/graph/channels/binop.gointernal/harness/graph/channels/binop_test.gointernal/harness/graph/channels/channels_test.gointernal/harness/graph/channels/ephemeral_value.gointernal/harness/graph/channels/last_value.gointernal/harness/graph/channels/reducer.gointernal/harness/graph/channels/reducer_test.gointernal/harness/graph/channels/topic.gointernal/harness/graph/channels/untracked.gointernal/harness/graph/checkpoint/checkpoint.gointernal/harness/graph/checkpoint/checkpoint_test.gointernal/harness/graph/checkpoint/concurrency_test.gointernal/harness/graph/checkpoint/memory.gointernal/harness/graph/checkpoint/nats.gointernal/harness/graph/constants/constants.gointernal/harness/graph/errors/errors.gointernal/harness/graph/errors/errors_test.gointernal/harness/graph/graph/checkpoint_recovery_test.gointernal/harness/graph/graph/compiled.gointernal/harness/graph/graph/graph.gointernal/harness/graph/graph/graph_channel_test.gointernal/harness/graph/graph/graph_concurrency_test.gointernal/harness/graph/graph/graph_integration_test.gointernal/harness/graph/graph/graph_test.gointernal/harness/graph/graph/message.gointernal/harness/graph/graph/state.gointernal/harness/graph/interrupt/interrupt.gointernal/harness/graph/interrupt/interrupt_test.gointernal/harness/graph/managed/managed.gointernal/harness/graph/managed/managed_test.gointernal/harness/graph/pregel/async.gointernal/harness/graph/pregel/background.gointernal/harness/graph/pregel/cache.gointernal/harness/graph/pregel/cache_async.gointernal/harness/graph/pregel/cache_test.gointernal/harness/graph/pregel/engine.gointernal/harness/graph/pregel/engine_test.gointernal/harness/graph/pregel/messages.gointernal/harness/graph/pregel/optimized.gointernal/harness/graph/pregel/optimized_test.gointernal/harness/graph/pregel/pregel_pressure_test.gointernal/harness/graph/pregel/read.gointernal/harness/graph/pregel/read_test.gointernal/harness/graph/pregel/remote.gointernal/harness/graph/pregel/retry.gointernal/harness/graph/pregel/retry_multi.gointernal/harness/graph/pregel/stream.gointernal/harness/graph/pregel/subgraph.gointernal/harness/graph/pregel/subgraph_test.gointernal/harness/graph/pregel/write.gointernal/harness/graph/pregel/write_test.gointernal/harness/graph/runnable/inject.gointernal/harness/graph/runnable/runnable.gointernal/harness/graph/runnable/runnable_test.gointernal/harness/graph/store/base.gointernal/harness/graph/store/memory.gointernal/harness/graph/store/store_test.gointernal/harness/graph/task/decorator.gointernal/harness/graph/task/decorator_test.gointernal/harness/graph/types/config.gointernal/harness/graph/types/config_test.gointernal/harness/graph/types/scratchpad.gointernal/harness/graph/types/scratchpad_test.gointernal/harness/graph/types/stream.gointernal/harness/graph/types/stream_test.gointernal/harness/graph/types/types.gointernal/harness/graph/visualization/draw.gointernal/harness/graph/visualization/draw_test.gointernal/harness/prebuilt/prebuilt.gointernal/harness/prebuilt/prebuilt_edge_test.gointernal/harness/prebuilt/prebuilt_test.go
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/harness/graph/pregel/engine.go (1)
1416-1424:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winBug: Fix at line 1420 is incomplete;
mis alreadynilwhen indexed.The attempted fix stores
nmintom[parts[i]], butmwas already reassigned tonilby the failed type assertion on line 1417. Whensubis not amap[string]interface{},mreceives the zero value (nil), and indexing into it on line 1420 will panic.Trace for path
"a.b"whenm["a"]exists but is a string:
sub, ok := m["a"]→sub = "string",ok = truem, ok2 = sub.(map[string]interface{})→m = nil,ok2 = falsem[parts[i]] = nm→ panic: assignment to entry in nil map🐛 Proposed fix using a separate cursor variable
func setNestedField(m map[string]interface{}, path string, val interface{}) { if path == "" { - for k, v := range val.(map[string]interface{}) { - m[k] = v + if valMap, ok := val.(map[string]interface{}); ok { + for k, v := range valMap { + m[k] = v + } } return } parts := strings.Split(path, ".") + cur := m for i := 0; i < len(parts)-1; i++ { - sub, ok := m[parts[i]] + sub, ok := cur[parts[i]] if !ok { sub = make(map[string]interface{}) - m[parts[i]] = sub + cur[parts[i]] = sub } - var ok2 bool - m, ok2 = sub.(map[string]interface{}) + subMap, ok2 := sub.(map[string]interface{}) if !ok2 { - nm := make(map[string]interface{}) - m[parts[i]] = nm - m = nm + subMap = make(map[string]interface{}) + cur[parts[i]] = subMap } + cur = subMap } - m[parts[len(parts)-1]] = val + cur[parts[len(parts)-1]] = val }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine.go` around lines 1416 - 1424, The type assertion on line 1417 assigns `nil` to `m` when the assertion fails (ok2 is false), and then line 1420 attempts to index into this `nil` value, causing a panic. Fix this by introducing a separate cursor variable to track the current nested map during traversal, rather than reusing `m` itself. When the type assertion fails and you need to create a new nested map `nm`, assign it to the parent map using the cursor variable, then update the cursor to point to `nm` for the next iteration. This preserves the reference to the parent map and prevents indexing into `nil`.
🧹 Nitpick comments (1)
internal/harness/graph/pregel/engine.go (1)
223-230: ⚖️ Poor tradeoffEngine state mutation is not thread-safe during concurrent
Runcalls.The
Runmethod resets and mutates Engine-level fields (currentCheckpoint,channelVersions,versionsSeen,backgroundExec) without synchronization. IfRunis called concurrently on the same Engine instance, these writes will race.If concurrent usage is expected, consider either:
- Documenting that a single Engine must not be used concurrently, or
- Moving these fields into a per-run struct passed through the execution context.
Also applies to: 277-277
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine.go` around lines 223 - 230, The Run method in the Engine struct mutates several fields (currentCheckpoint, channelVersions, versionsSeen, deferredCheckpoints, and backgroundExec) without synchronization, creating a race condition if Run is called concurrently on the same Engine instance. To fix this, choose one approach: (1) Add clear documentation to the Engine type and Run method specifying that a single Engine instance cannot be safely used concurrently and must be protected by external synchronization, OR (2) Refactor by moving these mutable fields (currentCheckpoint, channelVersions, versionsSeen, deferredCheckpoints, backgroundExec) into a per-run execution state struct that is created and passed through the execution context for each Run call, eliminating shared state mutations. Ensure any chosen approach is consistently applied across all locations where these fields are accessed and modified in the Run method and related execution paths.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@internal/harness/graph/pregel/engine.go`:
- Around line 1416-1424: The type assertion on line 1417 assigns `nil` to `m`
when the assertion fails (ok2 is false), and then line 1420 attempts to index
into this `nil` value, causing a panic. Fix this by introducing a separate
cursor variable to track the current nested map during traversal, rather than
reusing `m` itself. When the type assertion fails and you need to create a new
nested map `nm`, assign it to the parent map using the cursor variable, then
update the cursor to point to `nm` for the next iteration. This preserves the
reference to the parent map and prevents indexing into `nil`.
---
Nitpick comments:
In `@internal/harness/graph/pregel/engine.go`:
- Around line 223-230: The Run method in the Engine struct mutates several
fields (currentCheckpoint, channelVersions, versionsSeen, deferredCheckpoints,
and backgroundExec) without synchronization, creating a race condition if Run is
called concurrently on the same Engine instance. To fix this, choose one
approach: (1) Add clear documentation to the Engine type and Run method
specifying that a single Engine instance cannot be safely used concurrently and
must be protected by external synchronization, OR (2) Refactor by moving these
mutable fields (currentCheckpoint, channelVersions, versionsSeen,
deferredCheckpoints, backgroundExec) into a per-run execution state struct that
is created and passed through the execution context for each Run call,
eliminating shared state mutations. Ensure any chosen approach is consistently
applied across all locations where these fields are accessed and modified in the
Run method and related execution paths.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 34b33df5-76c8-4fb9-a029-01148c0bea6f
📒 Files selected for processing (4)
internal/harness/graph/interrupt/interrupt.gointernal/harness/graph/pregel/cache.gointernal/harness/graph/pregel/engine.gointernal/harness/graph/pregel/messages.go
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/harness/graph/pregel/cache.go
- internal/harness/graph/interrupt/interrupt.go
- internal/harness/graph/pregel/messages.go
|
@CodeRabbit review --dir internal/harness/graph/graph |
|
@CodeRabbit review --dir internal/harness/graph/channels |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
find internal/harness/graph/graph -type f -name "*.go" | sortLength of output: 536 🏁 Script executed: #!/bin/bash
echo "===== graph.go =====" && cat internal/harness/graph/graph/graph.go
echo "===== compiled.go =====" && cat internal/harness/graph/graph/compiled.go
echo "===== state.go =====" && cat internal/harness/graph/graph/state.go
echo "===== message.go =====" && cat internal/harness/graph/graph/message.goLength of output: 59422 🏁 Script executed: #!/bin/bash
echo "===== graph_test.go =====" && cat internal/harness/graph/graph/graph_test.go
echo "===== graph_integration_test.go =====" && cat internal/harness/graph/graph/graph_integration_test.go
echo "===== checkpoint_recovery_test.go =====" && cat internal/harness/graph/graph/checkpoint_recovery_test.goLength of output: 29398
Review:
|
| Severity | File | Issue |
|---|---|---|
| 🔴 High | graph.go |
Node errors swallowed → infinite rescheduling until recursion limit |
| 🔴 High | graph.go |
nil context to condition functions |
| 🔴 High | graph.go |
Inline runner: nil input breaks checkpoint resume |
| 🔴 High | compiled.go |
Inverted checkpoint map — reverse migration returns wrong ID |
| 🟠 Medium | graph.go |
AddEdge(Start, X) overwrites entryPoint silently |
| 🟠 Medium | graph.go |
Regular edges silently suppressed when conditional edges exist |
| 🟠 Medium | graph.go |
StateGraph.NodeTriggerMode mutated by Compile — data race |
| 🟠 Medium | compiled.go |
generateCheckpointID not collision-safe |
| 🟠 Medium | message.go |
messages channel never registered in NewMessageGraph |
| 🟡 Low | graph.go |
__root__ magic key undocumented |
| 🟡 Low | state.go |
Double schema validation in Compile |
| 🟡 Low | state.go |
Duplicate reducer definitions vs channels/reducer.go |
| 🟡 Low | message.go |
SetEntryPoint error silently discarded |
| 🟡 Low | message.go |
GraphError lacks errors.Is/errors.As |
| 🟡 Low | compiled.go |
Dead code: buildTaskPath result discarded |
| 🔵 Nit | graph_test.go |
Duplicate nil-error check in TestAddEdge |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
echo "=== base.go ===" && cat internal/harness/graph/channels/base.go
echo "=== any_value.go ===" && cat internal/harness/graph/channels/any_value.go
echo "=== last_value.go ===" && cat internal/harness/graph/channels/last_value.go
echo "=== ephemeral_value.go ===" && cat internal/harness/graph/channels/ephemeral_value.go
echo "=== untracked.go ===" && cat internal/harness/graph/channels/untracked.go
echo "=== topic.go ===" && cat internal/harness/graph/channels/topic.go
echo "=== barrier.go ===" && cat internal/harness/graph/channels/barrier.go
echo "=== binop.go ===" && cat internal/harness/graph/channels/binop.go
echo "=== reducer.go ===" && cat internal/harness/graph/channels/reducer.go
echo "=== binop_test.go ===" && cat internal/harness/graph/channels/binop_test.go
echo "=== channels_test.go ===" && cat internal/harness/graph/channels/channels_test.go
echo "=== reducer_test.go ===" && cat internal/harness/graph/channels/reducer_test.goLength of output: 51590
Review:
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16039 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
@CodeRabbit review --dir internal/harness/graph/checkpoint |
|
@CodeRabbit review --dir internal/harness/graph/interrupt |
|
@CodeRabbit review --dir internal/harness/graph/managed |
|
@CodeRabbit review --dir internal/harness/graph/runnable |
|
@CodeRabbit review --dir internal/harness/graph/task |
|
@CodeRabbit review --dir internal/harness/graph/prebuilt |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
find internal/harness/graph/prebuilt -type f -name "*.go" | sort 2>/dev/null || echo "Directory not found or empty"
tree internal/harness/graph/prebuilt 2>/dev/null || echo "tree not available or dir not found"Length of output: 447 🏁 Script executed: #!/bin/bash
find internal/harness/graph -type d | sortLength of output: 529
Would you like me to review any of the remaining unreviewed directories — |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
echo "=== interrupt.go ===" && cat internal/harness/graph/interrupt/interrupt.go
echo "=== interrupt_test.go ===" && cat internal/harness/graph/interrupt/interrupt_test.goLength of output: 11211
Review:
|
| Severity | Issue |
|---|---|
| 🔴 Critical | TOCTOU race — getResumeValues/getInterruptIndex/incrementIndex are 3 non-atomic lock acquisitions |
| 🔴 Critical | nullResume never cleared inside Interrupt() — unbounded duplicate appends |
| 🔴 Critical | Reset() always wipes globalContext, corrupting concurrent in-flight requests |
| 🟠 Medium | getResumeValues() returns raw internal slice — unguarded reference post-lock-release |
| 🟠 Medium | generateInterruptID not unique — same value at different call sites → same ID |
| 🟠 Medium | GetInterruptValue returns *types.Interrupt envelope, not the user's .Value |
| 🔵 Low | TestGlobalContext leaves global state dirty after test |
| 🔵 Low | GetNullResume(consume=true) path has no test coverage |
| 🔵 Nit | GetInterruptContext returns pointer to unexported type |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
echo "=== checkpoint.go ===" && cat internal/harness/graph/checkpoint/checkpoint.go
echo "=== memory.go ===" && cat internal/harness/graph/checkpoint/memory.go
echo "=== nats.go ===" && cat internal/harness/graph/checkpoint/nats.go
echo "=== checkpoint_test.go ===" && cat internal/harness/graph/checkpoint/checkpoint_test.go
echo "=== concurrency_test.go ===" && cat internal/harness/graph/checkpoint/concurrency_test.goLength of output: 55674
Review:
|
| Severity | File | Issue |
|---|---|---|
| 🔴 Critical | checkpoint.go |
Clone() generates two different UUIDs for ID and Metadata.ID |
| 🔴 Critical | checkpoint.go |
Clone() shallow-copies PendingWrites.Value |
| 🔴 Critical | checkpoint.go |
Save() version conflict skipped when ParentID == "" |
| 🔴 Critical | nats.go |
encodeKey is a no-op; no NATS KV key sanitization |
| 🟠 Medium | checkpoint.go |
deepCopy silently returns shallow ref on JSON failure |
| 🟠 Medium | checkpoint.go |
PutWrites TOCTOU race in conflict detection |
| 🟠 Medium | both | Two incompatible in-memory implementations (CheckpointManager vs MemorySaver) |
| 🟠 Medium | nats.go |
uint8(cfg.History) silently truncates History > 255 |
| 🟠 Medium | nats.go |
fmt.Printf in GC instead of structured logger |
| 🔵 Low | checkpoint_test.go |
Raw string "thread_id" instead of constants.ConfigKeyThreadID |
| 🔵 Low | memory.go |
GetState absent from NATSSaver — API asymmetry |
| 🔵 Low | concurrency_test.go |
Conflict test uses t.Logf instead of asserting |
| 🔵 Low | both | Duplicate package doc comment |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
echo "=== managed.go ===" && cat internal/harness/graph/managed/managed.go
echo "=== managed_test.go ===" && cat internal/harness/graph/managed/managed_test.goLength of output: 30518
Review:
|
| Missing coverage | Notes |
|---|---|
Runtime.Clone, Merge, Override |
Core runtime methods entirely untested |
Runtime.Set / Get (with live context) |
context.Context parameter behavior never validated |
PregelScratchpad all methods |
Zero tests for the scratchpad type |
PatchConfig, PatchConfigurable, GetConfigurable |
Side-effect bug in #1 above would be caught here |
ParseCheckpointNS, RecastCheckpointNS |
Stub behavior in #3 above would be caught here |
FormatCheckpoint, FormatTask, FormatValue, FormatDuration |
No format utilities are tested |
IsLastStep.Get, IsLastStep.Set |
The most common managed value is only tested via IsManagedValue |
GetTaskID, GetRuntime, SetRuntime, config accessor helpers |
Config accessor functions have no tests |
Summary Table
| Severity | Issue |
|---|---|
| 🔴 Critical | PatchConfigurable mutates original base map's configurable in-place |
| 🔴 Critical | ExtractManagedValues/ExtractManagedValueSpecs panic on unexported struct fields |
| 🟠 Medium | splitCheckpointNS is a stub — ParseCheckpointNS/RecastCheckpointNS are non-functional |
| 🟠 Medium | isTaskID heuristic too broad — valid node names misclassified |
| 🟠 Medium | DEFAULT_RUNTIME.Configurable shared mutable map — data race risk |
| 🟠 Medium | ManagedValueMapping not concurrency-safe |
| 🟠 Medium | Runtime.Merge silently ignores Step == 0 (valid initial step) |
| 🟠 Medium | get_runtime unexported dead code duplicating GetRuntime |
| 🟡 Low | Runtime.Set/Get accept unused context.Context |
| 🟡 Low | FormatDuration millisecond input not documented — conflicts with time.Duration |
| 🟡 Low | containsDash/containsUnderscore reinvent strings.ContainsRune |
| 🔵 Gap | Large test coverage gaps for Runtime, PregelScratchpad, config helpers, NS functions, formatters |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
fd . internal/harness/graph/task --type f -e go | sortLength of output: 198 🏁 Script executed: #!/bin/bash
echo "=== decorator.go ===" && cat internal/harness/graph/task/decorator.go
echo "=== decorator_test.go ===" && cat internal/harness/graph/task/decorator_test.goLength of output: 23183
Review:
|
| Severity | Issue |
|---|---|
| 🔴 Critical | Cached() stores policy but Wrap() never applies it — caching is silently broken |
| 🔴 Critical | Entrypoint.Invoke / Stream bypass the graph and call raw Execute |
| 🔴 Critical | AInvoke / ABatch discard errors; no way to observe async results |
| 🔴 Critical | Entrypoint.compiled has a data race under concurrent Invoke calls |
| 🟠 Medium | addJitter is deterministic and only subtracts — not true jitter |
| 🟠 Medium | Entrypoint.Compile is a stub that does nothing |
| 🟠 Medium | Batch is sequential, not concurrent |
| 🟠 Medium | pow should use math.Pow |
| 🟡 Low | InvokeWithDependencies also bypasses the graph |
| 🟡 Low | TestCompose comment describes wrong decorator order |
| 🟡 Low | Many exported symbols have no test coverage |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
echo "=== Directory listing ===" && find internal/harness/graph/runnable -type f | sort
echo ""
echo "=== File contents ==="
for f in $(find internal/harness/graph/runnable -type f -name "*.go" | sort); do
echo "===== $f ====="
cat "$f"
echo ""
doneLength of output: 32610
Review:
|
| Severity | File | Issue |
|---|---|---|
| 🔴 Critical | inject.go |
Tracer.TraceCallback() — data race on currentInput and spans |
| 🔴 Critical | runnable.go |
Stream silently drops errors in all four implementations |
| 🔴 Critical | runnable.go |
RunnableParallel.Invoke always passes nil input to sub-runnables |
| 🔴 Critical | inject.go |
buildArguments misleading indentation hides latent nil-dereference |
| 🟡 Medium | runnable.go |
NewRunnableSeq type-compatibility check is always a no-op |
| 🟡 Medium | inject.go |
Non-deterministic runtime value injection (map iteration) |
| 🟡 Medium | inject.go |
CoerceToInjectableRunnable type switch misses non-any Runnable instantiations |
| 🟡 Medium | inject.go |
executeWithArgs panics on non-nillable second return values |
| 🔵 Low | runnable.go |
RunnableError lacks Unwrap/errors.Is/errors.As |
| 🔵 Low | runnable_test.go |
Zero test coverage for inject.go |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
internal/harness/graph/channels/barrier.go (2)
465-485:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
LastValueAfterFinishrestore losesfinishedstate.
Checkpoint()persists onlyvalue, whileGet()/IsAvailable()requirefinished == true. After restore, availability semantics change becausefinishedresets to false.Proposed fix (with backward-compatible restore)
func (c *LastValueAfterFinish) Checkpoint() interface{} { c.mu.RLock() defer c.mu.RUnlock() - return c.value + if IsMissing(c.value) && !c.finished { + return Missing + } + return map[string]interface{}{ + "value": c.value, + "finished": c.finished, + } } // FromCheckpoint restores the channel from a checkpoint. func (c *LastValueAfterFinish) FromCheckpoint(checkpoint interface{}) Channel { c.mu.Lock() defer c.mu.Unlock() newCh := NewLastValueAfterFinish(c.Typ) newCh.Key = c.Key - if !IsMissing(checkpoint) { - newCh.value = checkpoint - } + if IsMissing(checkpoint) || checkpoint == nil { + return newCh + } + // Backward compatibility: old checkpoints may store raw value only. + if cp, ok := checkpoint.(map[string]interface{}); ok { + if v, ok := cp["value"]; ok && !IsMissing(v) { + newCh.value = v + } + if finished, ok := cp["finished"].(bool); ok { + newCh.finished = finished + } + return newCh + } + newCh.value = checkpoint return newCh }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/channels/barrier.go` around lines 465 - 485, The `Checkpoint()` and `FromCheckpoint()` methods in `LastValueAfterFinish` are not persisting the `finished` state, causing restored channels to lose their availability semantics. Modify `Checkpoint()` to return a structure or map containing both the `value` and `finished` state instead of just returning `c.value`. Then update `FromCheckpoint()` to extract and restore both fields from the checkpoint, handling backward compatibility by checking if the checkpoint is in the old format (a simple value) versus the new format (a structure containing both value and finished state). After restoration, set `newCh.finished` to the restored value so that `Get()` and `IsAvailable()` operate correctly.
307-311:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winCheckpoint leaks mutable internal state (
seen) instead of snapshotting it.At Line 309,
Checkpoint()storesc.seenby reference. That escapes the channel’s lock and allows post-checkpoint mutation/races, so persisted state may be inconsistent with the snapshot moment.Proposed fix
func (c *NamedBarrierValueAfterFinish) Checkpoint() interface{} { c.mu.RLock() defer c.mu.RUnlock() if len(c.seen) == 0 && !c.finished { return Missing } - // Return as a map with both values + seenCopy := make(map[string]bool, len(c.seen)) + for k, v := range c.seen { + seenCopy[k] = v + } + result := map[string]interface{}{ - "seen": c.seen, + "seen": seenCopy, "finished": c.finished, } return result }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/channels/barrier.go` around lines 307 - 311, The Checkpoint() method is leaking a reference to the mutable internal state c.seen instead of creating a snapshot. To fix this, replace the direct assignment of c.seen in the result map with a copy or snapshot of c.seen (such as creating a new map with the same contents if c.seen is a map, or using appropriate copy mechanisms for its actual data type). Keep the c.finished value as is. This ensures the returned checkpoint state is immutable and prevents external code from modifying the channel's internal state after the checkpoint is taken.internal/harness/graph/checkpoint/checkpoint.go (3)
624-631:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Listreturns oldest-first but comment says "most recent first".The comment on line 624 says "Return most recent checkpoints first" but the loop iterates from
starttolen(checkpoints)in ascending order, producing oldest-first results within the returned slice.🐛 Fix to return most recent first (as documented)
// Return most recent checkpoints first result := make([]*Checkpoint, limit) - start := len(checkpoints) - limit - for i := 0; i < limit; i++ { - result[i] = checkpoints[start+i].Clone() + for i := 0; i < limit; i++ { + result[i] = checkpoints[len(checkpoints)-1-i].Clone() }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/checkpoint/checkpoint.go` around lines 624 - 631, The List function has a comment stating "Return most recent checkpoints first" but the loop iterates from start to len(checkpoints) in ascending order, which produces oldest-first results. To fix this, reverse the iteration so that the result slice contains most recent checkpoints first: iterate the loop from limit-1 down to 0 and access checkpoints at indices that go from highest to lowest, or iterate forward but assign to the result array in reverse order (assigning to result[limit-1-i] instead of result[i]).
164-165:⚠️ Potential issue | 🟠 Major | ⚡ Quick winShallow copy of
PendingWritesmay leak mutable references.
copy(clone.PendingWrites, c.PendingWrites)performs a shallow copy. If anyPendingWrite.Valuecontains a map or slice, mutations to the original checkpoint's pending writes will affect the clone. This contradicts the method's stated purpose of creating a "deep copy."🐛 Proposed fix to deep copy PendingWrites values
// Copy pending writes - copy(clone.PendingWrites, c.PendingWrites) + for i, pw := range c.PendingWrites { + clone.PendingWrites[i] = PendingWrite{ + Channel: pw.Channel, + Value: deepCopy(pw.Value), + Overwrite: pw.Overwrite, + Node: pw.Node, + Timestamp: pw.Timestamp, + TaskID: pw.TaskID, + } + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/checkpoint/checkpoint.go` around lines 164 - 165, The shallow copy operation on PendingWrites using the built-in copy function does not deep copy mutable values within PendingWrite.Value (such as maps or slices), allowing mutations in the original checkpoint to affect the clone. Replace the simple copy(clone.PendingWrites, c.PendingWrites) with an explicit iteration through each PendingWrite element, where each element's Value is deep copied using appropriate deep copy logic (such as cloning maps and slices individually) to ensure true independence between the original and cloned checkpoint's pending writes.
242-251:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
ToMapdropsTimestampandTaskIDfrom pending writes.Serialization omits
TimestampandTaskIDfields fromPendingWrite, causing data loss during round-trip serialization viaToMap/FromMap. If these fields are populated (viaNewPendingWrite), they will be silently discarded.🐛 Proposed fix to preserve all PendingWrite fields
pendingWrites := make([]map[string]interface{}, len(c.PendingWrites)) for i, pw := range c.PendingWrites { pendingWrites[i] = map[string]interface{}{ "channel": pw.Channel, "value": pw.Value, "overwrite": pw.Overwrite, "node": pw.Node, + "timestamp": pw.Timestamp.Format(time.RFC3339Nano), + "task_id": pw.TaskID, } }And in
FromMap(lines 311-323):if pwMap, ok := pw.(map[string]interface{}); ok { + var timestamp time.Time + if ts := getString(pwMap, "timestamp"); ts != "" { + timestamp, _ = time.Parse(time.RFC3339Nano, ts) + } c.PendingWrites = append(c.PendingWrites, PendingWrite{ Channel: getString(pwMap, "channel"), Overwrite: getBool(pwMap, "overwrite", false), Node: getString(pwMap, "node"), Value: pwMap["value"], + Timestamp: timestamp, + TaskID: getString(pwMap, "task_id"), }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/checkpoint/checkpoint.go` around lines 242 - 251, The ToMap method in the pendingWrites serialization is missing the Timestamp and TaskID fields from the PendingWrite struct, causing data loss during round-trip serialization. In the map construction for pendingWrites where you iterate over c.PendingWrites and create the map with Channel, Value, Overwrite, and Node fields, add the missing Timestamp and TaskID fields to the map. Additionally, update the corresponding FromMap method (lines 311-323) to read these two fields back from the map when reconstructing PendingWrite objects to ensure full deserialization.
🧹 Nitpick comments (2)
internal/harness/graph/checkpoint/checkpoint.go (2)
807-818: 💤 Low value
deepCopysilently returns original reference on marshal/unmarshal failure.When JSON serialization fails (e.g., for types with cyclic references, unexported fields, or channel types), the function returns the original value rather than a copy. This could leak mutable references without warning. Consider logging when this fallback occurs.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/checkpoint/checkpoint.go` around lines 807 - 818, The deepCopy function in checkpoint.go silently returns the original value reference when JSON marshaling or unmarshaling operations fail, which can leak mutable references without warning. Add logging at both error points where the function falls back to returning the original value: first when json.Marshal fails (after the first err check) and second when json.Unmarshal fails (after the second err check). Include the actual error details in the log messages to make the fallback behavior explicit and aid in debugging.
198-206: ⚡ Quick win
AddPendingWriteomitsTimestampandTaskIDthatNewPendingWritesets.
NewPendingWrite(line 72-81) populatesTimestampandTaskID, butAddPendingWritecreates aPendingWritewithout these fields. This inconsistency means writes added viaAddPendingWritewill have zero timestamps and empty task IDs, complicating debugging and audit trails.♻️ Proposed fix to align AddPendingWrite with NewPendingWrite
-// AddPendingWrite adds a pending write. -func (c *Checkpoint) AddPendingWrite(channel string, value interface{}, overwrite bool, node string) { - c.PendingWrites = append(c.PendingWrites, PendingWrite{ - Channel: channel, - Value: value, - Overwrite: overwrite, - Node: node, - }) +// AddPendingWrite adds a pending write with optional taskID. +func (c *Checkpoint) AddPendingWrite(channel string, value interface{}, overwrite bool, node, taskID string) { + c.PendingWrites = append(c.PendingWrites, PendingWrite{ + Channel: channel, + Value: value, + Overwrite: overwrite, + Node: node, + Timestamp: time.Now(), + TaskID: taskID, + }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/checkpoint/checkpoint.go` around lines 198 - 206, The AddPendingWrite method is creating PendingWrite objects without populating the Timestamp and TaskID fields, while NewPendingWrite includes these fields. Update the AddPendingWrite method to populate both Timestamp (with the current time) and TaskID fields when creating the PendingWrite struct, aligning its behavior with how NewPendingWrite initializes these fields. This ensures writes added via AddPendingWrite have consistent metadata for debugging and audit purposes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/harness/graph/checkpoint/checkpoint.go`:
- Around line 555-562: The conflict detection logic in PutWrites is incomplete
because it allows empty checkpoint_id values to bypass the version-chain check.
The current condition requires both callerID to be non-empty AND different from
current.ID to trigger an error, which means empty callerID silently passes
through. Refactor the logic to first require that checkpoint_id is always
provided (non-empty), returning an error if missing, then separately check if
the provided checkpoint_id matches current.ID. This ensures stale writers cannot
bypass version-chain conflict detection.
- Around line 510-521: The version conflict detection in the checkpoint
validation logic at line 515 is skipped when the ParentID does not match the
latest checkpoint ID. The current combined condition `latest.ID ==
checkpoint.ParentID && latest.Version != checkpoint.Version-1` means version
validation only occurs if both conditions are true, allowing version conflicts
to go undetected. Restructure the logic to separate the ParentID check from the
version validation, ensuring that the version is always validated when
checkpoints exist (checking if the version is the expected sequential number),
regardless of whether the ParentID matches the latest checkpoint ID.
---
Outside diff comments:
In `@internal/harness/graph/channels/barrier.go`:
- Around line 465-485: The `Checkpoint()` and `FromCheckpoint()` methods in
`LastValueAfterFinish` are not persisting the `finished` state, causing restored
channels to lose their availability semantics. Modify `Checkpoint()` to return a
structure or map containing both the `value` and `finished` state instead of
just returning `c.value`. Then update `FromCheckpoint()` to extract and restore
both fields from the checkpoint, handling backward compatibility by checking if
the checkpoint is in the old format (a simple value) versus the new format (a
structure containing both value and finished state). After restoration, set
`newCh.finished` to the restored value so that `Get()` and `IsAvailable()`
operate correctly.
- Around line 307-311: The Checkpoint() method is leaking a reference to the
mutable internal state c.seen instead of creating a snapshot. To fix this,
replace the direct assignment of c.seen in the result map with a copy or
snapshot of c.seen (such as creating a new map with the same contents if c.seen
is a map, or using appropriate copy mechanisms for its actual data type). Keep
the c.finished value as is. This ensures the returned checkpoint state is
immutable and prevents external code from modifying the channel's internal state
after the checkpoint is taken.
In `@internal/harness/graph/checkpoint/checkpoint.go`:
- Around line 624-631: The List function has a comment stating "Return most
recent checkpoints first" but the loop iterates from start to len(checkpoints)
in ascending order, which produces oldest-first results. To fix this, reverse
the iteration so that the result slice contains most recent checkpoints first:
iterate the loop from limit-1 down to 0 and access checkpoints at indices that
go from highest to lowest, or iterate forward but assign to the result array in
reverse order (assigning to result[limit-1-i] instead of result[i]).
- Around line 164-165: The shallow copy operation on PendingWrites using the
built-in copy function does not deep copy mutable values within
PendingWrite.Value (such as maps or slices), allowing mutations in the original
checkpoint to affect the clone. Replace the simple copy(clone.PendingWrites,
c.PendingWrites) with an explicit iteration through each PendingWrite element,
where each element's Value is deep copied using appropriate deep copy logic
(such as cloning maps and slices individually) to ensure true independence
between the original and cloned checkpoint's pending writes.
- Around line 242-251: The ToMap method in the pendingWrites serialization is
missing the Timestamp and TaskID fields from the PendingWrite struct, causing
data loss during round-trip serialization. In the map construction for
pendingWrites where you iterate over c.PendingWrites and create the map with
Channel, Value, Overwrite, and Node fields, add the missing Timestamp and TaskID
fields to the map. Additionally, update the corresponding FromMap method (lines
311-323) to read these two fields back from the map when reconstructing
PendingWrite objects to ensure full deserialization.
---
Nitpick comments:
In `@internal/harness/graph/checkpoint/checkpoint.go`:
- Around line 807-818: The deepCopy function in checkpoint.go silently returns
the original value reference when JSON marshaling or unmarshaling operations
fail, which can leak mutable references without warning. Add logging at both
error points where the function falls back to returning the original value:
first when json.Marshal fails (after the first err check) and second when
json.Unmarshal fails (after the second err check). Include the actual error
details in the log messages to make the fallback behavior explicit and aid in
debugging.
- Around line 198-206: The AddPendingWrite method is creating PendingWrite
objects without populating the Timestamp and TaskID fields, while
NewPendingWrite includes these fields. Update the AddPendingWrite method to
populate both Timestamp (with the current time) and TaskID fields when creating
the PendingWrite struct, aligning its behavior with how NewPendingWrite
initializes these fields. This ensures writes added via AddPendingWrite have
consistent metadata for debugging and audit purposes.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 9ea5bb6f-9b2c-452a-9a42-f93d5fcc3e05
📒 Files selected for processing (18)
internal/harness/graph/channels/barrier.gointernal/harness/graph/channels/base.gointernal/harness/graph/channels/binop.gointernal/harness/graph/channels/topic.gointernal/harness/graph/channels/untracked.gointernal/harness/graph/checkpoint/checkpoint.gointernal/harness/graph/checkpoint/memory.gointernal/harness/graph/graph/compiled.gointernal/harness/graph/graph/graph.gointernal/harness/graph/graph/graph_integration_test.gointernal/harness/graph/graph/graph_test.gointernal/harness/graph/graph/message.gointernal/harness/graph/interrupt/interrupt.gointernal/harness/graph/managed/managed.gointernal/harness/graph/runnable/inject.gointernal/harness/graph/runnable/runnable.gointernal/harness/graph/task/decorator.gointernal/harness/graph/task/decorator_test.go
💤 Files with no reviewable changes (1)
- internal/harness/graph/graph/graph_test.go
🚧 Files skipped from review as they are similar to previous changes (10)
- internal/harness/graph/channels/untracked.go
- internal/harness/graph/channels/topic.go
- internal/harness/graph/channels/binop.go
- internal/harness/graph/checkpoint/memory.go
- internal/harness/graph/graph/compiled.go
- internal/harness/graph/interrupt/interrupt.go
- internal/harness/graph/graph/graph_integration_test.go
- internal/harness/graph/graph/message.go
- internal/harness/graph/managed/managed.go
- internal/harness/graph/graph/graph.go
|
@CodeRabbit review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (6)
internal/harness/graph/pregel/engine.go (6)
240-266:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winCritical: Checkpoint restoration is unreachable.
applyInput(line 241) callstoMap(input)which returns an error wheninput == nil(line 1236-1238). This means wheninput == nil, the function returns early at line 242-244, and the checkpoint restoration block at lines 252-266 is never reached.The documented resume-from-checkpoint flow (where callers pass
nilinput to resume) cannot work.🐛 Proposed fix: Skip applyInput for nil input
- // Apply input to channels - if err := e.applyInput(channelRegistry, input); err != nil { - errCh <- fmt.Errorf("failed to apply input: %w", err) - return - } - // Get thread ID for checkpointing threadID := e.getThreadID() // Load checkpoint only when resuming (input == nil). // New executions (input != nil) start from scratch — checkpoint is not loaded, // preventing state from bleeding across independent runs on the same Engine. if input == nil && e.checkpointer != nil { cpData, err := e.checkpointer.Get(ctx, map[string]interface{}{ constants.ConfigKeyThreadID: threadID, }) if err == nil && cpData != nil { if err := channelRegistry.RestoreFromCheckpoint(cpData); err != nil { errCh <- fmt.Errorf("failed to restore from checkpoint: %w", err) return } // Load checkpoint object if cp, err := checkpoint.FromMap(cpData); err == nil { e.currentCheckpoint = cp } } - } + } else if input != nil { + // Apply input to channels only for new executions + if err := e.applyInput(channelRegistry, input); err != nil { + errCh <- fmt.Errorf("failed to apply input: %w", err) + return + } + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine.go` around lines 240 - 266, The applyInput function is being called unconditionally even when input is nil, but toMap(input) inside applyInput returns an error when input is nil, causing an early return before the checkpoint restoration block can execute. To fix this, wrap the applyInput call with a conditional check so that it only executes when input is not nil, allowing the checkpoint restoration code at the bottom of the block to be reachable when resuming from a checkpoint with nil input.
1194-1205:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winError silently ignored in
buildOutput.When
registry.GetValues()returns an error, it's silently swallowed andlastStateis returned instead. Consider logging or propagating the error.🔧 Proposed fix: Return the error
func (e *Engine) buildOutput(registry *channels.Registry, lastState interface{}) (interface{}, error) { values, err := registry.GetValues() if err != nil { - return lastState, nil + // Log but don't fail - fall back to lastState + if e.debug { + log.Printf("warning: GetValues failed, using lastState: %v", err) + } + return lastState, nil }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine.go` around lines 1194 - 1205, The buildOutput method currently silences errors returned by registry.GetValues() by returning (lastState, nil) when an error occurs. Instead of ignoring the error, propagate it by returning (nil, err) when GetValues() encounters an error, so callers of buildOutput can properly handle and respond to failures in retrieving values from the registry.
1403-1408:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPanic: Unchecked type assertion when
pathis empty.When
path == "", line 1405 performsval.(map[string]interface{})without a type check. Ifvalis not a map (e.g., a primitive or slice), this will panic.🐛 Proposed fix: Add type check
func setNestedField(m map[string]interface{}, path string, val interface{}) { if path == "" { - for k, v := range val.(map[string]interface{}) { - m[k] = v + if valMap, ok := val.(map[string]interface{}); ok { + for k, v := range valMap { + m[k] = v + } } return }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine.go` around lines 1403 - 1408, The setNestedField function performs an unchecked type assertion on val when path is empty, which will panic if val is not a map. Add a type check using the comma-ok pattern to verify that val is actually a map[string]interface{} before attempting to convert it and iterate over it. If the type check fails, handle the error appropriately (either by returning early, logging an error, or panicking with a descriptive message).
1065-1117:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winCritical:
nilcontext passed to condition and branch functions.Lines 1071 and 1103 pass
nilas the context to user-provided condition functions:conditionResult, err := condEdge.Condition(nil, state) // line 1071 branchResult, err := branch.Condition(nil, state) // line 1103If any condition function calls
ctx.Done(),ctx.Err(), orctx.Value(), the nil dereference will panic. This also prevents condition functions from respecting cancellation.🐛 Proposed fix: Pass actual context
Add a
ctxparameter togetNextNodesand pass it through:-func (e *Engine) getNextNodes(node string, state interface{}) map[string]bool { +func (e *Engine) getNextNodes(ctx context.Context, node string, state interface{}) map[string]bool { nextNodes := make(map[string]bool) // Check conditional edges for _, condEdge := range e.graph.GetConditionalEdges() { if condEdge.From == node { - conditionResult, err := condEdge.Condition(nil, state) + conditionResult, err := condEdge.Condition(ctx, state) if err != nil { continue } // ... similar for branch.ConditionUpdate callers to pass context:
- nextNodes := e.getNextNodes(lastCompletedNode, currentState) + nextNodes := e.getNextNodes(ctx, lastCompletedNode, currentState)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine.go` around lines 1065 - 1117, The getNextNodes method is passing nil as the context to user-provided condition functions (condEdge.Condition and branch.Condition calls), which will cause panics if those functions attempt to use context methods like Done(), Err(), or Value(). Add a context parameter to the getNextNodes method signature and pass that context through to both the condEdge.Condition call at line 1071 and the branch.Condition call at line 1103 instead of nil. Then locate all callers of getNextNodes and update them to pass the appropriate context value in their function calls.
749-756:⚠️ Potential issue | 🟠 Major | ⚡ Quick winBug: Incorrect "seen" tracking uses channel names as node identifiers.
The variable
resultNameactually contains channel names (fromwritesByChannelwhich is keyed by channel at line 694), not result/node names. The logic then:
- Checks if a channel name exists in
triggerToNodes(which contains trigger strings)- Calls
markSeen(resultName, channelName)where first param should be a node nameThis conflates channel names with node/trigger names, causing incorrect version tracking.
🐛 Proposed fix: Track seen by result node names
// Mark channels as seen by nodes - for resultName := range writesByChannel { - if _, ok := triggerToNodes[resultName]; ok { - for channelName := range updatedChannels { - e.markSeen(resultName, channelName) - } - } + for _, result := range results { + if result.Err != nil { + continue + } + for channelName := range updatedChannels { + e.markSeen(result.Name, channelName) + } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine.go` around lines 749 - 756, The loop is iterating over channel names from writesByChannel (which is keyed by channel at line 694) and treating them as node names, but resultName contains channel names, not node/trigger names. The markSeen function requires a node name as its first parameter. To fix this, instead of iterating through writesByChannel with resultName as a channel name, iterate over the actual node/trigger names that are keys in triggerToNodes, and for each node that has written to channels in updatedChannels, call markSeen with the proper node name and the updated channel names.
224-231:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftData race: Engine fields mutated without synchronization.
The doc at lines 60-62 states the Engine is "reusable across multiple Run calls." However,
Run()modifies Engine fields (currentCheckpoint,channelVersions,versionsSeen,deferredCheckpoints,backgroundExec) from a goroutine without any mutex protection. ConcurrentRun()calls will race on these fields.🔒 Recommended fix: Add mutex or document single-caller constraint
Either add a mutex to protect per-run state mutations:
type Engine struct { graph *graph.StateGraph + mu sync.Mutex // protects per-run mutable state checkpointer graph.Checkpointer // ... rest of fieldsgo func() { defer close(errCh) + e.mu.Lock() + defer e.mu.Unlock() // Create stream manager for event streamingOr document that concurrent
Run()calls are not supported and callers must serialize.Also applies to: 277-278
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine.go` around lines 224 - 231, The Engine fields currentCheckpoint, channelVersions, versionsSeen, deferredCheckpoints, and backgroundExec are being mutated in the Run() method without any mutex protection, creating a data race when concurrent Run() calls occur. Add a mutex field to the Engine struct and acquire it at the beginning of the Run() method to protect all mutations of these per-run state fields, releasing it after the execution is complete. Alternatively, clearly document in the Engine type that concurrent Run() calls are not supported and callers must serialize access.
🧹 Nitpick comments (2)
internal/harness/graph/checkpoint/concurrency_test.go (1)
383-387: ⚡ Quick winUse unique task IDs per goroutine to avoid conflating conflict checks with task-level idempotency.
At Line 383/Line 386, every goroutine uses
"task1". For a concurrency conflict test, distinct task IDs make the test more robust and isolate version-chain behavior.Suggested test tightening
@@ writes := []PendingWrite{ - *NewPendingWrite("counter", taskNum, false, "node1", "task1"), + *NewPendingWrite("counter", taskNum, false, "node1", fmt.Sprintf("task-%d", taskNum)), } - err := manager.PutWrites(ctx, config, writes, "task1") + taskID := fmt.Sprintf("task-%d", taskNum) + err := manager.PutWrites(ctx, config, writes, taskID)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/checkpoint/concurrency_test.go` around lines 383 - 387, Replace the hardcoded "task1" string with unique task IDs per goroutine to properly test concurrency conflict scenarios. The hardcoded task ID appears in two places within the test loop: as the final parameter in NewPendingWrite and as the final parameter in the manager.PutWrites call. Since taskNum is already available and varies per goroutine, use it to construct distinct task IDs (for example, by formatting taskNum into the task ID string) for both the NewPendingWrite creation and the PutWrites invocation to ensure each goroutine operates with its own task identity.internal/harness/graph/pregel/engine.go (1)
1126-1156: 💤 Low valueUnused
stateparameter increateTaskandcreateTaskInfo.Both functions accept a
state interface{}parameter that is never used. This adds confusion about the API contract.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/harness/graph/pregel/engine.go` around lines 1126 - 1156, Both the createTask and createTaskInfo methods have an unused state interface{} parameter in their function signatures that is never referenced in either method body. Remove the state interface{} parameter from both method signatures and update any call sites that invoke these methods to not pass the state argument, ensuring the methods only accept the parameters they actually use: node, channels, and triggers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/harness/graph/checkpoint/concurrency_test.go`:
- Around line 198-205: Replace the soft assertion pattern in the PutWrites
conflict check where you currently use `if err == nil` followed by `t.Logf` with
a hard assertion that fails the test. Instead, assert that the error is non-nil
and specifically check that it is a `*VersionConflictError` type using type
assertion to prevent false positives when other error types are returned. Apply
this fix at all locations in the test file where this concurrency-conflict
assertion pattern is used, ensuring that version-conflict guarantees are
validated with hard assertions rather than logging.
---
Outside diff comments:
In `@internal/harness/graph/pregel/engine.go`:
- Around line 240-266: The applyInput function is being called unconditionally
even when input is nil, but toMap(input) inside applyInput returns an error when
input is nil, causing an early return before the checkpoint restoration block
can execute. To fix this, wrap the applyInput call with a conditional check so
that it only executes when input is not nil, allowing the checkpoint restoration
code at the bottom of the block to be reachable when resuming from a checkpoint
with nil input.
- Around line 1194-1205: The buildOutput method currently silences errors
returned by registry.GetValues() by returning (lastState, nil) when an error
occurs. Instead of ignoring the error, propagate it by returning (nil, err) when
GetValues() encounters an error, so callers of buildOutput can properly handle
and respond to failures in retrieving values from the registry.
- Around line 1403-1408: The setNestedField function performs an unchecked type
assertion on val when path is empty, which will panic if val is not a map. Add a
type check using the comma-ok pattern to verify that val is actually a
map[string]interface{} before attempting to convert it and iterate over it. If
the type check fails, handle the error appropriately (either by returning early,
logging an error, or panicking with a descriptive message).
- Around line 1065-1117: The getNextNodes method is passing nil as the context
to user-provided condition functions (condEdge.Condition and branch.Condition
calls), which will cause panics if those functions attempt to use context
methods like Done(), Err(), or Value(). Add a context parameter to the
getNextNodes method signature and pass that context through to both the
condEdge.Condition call at line 1071 and the branch.Condition call at line 1103
instead of nil. Then locate all callers of getNextNodes and update them to pass
the appropriate context value in their function calls.
- Around line 749-756: The loop is iterating over channel names from
writesByChannel (which is keyed by channel at line 694) and treating them as
node names, but resultName contains channel names, not node/trigger names. The
markSeen function requires a node name as its first parameter. To fix this,
instead of iterating through writesByChannel with resultName as a channel name,
iterate over the actual node/trigger names that are keys in triggerToNodes, and
for each node that has written to channels in updatedChannels, call markSeen
with the proper node name and the updated channel names.
- Around line 224-231: The Engine fields currentCheckpoint, channelVersions,
versionsSeen, deferredCheckpoints, and backgroundExec are being mutated in the
Run() method without any mutex protection, creating a data race when concurrent
Run() calls occur. Add a mutex field to the Engine struct and acquire it at the
beginning of the Run() method to protect all mutations of these per-run state
fields, releasing it after the execution is complete. Alternatively, clearly
document in the Engine type that concurrent Run() calls are not supported and
callers must serialize access.
---
Nitpick comments:
In `@internal/harness/graph/checkpoint/concurrency_test.go`:
- Around line 383-387: Replace the hardcoded "task1" string with unique task IDs
per goroutine to properly test concurrency conflict scenarios. The hardcoded
task ID appears in two places within the test loop: as the final parameter in
NewPendingWrite and as the final parameter in the manager.PutWrites call. Since
taskNum is already available and varies per goroutine, use it to construct
distinct task IDs (for example, by formatting taskNum into the task ID string)
for both the NewPendingWrite creation and the PutWrites invocation to ensure
each goroutine operates with its own task identity.
In `@internal/harness/graph/pregel/engine.go`:
- Around line 1126-1156: Both the createTask and createTaskInfo methods have an
unused state interface{} parameter in their function signatures that is never
referenced in either method body. Remove the state interface{} parameter from
both method signatures and update any call sites that invoke these methods to
not pass the state argument, ensuring the methods only accept the parameters
they actually use: node, channels, and triggers.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 578a48cf-fbfe-4df5-8283-ded56183aafc
📒 Files selected for processing (6)
internal/harness/graph/checkpoint/checkpoint.gointernal/harness/graph/checkpoint/concurrency_test.gointernal/harness/graph/checkpoint/nats.gointernal/harness/graph/managed/managed.gointernal/harness/graph/pregel/engine.gointernal/harness/graph/task/decorator.go
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/harness/graph/checkpoint/nats.go
- internal/harness/graph/checkpoint/checkpoint.go
- internal/harness/graph/managed/managed.go
| // Second write with the same checkpoint_id → the first write already advanced | ||
| // the version chain, so this should fail with a conflict. | ||
| err = manager.PutWrites(ctx, config1, writes2, "task1") | ||
| if err == nil { | ||
| t.Error("expected conflict error for stale checkpoint_id") | ||
| } else { | ||
| t.Logf("Got expected conflict: %v", err) | ||
| } |
There was a problem hiding this comment.
Fail the test on conflict-assertion mismatch instead of logging.
At Line 204 and Line 402, t.Logf allows the test to pass even when concurrency/version-conflict guarantees are broken. These should be hard assertions, and the conflict-path test should assert *VersionConflictError (not just non-nil error) to prevent false positives.
Proposed assertion hardening
@@
err = manager.PutWrites(ctx, config1, writes2, "task1")
if err == nil {
t.Error("expected conflict error for stale checkpoint_id")
} else {
- t.Logf("Got expected conflict: %v", err)
+ if _, ok := err.(*VersionConflictError); !ok {
+ t.Fatalf("expected VersionConflictError, got %T (%v)", err, err)
+ }
}
@@
if successCount != 1 {
- t.Logf("Expected 1 successful write (version chain), got %d", successCount)
+ t.Fatalf("Expected exactly 1 successful write (version chain), got %d", successCount)
}Also applies to: 399-403
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/harness/graph/checkpoint/concurrency_test.go` around lines 198 -
205, Replace the soft assertion pattern in the PutWrites conflict check where
you currently use `if err == nil` followed by `t.Logf` with a hard assertion
that fails the test. Instead, assert that the error is non-nil and specifically
check that it is a `*VersionConflictError` type using type assertion to prevent
false positives when other error types are returned. Apply this fix at all
locations in the test file where this concurrency-conflict assertion pattern is
used, ensuring that version-conflict guarantees are validated with hard
assertions rather than logging.
### What problem does this PR solve? core module for agent layer built on top of graph engine #16039 ### Type of change - [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve? core module for agent layer built on top of graph engine infiniflow#16039 ### Type of change - [x] New Feature (non-breaking change which adds functionality)
What problem does this PR solve?
go-version of Pregel-based BSP engine
Type of change