Skip to content

Feat: add harness-go framework —— graph engine - #16039

Merged
yingfeng merged 11 commits into
infiniflow:mainfrom
yingfeng:harness_graph
Jun 15, 2026
Merged

yingfeng merged 11 commits into
infiniflow:mainfrom
yingfeng:harness_graph

Conversation

@yingfeng

Copy link
Copy Markdown
Member

What problem does this PR solve?

go-version of Pregel-based BSP engine

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 15, 2026
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds graph channel, checkpoint, graph, and Pregel runtime packages plus broad tests across the harness.

Changes

Graph harness runtime

Layer / File(s) Summary
Channel model and base implementations
internal/harness/graph/channels/*
Adds the channel contract, missing-value semantics, registry operations, channel implementations, reducer wiring, and channel-focused tests.
Runtime constants, errors, managed values, and interrupts
internal/harness/graph/constants/constants.go, internal/harness/graph/errors/*, internal/harness/graph/managed/*, internal/harness/graph/interrupt/*
Defines reserved graph constants, structured graph error types, managed runtime/config helpers, scratchpad/runtime utilities, and resumable interrupt context behavior with tests.
Checkpoint storage and version management
internal/harness/graph/checkpoint/*
Adds checkpoint models, cloning and serialization, conflict-aware checkpoint management, in-memory and NATS-backed savers, and checkpoint persistence/concurrency tests.
Graph model, schema, messages, and compiled execution
internal/harness/graph/graph/graph.go, internal/harness/graph/graph/compiled.go, internal/harness/graph/graph/state.go, internal/harness/graph/graph/message.go, internal/harness/graph/graph/*test.go
Introduces the state-graph builder, schema-driven channel configuration, message graph helpers, compiled subgraph wrapper, inline execution path, and graph integration, concurrency, channel, and recovery tests.
Pregel utilities and supporting subsystems
internal/harness/graph/pregel/async.go, internal/harness/graph/pregel/background.go, internal/harness/graph/pregel/cache*.go, internal/harness/graph/pregel/read*.go, internal/harness/graph/pregel/retry*.go, internal/harness/graph/pregel/stream.go, internal/harness/graph/pregel/messages.go, internal/harness/graph/pregel/remote.go, internal/harness/graph/pregel/subgraph.go, internal/harness/graph/pregel/*test.go
Adds retry, async/background execution, caching, stream events, message chunk aggregation, channel readers and triggers, remote execution over HTTP, subgraph helpers, and supporting tests.
Pregel engine and optimization layers
internal/harness/graph/pregel/engine.go, internal/harness/graph/pregel/optimized.go, internal/harness/graph/pregel/engine_test.go, internal/harness/graph/pregel/optimized_test.go, internal/harness/graph/pregel/pregel_pressure_test.go
Implements the Pregel engine run loop, task scheduling, write application, checkpoints and streaming integration, optimized execution helpers, and large engine pressure and behavior test coverage.

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
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Suggested labels

💞 feature

Poem

🐇 I hopped through graphs with keys in tow,
Where channels bloom and checkpoints grow.
Streams now chatter, retries sing,
Subgraphs hide in burrows spring.
A clever hare salutes this spree—
More paths, more state, more concurrency.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Trailing 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 win

Avoid 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

CollectToMap emitter is not thread-safe.

The emitter writes to the target map 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_RecursionLimit doesn'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 newSimpleGraph already has node_a → node_b → End. Adding another edge node_a → End doesn't create an infinite loop.

Consider using a graph that actually loops (like newLoopGraph from 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

WaitForPending is 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 win

Potential race between emit() and Close() despite mutex.

emit() uses RLock to check closed and 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

NodeToRemoteRunnable ignores the node parameter.

The function accepts a node types.NodeFunc but never uses it. The comment indicates it should "register the node locally and expose it via HTTP", but it only creates a RemoteRunnable pointing 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 win

Potential 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 win

Assert Interrupt errors 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 win

Avoid dropping err values in test assertions.

A few paths ignore Update/Get errors, 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

FormatError is not traversing the actual unwrap chain.

Line 216 uses the original err parameter instead of the loop variable current, so the function cannot properly traverse a wrapped error chain. Replace the buggy unwrap logic with the standard library's errors.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

List ordering 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 win

Expected-error concurrency tests do not assert their expected outcomes.

InterruptRace and TimeoutRace only 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 win

Conflict-path test currently uses the same task ID for both writes.

The second write set (writes2) is created as task2, but PutWrites is 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 value

Fire-and-forget ASet uses context.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

WriteJSON may produce unexpected output.

WriteJSON marshals data to JSON bytes, then passes those bytes to Write, which calls EmitDebug. 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

PriorityQueue is defined but unused.

The PriorityQueue type and its methods are implemented but the BackgroundExecutor uses 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 win

Test doesn't assert that error occurs for nil registry.

PrepareNextTasksOptimized is called with nil registry, 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 win

Hardcoded timeout and no HTTP client configuration.

NewHTTPPregelProtocol hardcodes a 30-second timeout with no way to customize the HTTP client, unlike RemoteRunnable which accepts HTTPClient and Timeout in 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

FinishNotification logs to stdout and discards the notification.

The method creates a FinishNotification struct but only logs to stdout via fmt.Printf and 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 value

No synchronization on ReadContext.Readers map.

AddReader modifies the Readers map while ReadAll iterates over it. If these are called concurrently, a data race occurs.

If ReadContext follows a "build then use" pattern (all AddReader calls complete before ShouldExecute/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 tradeoff

Engine is not safe for concurrent Run calls.

The Engine struct has mutable fields (currentCheckpoint, channelVersions, versionsSeen, deferredCheckpoints) that are modified during Run without synchronization. The docstring says "reusable across multiple Run calls" but doesn't clarify these must be sequential.

Consider either:

  1. Adding a mutex to protect mutable state
  2. Documenting that concurrent Run calls are not supported
  3. Moving per-run state into a separate runContext struct
🤖 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 win

Prefer making reservation policy immutable.

Because Reserved is an exported map, any package can mutate it at runtime and silently change IsReserved behavior.

🤖 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 win

Add checkpoint/restore coverage for after-finish channels.

Current tests validate finish gating, but not checkpoint round-trip of that gate. Add cases for LastValueAfterFinish and NamedBarrierValueAfterFinish that 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 win

Factory 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-int numeric 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d94b08 and 9fb973e.

📒 Files selected for processing (74)
  • internal/harness/graph/channels/any_value.go
  • internal/harness/graph/channels/barrier.go
  • internal/harness/graph/channels/base.go
  • internal/harness/graph/channels/binop.go
  • internal/harness/graph/channels/binop_test.go
  • internal/harness/graph/channels/channels_test.go
  • internal/harness/graph/channels/ephemeral_value.go
  • internal/harness/graph/channels/last_value.go
  • internal/harness/graph/channels/reducer.go
  • internal/harness/graph/channels/reducer_test.go
  • internal/harness/graph/channels/topic.go
  • internal/harness/graph/channels/untracked.go
  • internal/harness/graph/checkpoint/checkpoint.go
  • internal/harness/graph/checkpoint/checkpoint_test.go
  • internal/harness/graph/checkpoint/concurrency_test.go
  • internal/harness/graph/checkpoint/memory.go
  • internal/harness/graph/checkpoint/nats.go
  • internal/harness/graph/constants/constants.go
  • internal/harness/graph/errors/errors.go
  • internal/harness/graph/errors/errors_test.go
  • internal/harness/graph/graph/checkpoint_recovery_test.go
  • internal/harness/graph/graph/compiled.go
  • internal/harness/graph/graph/graph.go
  • internal/harness/graph/graph/graph_channel_test.go
  • internal/harness/graph/graph/graph_concurrency_test.go
  • internal/harness/graph/graph/graph_integration_test.go
  • internal/harness/graph/graph/graph_test.go
  • internal/harness/graph/graph/message.go
  • internal/harness/graph/graph/state.go
  • internal/harness/graph/interrupt/interrupt.go
  • internal/harness/graph/interrupt/interrupt_test.go
  • internal/harness/graph/managed/managed.go
  • internal/harness/graph/managed/managed_test.go
  • internal/harness/graph/pregel/async.go
  • internal/harness/graph/pregel/background.go
  • internal/harness/graph/pregel/cache.go
  • internal/harness/graph/pregel/cache_async.go
  • internal/harness/graph/pregel/cache_test.go
  • internal/harness/graph/pregel/engine.go
  • internal/harness/graph/pregel/engine_test.go
  • internal/harness/graph/pregel/messages.go
  • internal/harness/graph/pregel/optimized.go
  • internal/harness/graph/pregel/optimized_test.go
  • internal/harness/graph/pregel/pregel_pressure_test.go
  • internal/harness/graph/pregel/read.go
  • internal/harness/graph/pregel/read_test.go
  • internal/harness/graph/pregel/remote.go
  • internal/harness/graph/pregel/retry.go
  • internal/harness/graph/pregel/retry_multi.go
  • internal/harness/graph/pregel/stream.go
  • internal/harness/graph/pregel/subgraph.go
  • internal/harness/graph/pregel/subgraph_test.go
  • internal/harness/graph/pregel/write.go
  • internal/harness/graph/pregel/write_test.go
  • internal/harness/graph/runnable/inject.go
  • internal/harness/graph/runnable/runnable.go
  • internal/harness/graph/runnable/runnable_test.go
  • internal/harness/graph/store/base.go
  • internal/harness/graph/store/memory.go
  • internal/harness/graph/store/store_test.go
  • internal/harness/graph/task/decorator.go
  • internal/harness/graph/task/decorator_test.go
  • internal/harness/graph/types/config.go
  • internal/harness/graph/types/config_test.go
  • internal/harness/graph/types/scratchpad.go
  • internal/harness/graph/types/scratchpad_test.go
  • internal/harness/graph/types/stream.go
  • internal/harness/graph/types/stream_test.go
  • internal/harness/graph/types/types.go
  • internal/harness/graph/visualization/draw.go
  • internal/harness/graph/visualization/draw_test.go
  • internal/harness/prebuilt/prebuilt.go
  • internal/harness/prebuilt/prebuilt_edge_test.go
  • internal/harness/prebuilt/prebuilt_test.go

Comment thread internal/harness/graph/pregel/cache.go Resolved
Comment thread internal/harness/graph/pregel/engine.go Resolved
@yingfeng yingfeng added the ci Continue Integration label Jun 15, 2026
@yingfeng
yingfeng marked this pull request as draft June 15, 2026 12:39
@yingfeng
yingfeng marked this pull request as ready for review June 15, 2026 12:40
@yingfeng yingfeng changed the title Add harness-go framework--Graph part Feat: add harness-go framework -- graph engine Jun 15, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Bug: Fix at line 1420 is incomplete; m is already nil when indexed.

The attempted fix stores nm into m[parts[i]], but m was already reassigned to nil by the failed type assertion on line 1417. When sub is not a map[string]interface{}, m receives the zero value (nil), and indexing into it on line 1420 will panic.

Trace for path "a.b" when m["a"] exists but is a string:

  1. sub, ok := m["a"] → sub = "string", ok = true
  2. m, ok2 = sub.(map[string]interface{}) → m = nil, ok2 = false
  3. m[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 tradeoff

Engine state mutation is not thread-safe during concurrent Run calls.

The Run method resets and mutates Engine-level fields (currentCheckpoint, channelVersions, versionsSeen, backgroundExec) without synchronization. If Run is called concurrently on the same Engine instance, these writes will race.

If concurrent usage is expected, consider either:

  1. Documenting that a single Engine must not be used concurrently, or
  2. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9fb973e and aa0beba.

📒 Files selected for processing (4)
  • internal/harness/graph/interrupt/interrupt.go
  • internal/harness/graph/pregel/cache.go
  • internal/harness/graph/pregel/engine.go
  • internal/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

@yingfeng

Copy link
Copy Markdown
Member Author

@CodeRabbit review --dir internal/harness/graph/graph

@yingfeng

Copy link
Copy Markdown
Member Author

@CodeRabbit review --dir internal/harness/graph/channels

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

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" | sort

Length 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.go

Length 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.go

Length of output: 29398



@yingfeng Here is a detailed review of internal/harness/graph/graph.


Review: internal/harness/graph/graph

graph.go

1. AddEdge from Start silently overwrites entryPoint (Line ~303)

Every call to AddEdge(constants.Start, nodeX) unconditionally overwrites g.entryPoint. In graphs with multiple start-to-node edges (DAG fan-out), only the last one is kept, leading to silent data loss. Consider appending to a slice and deriving entryPoint from Validate(), or returning an error when a second Start edge conflicts.

// current — last AddEdge(Start, X) wins
if from == constants.Start {
    g.entryPoint = to   // ← overwrites silently
}

2. nil context passed to condition functions (Line ~553)

In inlineGetNextTasks, conditional edges are evaluated as:

conditionResult, err := condEdge.Condition(nil, currentState)

nil is passed instead of the caller's ctx. If any condition function touches ctx (e.g., for cancellation, tracing, or deadline checks), it will panic or silently bypass cancellation.

// fix:
conditionResult, err := condEdge.Condition(ctx, currentState)

3. Inline fallback runner: nil input breaks checkpoint resume

inlineRun calls inlineApplyInput(channelRegistry, input) unconditionally. inlineToMap(nil) returns error("nil value"), so resume-from-checkpoint with input = nil always fails. The canonical resume pattern requires skipping applyInput when input is nil (the checkpoint itself provides state).

4. Node errors are silently swallowed; failing node causes infinite rescheduling

In inlineExecuteTasks, a node returning an error is appended to results but completedTasks[result.nodeName] is never set. On the next iteration, inlineGetNextTasks re-schedules the same entry-point node indefinitely until the recursion limit fires. The returned error is GraphRecursionError, not the original node error, making debugging opaque. TestGraphIntegration_NodeError passes only because it checks err != nil:

// Current: node error is ignored in scheduling
for _, result := range results {
    if result.err == nil {               // ← failing nodes never complete
        completedTasks[result.nodeName] = true

The fix is to propagate node errors immediately (or collect them and surface the first one).

5. Conditional edges suppress regular edges on same node

if len(nextNodes) == 0 {
    for _, edge := range g.edges { ... }  // regular edges only checked if NO cond-edge matched
}

If a node has both a conditional edge and a regular edge (e.g., always-fan-out plus a fixed next step), the regular edge is completely ignored when conditional targets are found.

6. StateGraph.NodeTriggerMode is mutated during Compile — data race risk

Compile writes to the StateGraph value (g.NodeTriggerMode = cg.nodeTriggerMode). If the same *StateGraph is compiled concurrently with different WithNodeTriggerMode options (valid for multi-tenant usage), this is a data race. Since NodeTriggerMode is only consumed by the engine post-compile, the cleanest fix is to keep it on CompiledGraph only:

// remove this line from Compile():
g.NodeTriggerMode = cg.nodeTriggerMode

7. Undocumented __root__ magic key in inlineToMap

return map[string]interface{}{"__root__": v}, nil

Scalar/non-struct values are silently wrapped under "__root__". No downstream code handles or documents this key, and it will silently fail channel lookups. Either return an error for unsupported types, or document the contract explicitly.


compiled.go

8. MigrateCheckpoint — inverted checkpoint map bookkeeping

When migrating to a subgraph:

subgraph.checkpointMap[newCheckpointID] = checkpointID   // stored in child
c.checkpointMap[checkpointID]           = newCheckpointID // stored in parent

When migrating from a subgraph (reverse, toSubgraph == ""):

parentCheckpointID, exists := c.checkpointMap[checkpointID]

Here c is the child graph calling back to parent, but c.checkpointMap[checkpointID] would return newCheckpointID (the child's own id) — not the original parent ID. The bidirectional mapping needs to use separate parent/child maps or a dedicated struct.

9. generateCheckpointID() is not collision-safe under concurrency

return fmt.Sprintf("cp_%d", time.Now().UnixNano())

Multiple concurrent migrations within the same nanosecond produce identical IDs. Use github.com/google/uuid (already imported in graph.go):

return "cp_" + uuid.New().String()

10. Dead code: buildTaskPath result discarded immediately

taskPath := buildTaskPath(c.namespace, toSubgraph)
_ = taskPath   // ← TODO comment implied but never implemented

Either implement checkpoint migration using taskPath, or remove the call until it is needed.


state.go

11. Double schema validation during Compile

Compile calls g.Validate() → g.ValidateStateSchema() → validateStateSchema(g.stateSchema), then immediately calls g.configureChannelsFromSchema() → g.GetStateSchemaInfo() → validateStateSchema(g.stateSchema) again. This is redundant and wasteful for large schemas. Cache the result from Validate() or pass it to configureChannelsFromSchema().

12. Built-in reducers map duplicates channels/reducer.go logic

state.go defines add, append, and merge inline reducers; channels/reducer.go exports AddReducer, AppendReducer, MergeReducer. These have divergent implementations (e.g., state.go's append wraps scalars in a slice, channels/reducer.go's AppendReducer builds a 2-element list). Consider aliasing to the canonical versions:

var reducers = map[string]types.ReducerFunc{
    "add":    func(c, u interface{}) interface{} { return channels.AddReducer(c, u) },
    "append": func(c, u interface{}) interface{} { return channels.AppendReducer(c, u) },
    "merge":  func(c, u interface{}) interface{} { return channels.MergeReducer(c, u) },
}

message.go

13. NewMessageGraph never registers the messages channel

NewMessageGraph() records g.messagesChannel = "messages" but never calls g.graph.AddChannel("messages", ...). Any call to GetMessages() will always return an empty slice because channelRegistry.Get("messages") will never find the channel.

14. MessageGraph.SetEntryPoint silently ignores errors

func (g *MessageGraph) SetEntryPoint(node string) {
    g.graph.SetEntryPoint(node)  // error return discarded
}

The error (e.g., node not found) is silently dropped. This should either return the error or panic with a clear message:

func (g *MessageGraph) SetEntryPoint(node string) error {
    return g.graph.SetEntryPoint(node)
}

15. GraphError duplicates errors/errors.go — lacks errors.Is/errors.As support

message.go defines its own GraphError while errors/errors.go already provides a rich hierarchy with ErrorContext, wrapping, and code constants. GraphError cannot be matched with errors.As from call sites. Migrate to the existing error types or add Is/As support.


Tests

16. Duplicate check in TestAddEdge (Line ~67, graph_test.go)

err = builder.AddEdge("node_a", "nonexistent")
if err == nil {
    t.Error("Expected error for non-existent node")
}
if err == nil {   // ← identical duplicate block
    t.Error("Expected error for non-existent node")
}

17. TestGraphIntegration_FieldMapping masks a real compile error

The test adds a DataEdge from "lookup" to "format" but no regular AddEdge from "lookup" to "format". "format" is therefore unreachable from "lookup" through computeReachable, causing Validate() to fail. The test calls t.Skipf on this failure, hiding what should be a pass or a known-limitation note:

if err != nil {
    t.Skipf("FieldMapping compile: %v (expected feature not fully wired)", err)
}

Consider either wiring the data edge properly (add a control-flow edge too) or converting the skip to t.Logf + explicit expectation.


Summary Table

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

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

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.go

Length of output: 51590



@yingfeng Here is the review of internal/harness/graph/channels:


Review: internal/harness/graph/channels

🔴 Critical

1. Registry has no mutex — data race on concurrent access (base.go)

All Registry methods (Register, Get, Remove, Names, CreateCheckpoint, RestoreFromCheckpoint, UpdateChannels, GetValues) read/write r.channels without any synchronization. The concurrency tests (graph_concurrency_test.go) run multiple goroutines against the same compiled graph; if the engine creates registries from shared channel definitions, this is a data race.

// base.go
type Registry struct {
    mu       sync.RWMutex   // ← add
    channels map[string]Channel
}

func (r *Registry) Register(name string, channel Channel) {
    r.mu.Lock()
    defer r.mu.Unlock()
    r.channels[name] = channel
}

func (r *Registry) Get(name string) (Channel, bool) {
    r.mu.RLock()
    defer r.mu.RUnlock()
    ch, ok := r.channels[name]
    return ch, ok
}
// ... apply same pattern to Remove, Names/List, CreateCheckpoint, RestoreFromCheckpoint, UpdateChannels, GetValues

2. NamedBarrierValue / NamedBarrierValueAfterFinish checkpoint type assertion breaks after JSON serialization (barrier.go)

Checkpoint() stores a map[string]bool (for NamedBarrierValue) or a map[string]interface{}{"seen": map[string]bool{...}} (for NamedBarrierValueAfterFinish). Any real checkpoint backend (NATS, database) round-trips through JSON, which decodes bool-valued maps as map[string]interface{}. The type assertions in FromCheckpoint will then silently fail and seen will be empty, effectively losing the barrier state.

// barrier.go – NamedBarrierValue.FromCheckpoint
// BEFORE (breaks after JSON round-trip):
if cp, ok := checkpoint.(map[string]bool); ok { ... }

// AFTER:
switch v := checkpoint.(type) {
case map[string]bool:
    newCh.seen = make(map[string]bool, len(v))
    for k, bv := range v { newCh.seen[k] = bv }
case map[string]interface{}:
    newCh.seen = make(map[string]bool, len(v))
    for k, bv := range v {
        if b, ok := bv.(bool); ok { newCh.seen[k] = b }
    }
}

Apply the same fix for NamedBarrierValueAfterFinish.FromCheckpoint where cp["seen"].(map[string]bool) is used.


3. UntrackedValue.Copy() silently drops the channel key (untracked.go)

Every other Copy() implementation copies c.Key. UntrackedValue.Copy() returns a brand-new channel without it, so any downstream code that relies on the key (error messages, engine routing) will see an empty string.

// BEFORE:
func (c *UntrackedValue) Copy() Channel {
    return NewUntrackedValue(c.Typ)
}

// AFTER:
func (c *UntrackedValue) Copy() Channel {
    newCh := NewUntrackedValue(c.Typ)
    newCh.Key = c.Key
    return newCh
}

🟡 Medium

4. Broken panic recovery in createZeroValue (binop.go)

The deferred recovery closes over no named return value, so it cannot actually return Missing on a panic — the function will return nil instead. The caller NewBinaryOperatorAggregate will then set c.value = nil, and IsMissing(nil) returns false, so the channel will incorrectly appear available with a nil value.

// BEFORE (recovery does nothing useful):
defer func() {
    if r := recover(); r != nil {
        // Cannot create zero value, return Missing  ← does NOT return Missing
    }
}()
zero := reflect.Zero(rt)
return zero.Interface()

// AFTER (use named return):
func createZeroValue(typ interface{}) (result interface{}) {
    result = Missing
    if typ == nil { return }
    // ...
    defer func() {
        if r := recover(); r != nil {
            result = Missing
        }
    }()
    zero := reflect.Zero(rt)
    result = zero.Interface()
    return
}

5. BinaryOperatorAggregate.Update silently discards non-overwrite values that follow an overwrite in the same batch (binop.go)

When a batch contains [overwrite(X), normalValue], normalValue is silently ignored because the if !seenOverwrite guard wraps the operator application. This is undocumented and may surprise callers who expect all values to be combined.

for _, value := range values {
    isOver, overwriteValue := isOverwrite(value)
    if isOver {
        ...
        seenOverwrite = true
        continue
    }
    if !seenOverwrite { // ← values after an overwrite are silently dropped
        c.value = c.operator(c.value, value)
    }
}

Either document this as intentional ("overwrite wins, subsequent values in same batch are ignored") or return an InvalidUpdateError if non-overwrite values follow an overwrite.


6. Topic.Checkpoint() returns an empty []interface{}{} instead of Missing for an empty channel (topic.go)

Registry.CreateCheckpoint() uses IsMissing(cp) to skip channels that have no state worth saving. An empty Topic returns []interface{}{}, which is not Missing, so it is always included in every checkpoint unnecessarily. Consider:

func (c *Topic) Checkpoint() interface{} {
    if len(c.values) == 0 {
        return Missing
    }
    result := make([]interface{}, len(c.values))
    copy(result, c.values)
    return result
}

And update FromCheckpoint to handle Missing accordingly (it already does via the !IsMissing(checkpoint) guard).


🔵 Low / Informational

7. EphemeralValue.Get() has a destructive side-effect that interacts with Registry.GetValues() (ephemeral_value.go)

Get() clears the stored value. If the Pregel engine calls Get() to pass the value to a node, and later calls Registry.GetValues() to build the output state, the ephemeral channel will already be Missing and will be absent from the output. This is the intended "fire-and-forget" semantics but is easy to miss. A doc comment on Get() noting that the call is destructive and the implications for GetValues() would help maintainers.

8. Missing test coverage for LastValueAfterFinish (barrier.go)

channels_test.go covers NamedBarrierValue and NamedBarrierValueAfterFinish but not LastValueAfterFinish. At minimum, the Finish()-gates-Get, Update single-value enforcement, and checkpoint round-trip cases should be covered.

9. Duplicate package channels doc comment (barrier.go vs base.go)

barrier.go has // Package channels provides channel implementations for LangGraph Go. at the top, and so does base.go. The Go convention is to have the package doc comment in exactly one file (typically doc.go or base.go). Remove the one in barrier.go.

@codecov

codecov Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (e3cb86d) to head (9bbeb28).
⚠️ Report is 7 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yingfeng

Copy link
Copy Markdown
Member Author

@CodeRabbit review --dir internal/harness/graph/checkpoint

@yingfeng

Copy link
Copy Markdown
Member Author

@CodeRabbit review --dir internal/harness/graph/interrupt

@yingfeng

Copy link
Copy Markdown
Member Author

@CodeRabbit review --dir internal/harness/graph/managed

@yingfeng

Copy link
Copy Markdown
Member Author

@CodeRabbit review --dir internal/harness/graph/runnable

@yingfeng

Copy link
Copy Markdown
Member Author

@CodeRabbit review --dir internal/harness/graph/task

@yingfeng

Copy link
Copy Markdown
Member Author

@CodeRabbit review --dir internal/harness/graph/prebuilt

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

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 | sort

Length of output: 529



@yingfeng There is no prebuilt directory in internal/harness/graph. Here are all existing subdirectories:

Directory Status
channels ✅ Reviewed
checkpoint ✅ Reviewed
constants —
errors —
graph ✅ Reviewed
interrupt ✅ Reviewed
managed ✅ Reviewed
pregel —
runnable ✅ (requested)
store —
task ✅ (requested)
types —
visualization —

Would you like me to review any of the remaining unreviewed directories — pregel, store, types, visualization, constants, or errors? Just use @CodeRabbit review --dir <path> or let me know which ones to prioritize.

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

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.go

Length of output: 11211



@yingfeng Here is the detailed review of internal/harness/graph/interrupt.


Review: internal/harness/graph/interrupt

🔴 Critical

1. TOCTOU race in Interrupt() — three non-atomic mutex acquisitions

getResumeValues(), getInterruptIndex(), and incrementIndex() each acquire and release the mutex independently. Between any two of these calls a concurrent goroutine can append a resume value or increment the index, leading to stale reads, double-consumption of a resume value, or an out-of-bounds index:

// interrupt.go — Lines ~57-65 (three separate lock windows)
resumeValues := ic.getResumeValues()   // lock/unlock 1
idx := ic.getInterruptIndex()          // lock/unlock 2

if idx < len(resumeValues) {
    ic.incrementIndex()                // lock/unlock 3  ← races with all of the above
    return resumeValues[idx], nil
}

The entire read-check-increment must execute under a single lock:

func (ic *interruptContext) consumeNextResumeValue() (interface{}, bool) {
    ic.mu.Lock()
    defer ic.mu.Unlock()
    if ic.index < len(ic.resumeValues) {
        v := ic.resumeValues[ic.index]
        ic.index++
        return v, true
    }
    return nil, false
}

2. nullResume is never cleared inside Interrupt() — causes infinite duplicate appends

// interrupt.go — Lines ~68-72
v := ic.getNullResume()
if v != nil {
    ic.appendResumeValue(v)  // appends nullResume to resumeValues
    return v, nil            // but never clears ic.nullResume
}

On the next call to Interrupt() with no new resume values, getNullResume() returns the same non-nil value again, appending it a second time, and so on. resumeValues grows unboundedly with the same value, and the index eventually falls back into this synthetic range, returning stale data.

Fix:

v := ic.getNullResume()
if v != nil {
    ic.setNullResume(nil)    // consume it
    ic.appendResumeValue(v)
    return v, nil
}

3. Reset() always resets globalContext — corrupts all concurrent requests

// interrupt.go — Lines ~193-199
func Reset(ctx context.Context) {
    ic := GetInterruptContext(ctx)
    if ic != nil {
        ic.reset()
    }
    globalContext.reset()  // ← ALWAYS resets, even when ctx has its own interruptContext
}

Any per-request context that calls Reset() will also wipe the global context, immediately corrupting every in-flight request that uses the global fallback path. The global reset should only happen when ctx itself has no interruptContext (i.e., callers who originally set up a per-request context should not also be resetting the shared global):

func Reset(ctx context.Context) {
    ic := GetInterruptContext(ctx)
    if ic != nil {
        ic.reset()
        return   // per-request context found; do not touch globalContext
    }
    globalContext.reset()
}

🟠 Medium

4. getResumeValues() exposes the internal slice — unguarded reference after lock release

func (ic *interruptContext) getResumeValues() []interface{} {
    ic.mu.Lock()
    defer ic.mu.Unlock()
    return ic.resumeValues   // ← returns alias to the internal slice
}

After the lock is released, the caller holds a live reference to the backing array. Concurrent appendResumeValue calls may reallocate the slice, creating a data race on the original backing array. Return a copy:

result := make([]interface{}, len(ic.resumeValues))
copy(result, ic.resumeValues)
return result

5. generateInterruptID is not unique — same value → same ID at any call site

func generateInterruptID(value interface{}) string {
    return fmt.Sprintf("%v", value)   // "Please provide input" == "Please provide input" always
}

Two different interrupt points that happen to use the same message string will produce identical IDs. The engine and client cannot distinguish which interrupt fired. The comment acknowledges a proper implementation would hash the namespace; that should be done:

func generateInterruptID(value interface{}) string {
    // TODO: incorporate checkpoint namespace + interrupt index for true uniqueness
    return fmt.Sprintf("%x", sha256Hash(fmt.Sprintf("%v", value)))
}

At minimum, appending an atomic counter makes IDs unique within a process.


6. GetInterruptValue returns *types.Interrupt, not the user's original value

func GetInterruptValue(err error) (interface{}, bool) {
    if gi, ok := err.(*errors.GraphInterrupt); ok && len(gi.Interrupts) > 0 {
        return gi.Interrupts[0], true   // returns *types.Interrupt, not the .Value field
    }
    return nil, false
}

Callers named GetInterruptValue reasonably expect the value passed to Interrupt(ctx, value). Instead they receive the *types.Interrupt envelope. TestInterrupt_Basic only checks val != nil, masking this discrepancy:

// fix:
if gi, ok := err.(*errors.GraphInterrupt); ok && len(gi.Interrupts) > 0 {
    if intr, ok := gi.Interrupts[0].(*types.Interrupt); ok {
        return intr.Value, true
    }
    return gi.Interrupts[0], true
}

🔵 Low / Informational

7. TestGlobalContext leaves global state dirty — potential test cross-contamination

func TestGlobalContext(t *testing.T) {
    Reset(context.Background())            // clear before
    AppendResumeValue(nil, "global_value") // modifies globalContext
    values := GetResumeValues(nil)
    // ... assertions ...
    // no Reset at the end
}

If test execution order changes or tests run in parallel, globalContext.resumeValues will contain "global_value" for subsequent tests. Add defer Reset(context.Background()) at the top.

8. GetNullResume(consume=true) path is untested

The consume bool parameter of GetNullResume (and the underlying setNullResume logic) has no test coverage. Add a test that sets a null resume, retrieves it with consume=true, and verifies a second call returns nil.

9. GetInterruptContext returns a pointer to an unexported type

func GetInterruptContext(ctx context.Context) *interruptContext

Returning a pointer to an unexported type from an exported function is valid Go but unconventional. External packages cannot name the type, making the API confusing. Consider either making interruptContext exported or narrowing this function to bool (which IsInterruptContext already provides) and routing all access through the exported top-level helpers.


Summary Table

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

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

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.go

Length of output: 55674



@yingfeng Here is the detailed review of internal/harness/graph/checkpoint.


Review: internal/harness/graph/checkpoint

🔴 Critical

1. Clone() generates two independent UUIDs — Checkpoint.ID ≠ Metadata.ID (checkpoint.go Lines ~130–175)

clone := &Checkpoint{
    ID: uuid.New().String(),         // ← UUID_A
    ...
    Metadata: CheckpointMetadata{
        ID: uuid.New().String(),     // ← UUID_B  (always ≠ UUID_A)
    },
}

Metadata.ID is intended to be the identity of the checkpoint, but it will never match clone.ID. Any code that looks up a checkpoint by Metadata.ID will fail to find it when querying by clone.ID, and vice versa. The fix is to generate one UUID and reuse it:

newID := uuid.New().String()
clone := &Checkpoint{
    ID: newID,
    ...
    Metadata: CheckpointMetadata{
        ID: newID,  // same ID
        ...
    },
}

2. Clone() shallow-copies PendingWrites.Value (checkpoint.go Line ~195)

copy(clone.PendingWrites, c.PendingWrites)

copy on a []PendingWrite copies the struct fields by value. The Value interface{} field holds a pointer or reference to the underlying data — it is not deep-copied. A mutation to Value in the clone would silently affect the original:

// Fix: deep-copy each write's Value
clone.PendingWrites = make([]PendingWrite, len(c.PendingWrites))
for i, pw := range c.PendingWrites {
    clone.PendingWrites[i] = pw
    clone.PendingWrites[i].Value = deepCopy(pw.Value)
}

3. Save() version conflict check is bypassed whenever ParentID == "" (checkpoint.go Lines ~395–420)

if checkpoint.ParentID != "" {   // ← guard skipped for every NewCheckpoint()
    ...
}

NewCheckpoint() never sets ParentID, so every checkpoint created with it has ParentID = "". An attacker or buggy caller can save a checkpoint at any version without triggering conflict detection simply by omitting ParentID. The guard should be removed or inverted — check for conflicts whenever a checkpoint with a matching thread already exists:

if checkpoints := cm.checkpoints[threadID]; len(checkpoints) > 0 {
    latest := checkpoints[len(checkpoints)-1]
    // Conflict if the caller's declared parent doesn't match actual latest
    if checkpoint.ParentID != "" && latest.ID != checkpoint.ParentID {
        return &VersionConflictError{...}
    }
    if checkpoint.Version != 0 && latest.Version != checkpoint.Version-1 {
        return &VersionConflictError{...}
    }
}

4. NATSSaver.encodeKey is a no-op — keys are not sanitized (nats.go Lines ~136–143)

func encodeKey(threadID string) string {
    return threadID   // ← identity function
}

The comment above it documents {tenant_id}:{thread_id} format, but the implementation just returns threadID unchanged. NATS KV keys must be alphanumeric with dashes, underscores, dots, and colons — no spaces or forward slashes. A threadID such as "my thread/123" or a UUID with incompatible characters produces an invalid key that causes a silent or hard-to-debug NATS error. At minimum the function should sanitize:

func encodeKey(threadID string) string {
    // Replace any character not valid in a NATS KV key
    return strings.NewReplacer(" ", "_", "/", "-").Replace(threadID)
}

🟠 Medium

5. deepCopy silently returns a shallow reference on JSON failure (checkpoint.go Lines ~525–545)

data, err := json.Marshal(v)
if err != nil {
    return v   // ← returns original; caller doesn't know
}
var result interface{}
if err := json.Unmarshal(data, &result); err != nil {
    return v   // ← same issue
}

Non-serializable types (channels, functions, circular references) fall through silently. Downstream code mutating the "copy" will also mutate the original, breaking checkpoint isolation with no indication. Consider returning an error or at least logging:

if err != nil {
    // log.Warn or return an error to the caller
    return v, fmt.Errorf("deepCopy: cannot marshal type %T: %w", v, err)
}

6. PutWrites conflict detection has a TOCTOU race (checkpoint.go Lines ~430–470)

The entire PutWrites body runs under a single mutex, but the conflict detection via activeWrites only detects conflicts within the same invocation lifecycle, not across concurrent invocations that arrive after the first has already cleared activeWrites. The test confirms this:

// From concurrency_test.go:
err = manager.PutWrites(ctx, config, writes2, "task1")
if err != nil {
    t.Logf("Got expected error: %v", err)  // ← logs, does not assert!
}

The t.Logf instead of t.Error acknowledges the conflict may or may not be detected. The activeWrites map is cleared at the end of each successful PutWrites, so by the time the second goroutine acquires the lock, the conflict marker is gone. Consider a generation counter or optimistic locking instead.


7. Two incompatible in-memory checkpoint implementations (checkpoint.go vs memory.go)

CheckpointManager provides a rich API (versioning, lineage, conflict detection) but does not implement BaseCheckpointer. MemorySaver implements BaseCheckpointer but has no versioning or lineage. Users needing an in-memory checkpoint for the Pregel engine must use MemorySaver, losing all the richness of CheckpointManager. Consider having MemorySaver delegate to CheckpointManager internally, or having CheckpointManager implement BaseCheckpointer directly.


8. NATSSaver silently truncates History > 255 (nats.go Line ~127)

History: uint8(cfg.History),   // cfg.History is int; overflow if > 255

A value of 256 becomes 0, effectively disabling history. Add a bounds check:

if cfg.History > 255 {
    return nil, fmt.Errorf("NATS KV History must be ≤ 255, got %d", cfg.History)
}

9. collectGarbage logs to fmt.Printf in production code (nats.go Line ~232)

fmt.Printf("[NATSSaver] GC: purged %d completed graph instances (keys)\n", purged)

This bypasses any structured logging the application may use (Zap, slog, logrus). Replace with an injected logger or the project's standard logging mechanism.


🔵 Low / Informational

10. Tests use raw string "thread_id" instead of constants.ConfigKeyThreadID (checkpoint_test.go)

config := map[string]interface{}{
    "thread_id": threadID,   // ← should be constants.ConfigKeyThreadID
}

If the constant value ever changes, the tests will silently diverge from the implementation. Replace with constants.ConfigKeyThreadID throughout.

11. NATSSaver is missing GetState — API asymmetry with MemorySaver

MemorySaver exposes GetState(ctx, config) (*CheckpointState, error) which returns a checkpoint and its metadata together. NATSSaver has no equivalent. Code written against MemorySaver's extended API cannot be swapped for NATSSaver without changes.

12. TestCheckpointManager_PutWrites_Conflict doesn't assert the conflict (concurrency_test.go Lines ~172–185)

err = manager.PutWrites(ctx, config, writes2, "task1")
if err != nil {
    t.Logf("Got expected error: %v", err)  // ← should be t.Errorf or a separate check
}

The test name says "Conflict" but it logs rather than asserts. The behavior under test is therefore untested.

13. Duplicate package-level doc comments in checkpoint.go and memory.go

Both files begin with:

// Package checkpoint provides ...

Go convention places the canonical package doc comment in exactly one file (typically doc.go). Remove the one in memory.go.


Summary Table

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

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

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.go

Length of output: 30518



@yingfeng Here is the review of internal/harness/graph/managed.


Review: internal/harness/graph/managed

🔴 Critical

1. PatchConfigurable mutates the original base map in-place (managed.go)

When base[ManagedConfigKeyConfigurable] already exists, its value is captured by reference and then mutated directly:

func PatchConfigurable(base map[string]interface{}, updates map[string]interface{}) map[string]interface{} {
    configurable := make(map[string]interface{})
    if cfg, ok := base[ManagedConfigKeyConfigurable]; ok {
        if cfgMap, ok := cfg.(map[string]interface{}); ok {
            configurable = cfgMap   // ← same reference, not a copy
        }
    }
    for k, v := range updates {
        configurable[k] = v         // ← mutates the original map inside base
    }
    ...
}

Any caller expecting PatchConfigurable to be non-destructive will instead silently corrupt its own config. Fix with a copy:

configurable := make(map[string]interface{})
if cfg, ok := base[ManagedConfigKeyConfigurable]; ok {
    if cfgMap, ok := cfg.(map[string]interface{}); ok {
        for k, v := range cfgMap {    // ← copy, not alias
            configurable[k] = v
        }
    }
}

2. ExtractManagedValues / ExtractManagedValueSpecs panic on unexported struct fields (managed.go)

reflect.Value.Interface() panics when called on an unexported field. Neither function guards against this:

for i := 0; i < v.NumField(); i++ {
    field := v.Field(i)
    if IsManagedValue(field.Interface()) {  // ← panics if field is unexported

Fix by checking IsExported() first:

for i := 0; i < v.NumField(); i++ {
    if !v.Type().Field(i).IsExported() {
        continue
    }
    field := v.Field(i)
    ...
}

🟠 Medium

3. splitCheckpointNS is a non-functional stub — ParseCheckpointNS and RecastCheckpointNS never work (managed.go)

splitCheckpointNS always returns []string{ns} regardless of separator characters:

func splitCheckpointNS(ns string) []string {
    // Simple implementation - split by separator
    return []string{ns}   // ← always a 1-element slice
}

Consequently ParseCheckpointNS("a|b|c") returns ["a|b|c"] instead of ["a","b","c"], and RecastCheckpointNS can never strip a task ID because len(parts) == 1 always. The separator is already hardcoded as "|" in joinCheckpointNS. A minimal fix:

import "strings"

func splitCheckpointNS(ns string) []string {
    return strings.Split(ns, "|")
}

4. isTaskID heuristic is overly broad — valid node names are misclassified (managed.go)

func isTaskID(s string) bool {
    return len(s) > 20 && (containsDash(s) || containsUnderscore(s))
}

Any node name longer than 20 characters that contains a dash or underscore (e.g., "my-preprocessing-step") is silently treated as a task ID, causing RecastCheckpointNS to incorrectly truncate namespace paths. Either use a stricter UUID-format check or key the detection on an explicit delimiter:

import "regexp"
var uuidRE = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
func isTaskID(s string) bool { return uuidRE.MatchString(s) }

5. DEFAULT_RUNTIME is a shared mutable global — data race on Configurable (managed.go)

var DEFAULT_RUNTIME = &Runtime{
    Configurable: make(map[string]interface{}),  // ← shared across all goroutines
    ...
}

get_runtime calls DEFAULT_RUNTIME.Clone() which shallow-copies Configurable via cloneMap, so users of get_runtime are safe. However, any caller that does DEFAULT_RUNTIME.Set(ctx, k, v) or DEFAULT_RUNTIME.Configurable[k] = v directly creates a data race. Consider making Configurable nil in the global (or marking it as truly immutable in documentation):

var DEFAULT_RUNTIME = &Runtime{}   // Configurable nil; callers must use Clone()

6. ManagedValueMapping is not concurrency-safe (managed.go)

ManagedValueMapping is a plain map[string]ManagedValue. Concurrent Register and Get calls from multiple goroutines (e.g., different nodes reading from a shared mapping) are an unprotected data race. Wrap in a struct with a sync.RWMutex or document that the mapping must only be written once at init time before being shared.


7. Runtime.Merge treats Step == 0 as "not provided" — silently ignores a valid initial step (managed.go)

if other.Step != 0 {
    merged.Step = other.Step
}

Step 0 is a valid step number (the first superstep). A merge where other.Step == 0 intentionally resets the step counter will silently be ignored. Use an explicit "presence" marker (e.g., a *int pointer or a separate boolean field) to distinguish "not set" from "zero".


8. get_runtime is unexported dead code that duplicates GetRuntime (managed.go)

The unexported get_runtime (snake_case) has identical logic to the exported GetRuntime but is never called within the package. Remove it or replace calls with GetRuntime.


🟡 Low

9. Runtime.Set / Runtime.Get accept a context.Context they never use (managed.go)

func (r *Runtime) Set(ctx context.Context, key string, value interface{}) {
    // ctx is never read
    r.Configurable[key] = value
}

The unused ctx misleads callers into thinking the context is observed (e.g., for cancellation or deadline propagation). Drop it or explain in a doc comment why it is reserved for future use.


10. FormatDuration input unit undocumented — conflicts with time.Duration (managed.go)

The function signature is FormatDuration(d int64) and assumes the input is in milliseconds, but Go's time.Duration is in nanoseconds. A caller passing time.Since(start) (a time.Duration) will see nonsensical output (microseconds displayed as hours). Add a doc comment and consider accepting time.Duration directly:

// FormatDuration formats a duration (in milliseconds) for debug output.
func FormatDuration(d int64) string { ... }

11. containsDash / containsUnderscore reinvent strings.ContainsRune (managed.go)

These two unexported helpers duplicate standard library behavior:

// replace:
func containsDash(s string) bool      { ... }
func containsUnderscore(s string) bool { ... }

// with:
import "strings"
strings.ContainsRune(s, '-')
strings.ContainsRune(s, '_')

🔵 Test Coverage Gaps (managed_test.go)

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

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

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 | sort

Length 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.go

Length of output: 23183



@yingfeng Here is the review of internal/harness/graph/task.


Review: internal/harness/graph/task

🔴 Critical

1. Cached() is silently broken — cachePolicy is never applied (decorator.go)

TaskDecorator.Wrap only branches on d.retryPolicy != nil; the cachePolicy field is stored but never consulted during execution. Any call to Cached(fn, ttl) silently falls through with no caching:

// Wrap (decorator.go) — cachePolicy is completely ignored
func (d *TaskDecorator) Wrap(fn types.NodeFunc) types.NodeFunc {
    return func(ctx context.Context, input interface{}) (interface{}, error) {
        if d.retryPolicy != nil {
            return d.executeWithRetry(ctx, taskCtx, fn)
        }
        // d.cachePolicy is never checked here
        output, err := fn(ctx, input)
        ...
    }
}

The fix is to wire CachedExecutor from pregel/cache.go inside Wrap:

if d.cachePolicy != nil {
    executor := pregel.NewCachedExecutor(cache, d.cachePolicy)
    return executor.Execute(ctx, d.name, input, func(ctx context.Context, in interface{}) (interface{}, error) {
        return fn(ctx, in)
    })
}

There is also no test covering Cached, so this bug is entirely invisible in the test suite.


2. Entrypoint.Invoke and Stream bypass the associated graph entirely (decorator.go)

Both methods detect that e.graph != nil and then… call e.Execute(ctx, input) anyway, completely ignoring the graph:

// Invoke — graph is never used
if e.graph == nil {
    return e.Execute(ctx, input)
}
// Note: In a full implementation, this would use the graph's Invoke method
return e.Execute(ctx, input)  // ← same path

Any code using NewEntrypointWithOptions(..., WithEntrypointGraph(g)) will silently get raw function execution, bypassing all graph routing, channel updates, checkpointing, and interrupts.


3. AInvoke and ABatch silently swallow errors and return no result (decorator.go)

func (e *Entrypoint) AInvoke(ctx context.Context, ...) <-chan struct{} {
    result := make(chan struct{}, 1)
    go func() {
        defer close(result)
        _, err := e.Invoke(ctx, input, config)
        _ = err  // ← error is discarded
    }()
    return result
}

Callers receive only a <-chan struct{} signal (done/not done), with no way to obtain the output or observe errors. These should return a result-carrying channel:

type InvokeResult struct {
    Output interface{}
    Err    error
}
func (e *Entrypoint) AInvoke(ctx context.Context, ...) <-chan InvokeResult

4. Entrypoint.compiled is not protected — data race under concurrent Invoke calls (decorator.go)

Multiple goroutines calling Invoke concurrently will all read !e.compiled and call Compile simultaneously with no synchronization. Replace the boolean with sync.Once:

type Entrypoint struct {
    compileOnce sync.Once
    // ...
}

func (e *Entrypoint) Invoke(ctx context.Context, ...) (interface{}, error) {
    var compileErr error
    e.compileOnce.Do(func() { compileErr = e.Compile(ctx) })
    if compileErr != nil {
        return nil, compileErr
    }
    // ...
}

🟠 Medium

5. addJitter is deterministic, not random, and always subtracts (decorator.go)

func addJitter(d time.Duration) time.Duration {
    jitter := float64(d) * 0.5 * float64(time.Now().UnixNano()%100)/100.0
    return d - time.Duration(jitter)  // always subtracts — range is [0.5d, d]
}

Two issues:

  • time.Now().UnixNano()%100 is deterministic within a tight loop — consecutive retries at nanosecond granularity produce nearly identical values.
  • The function only subtracts jitter, so the result is always in [0.5d, d] instead of the expected [0.75d, 1.25d]-style band.
import "math/rand"

func addJitter(d time.Duration) time.Duration {
    // ±25% jitter
    delta := float64(d) * 0.25
    jitter := (rand.Float64()*2 - 1) * delta
    return d + time.Duration(jitter)
}

6. Entrypoint.Compile is an empty stub with no actual behaviour (decorator.go)

The method does nothing except set e.compiled = true. Both the checkpointer and store setup blocks are comment-only placeholders. At minimum this should return an error if a graph is present but cannot be compiled, or be removed until implemented.


7. Batch processes inputs sequentially despite the "batch" naming convention (decorator.go)

Batch iterates over inputs with a plain for loop. Users expecting concurrent fan-out (the natural expectation from a "batch" API in a concurrent graph framework) will be surprised:

for i, input := range inputs {
    output, err := e.Invoke(ctx, input, config)  // serial

Either add a concurrent bool option, or document the sequential behaviour prominently.


8. pow reimplements math.Pow (decorator.go)

// current
func pow(base float64, exp int) float64 {
    result := 1.0
    for i := 0; i < exp; i++ { result *= base }
    return result
}

Replace with math.Pow(base, float64(attempt-1)) directly at the call site and remove the helper.


🔵 Low / Informational

9. Entrypoint.InvokeWithDependencies also bypasses the graph (decorator.go)

Same issue as point 2: it calls injectedFn(ctx, input) where injectedFn wraps e.fn, never the graph.

10. TestCompose has a misleading comment (decorator_test.go)

The comment says "first addTen, then double" but Compose applies decorators from last to first:

for i := len(decorators) - 1; i >= 0; i-- {  // double is applied first

So execution order is actually: base fn (0+1=1) → double (×2=2) → addTen (+10=12). The comment is inverted.

11. No tests for several exported APIs (decorator_test.go)

The following exported symbols have zero test coverage:

  • Cached / CachePolicy wiring
  • InjectDependencies, GetExecutionContext, GetConfig, GetPrevious, GetStore, GetWriter
  • Final, IsFinal, GetFinalValue
  • EntrypointDecorator
  • AInvoke, ABatch
  • WithEntrypointCheckpointer, WithEntrypointStore, WithEntrypointGraph

Summary Table

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

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

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 ""
done

Length of output: 32610



@yingfeng Here is the review of internal/harness/graph/runnable.


Review: internal/harness/graph/runnable

🔴 Critical

1. Tracer.TraceCallback() — data race on currentInput and spans (inject.go)

currentInput is a closure variable shared between two goroutines that may call OnStartFunc and OnEndFunc concurrently (e.g., from different pipeline stages). t.spans is also appended without a lock.

// CURRENT — racy:
func (t *Tracer) TraceCallback() Callback {
    var currentInput interface{}   // ← shared between two closures, no mutex
    return &CallbackFunc{
        OnStartFunc: func(...) { currentInput = input },
        OnEndFunc:   func(...) { t.spans = append(t.spans, ...) }, // ← t.spans unguarded
    }
}

// FIX:
func (t *Tracer) TraceCallback() Callback {
    var mu sync.Mutex
    var currentInput interface{}
    return &CallbackFunc{
        OnStartFunc: func(_ context.Context, _ string, input interface{}) {
            mu.Lock(); currentInput = input; mu.Unlock()
        },
        OnEndFunc: func(_ context.Context, name string, output interface{}, err error) {
            mu.Lock()
            inp := currentInput
            mu.Unlock()
            t.mu.Lock()   // add sync.Mutex to Tracer
            t.spans = append(t.spans, Span{Name: name, Input: inp, Output: output, Error: err})
            t.mu.Unlock()
        },
    }
}

2. Stream silently drops errors — consumers cannot detect failures (runnable.go)

RunnableFunc.Stream, RunnableSeq.Stream, RunnableParallel.Stream, and RunnableMap.Stream all share the same pattern:

output, err := r.Invoke(ctx, input)
if err == nil {
    ch <- output
}
// err is silently discarded — channel closes with no value, looks like empty success

A caller receiving a closed empty channel cannot distinguish a successful empty result from a failed execution. Either use a separate error channel, or wrap output+error in a struct:

type StreamResult struct {
    Value interface{}
    Err   error
}
// Stream(ctx, input) <-chan StreamResult

Or at minimum document that callers must use Invoke/Batch for error handling.


3. RunnableParallel.Invoke passes nil to every sub-runnable (runnable.go)

go func(n string, rn Runnable[any, any]) {
    value, err := rn.Invoke(ctx, nil)  // ← input is always nil
    ...
}(name, r)

The comment acknowledges this but the consequence is that RunnableParallel is fundamentally broken for any fan-out use case — it cannot distribute input to child runnables. At minimum, pass the actual input:

value, err := rn.Invoke(ctx, input)

4. buildArguments — runtime injection block has misleading indentation, creating a latent nil-dereference risk (inject.go)

The runtime injection block is physically indented as if it is outside the if r.injectionCtx != nil guard but it is inside it:

if r.injectionCtx != nil {
    if paramType == reflect.TypeOf(&types.RunnableConfig{}) { ... }

// Check runtime values        ← looks like it is at top level
if !injected && r.injectionCtx.Runtime != nil {   // ← would panic if injectionCtx nil
    ...
}
}

Re-indent the inner block so its scope is unambiguous. A future refactor separating it could produce a nil-pointer dereference on r.injectionCtx.Runtime.


🟡 Medium

5. NewRunnableSeq type-compatibility check is a no-op (runnable.go)

The check compares OutputType and InputType strings from the schema, but for any Runnable[any, any] those are always "interface {}":

fmt.Sprintf("%T", *new(any))  // → "interface {}"

So prevSchema.OutputType != currSchema.InputType is always false and NewRunnableSeq never returns a type-mismatch error. The check provides false confidence; it should either be removed or use actual reflection types.


6. buildArguments — non-deterministic runtime value injection (inject.go)

Runtime injection iterates r.injectionCtx.Runtime (a map[string]interface{}) and picks the first value whose type matches the parameter. Map iteration order in Go is random, so when two runtime values satisfy the same parameter type, which one gets injected is non-deterministic across runs.


7. CoerceToInjectableRunnable — type switch only matches Runnable[any, any] (inject.go)

case Runnable[any, any]:
    // Wrap existing runnable

In Go, a generic interface type assertion matches only the exact instantiation. A Runnable[string, string] will fall through to the default branch and be handled as a raw function (which will fail unless it happens to be a reflect.Func). Consider accepting interface{ Invoke(context.Context, interface{}) (interface{}, error) } instead.


8. executeWithArgs — results[1].IsNil() panics on non-nillable types (inject.go)

if !results[1].IsNil() {

reflect.Value.IsNil() panics when called on a value whose kind is not a pointer, channel, function, interface, map, or slice. If a function erroneously returns a non-pointer second value (e.g. (string, int)), this panics instead of returning a clean error.

// FIX:
errResult := results[1]
if errResult.Kind() == reflect.Interface || errResult.Kind() == reflect.Ptr {
    if !errResult.IsNil() {
        // ... handle error
    }
}

🔵 Low / Informational

9. RunnableError lacks errors.Is/errors.As / Unwrap() support (runnable.go)

RunnableError cannot be introspected with errors.Is or matched with errors.As. Adding an Unwrap() method or an Is(target error) bool method would align it with Go error-handling conventions.

10. No test coverage for inject.go (runnable_test.go)

runnable_test.go covers RunnableFunc, RunnableSeq, RunnableParallel, RunnableMap, and RunnableBuilder, but InjectableRunnable, Tracer, CoerceToInjectableRunnable, WithTracing, InjectDependencies, and ParamInjector have zero test coverage.


Summary Table

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

@yingfeng yingfeng changed the title Feat: add harness-go framework -- graph engine Feat: add harness-go framework - graph engine Jun 15, 2026
@yingfeng yingfeng changed the title Feat: add harness-go framework - graph engine Feat: add harness-go framework —— graph engine Jun 15, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

LastValueAfterFinish restore loses finished state.

Checkpoint() persists only value, while Get()/IsAvailable() require finished == true. After restore, availability semantics change because finished resets 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 win

Checkpoint leaks mutable internal state (seen) instead of snapshotting it.

At Line 309, Checkpoint() stores c.seen by 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

List returns oldest-first but comment says "most recent first".

The comment on line 624 says "Return most recent checkpoints first" but the loop iterates from start to len(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 win

Shallow copy of PendingWrites may leak mutable references.

copy(clone.PendingWrites, c.PendingWrites) performs a shallow copy. If any PendingWrite.Value contains 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

ToMap drops Timestamp and TaskID from pending writes.

Serialization omits Timestamp and TaskID fields from PendingWrite, causing data loss during round-trip serialization via ToMap/FromMap. If these fields are populated (via NewPendingWrite), 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

deepCopy silently 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

AddPendingWrite omits Timestamp and TaskID that NewPendingWrite sets.

NewPendingWrite (line 72-81) populates Timestamp and TaskID, but AddPendingWrite creates a PendingWrite without these fields. This inconsistency means writes added via AddPendingWrite will 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

📥 Commits

Reviewing files that changed from the base of the PR and between aa0beba and 1aa8837.

📒 Files selected for processing (18)
  • internal/harness/graph/channels/barrier.go
  • internal/harness/graph/channels/base.go
  • internal/harness/graph/channels/binop.go
  • internal/harness/graph/channels/topic.go
  • internal/harness/graph/channels/untracked.go
  • internal/harness/graph/checkpoint/checkpoint.go
  • internal/harness/graph/checkpoint/memory.go
  • internal/harness/graph/graph/compiled.go
  • internal/harness/graph/graph/graph.go
  • internal/harness/graph/graph/graph_integration_test.go
  • internal/harness/graph/graph/graph_test.go
  • internal/harness/graph/graph/message.go
  • internal/harness/graph/interrupt/interrupt.go
  • internal/harness/graph/managed/managed.go
  • internal/harness/graph/runnable/inject.go
  • internal/harness/graph/runnable/runnable.go
  • internal/harness/graph/task/decorator.go
  • internal/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

@yingfeng

Copy link
Copy Markdown
Member Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Critical: Checkpoint restoration is unreachable.

applyInput (line 241) calls toMap(input) which returns an error when input == nil (line 1236-1238). This means when input == 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 nil input 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 win

Error silently ignored in buildOutput.

When registry.GetValues() returns an error, it's silently swallowed and lastState is 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 win

Panic: Unchecked type assertion when path is empty.

When path == "", line 1405 performs val.(map[string]interface{}) without a type check. If val is 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 win

Critical: nil context passed to condition and branch functions.

Lines 1071 and 1103 pass nil as the context to user-provided condition functions:

conditionResult, err := condEdge.Condition(nil, state)  // line 1071
branchResult, err := branch.Condition(nil, state)        // line 1103

If any condition function calls ctx.Done(), ctx.Err(), or ctx.Value(), the nil dereference will panic. This also prevents condition functions from respecting cancellation.

🐛 Proposed fix: Pass actual context

Add a ctx parameter to getNextNodes and 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.Condition

Update 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 win

Bug: Incorrect "seen" tracking uses channel names as node identifiers.

The variable resultName actually contains channel names (from writesByChannel which is keyed by channel at line 694), not result/node names. The logic then:

  1. Checks if a channel name exists in triggerToNodes (which contains trigger strings)
  2. Calls markSeen(resultName, channelName) where first param should be a node name

This 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 lift

Data 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. Concurrent Run() 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 fields
 	go func() {
 		defer close(errCh)
+		e.mu.Lock()
+		defer e.mu.Unlock()
 
 		// Create stream manager for event streaming

Or 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 win

Use 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 value

Unused state parameter in createTask and createTaskInfo.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1aa8837 and 9bbeb28.

📒 Files selected for processing (6)
  • internal/harness/graph/checkpoint/checkpoint.go
  • internal/harness/graph/checkpoint/concurrency_test.go
  • internal/harness/graph/checkpoint/nats.go
  • internal/harness/graph/managed/managed.go
  • internal/harness/graph/pregel/engine.go
  • internal/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

Comment on lines +198 to +205
// 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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

@yingfeng
yingfeng merged commit e7c0687 into infiniflow:main Jun 15, 2026
1 check passed
yingfeng added a commit that referenced this pull request Jun 16, 2026
### 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)
Harry-Hz-Zhang pushed a commit to Harry-Hz-Zhang/ragflow that referenced this pull request Jun 17, 2026
### 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant