Skip to content

Log improvements - #1198

Merged
snakajima merged 1 commit into
receptron:mainfrom
isamu:LogImprovements
Aug 14, 2025
Merged

snakajima merged 1 commit into
receptron:mainfrom
isamu:LogImprovements

Conversation

@isamu

@isamu isamu commented Aug 14, 2025 •

Copy link
Copy Markdown
Member
  • Add a namedInputs
  • Set agentId to be executed

Summary by CodeRabbit

  • New Features
    • Execution logs now capture named input mappings and an optional agent identifier for clearer run tracing.
  • Bug Fixes
    • Improved result aggregation to prevent potential edge-case issues when building input results.
  • Refactor
    • Internal execution flow updated to pass named inputs to preparation and logging steps; no impact on public APIs.
  • Chores
    • Strengthened typing for result utilities to ensure consistent, explicit return shapes.

- Add a namedInputs
- Set agentId to be executed
@isamu
isamu requested a review from snakajima August 14, 2025 10:21
@coderabbitai

coderabbitai Bot commented Aug 14, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce support for named input mappings in the GraphAI library, modifying how inputs are processed and logged during node execution. This involves updates to node preparation, transaction logging, and result utility functions.

Changes

Cohort / File(s) Change Summary
Node Execution
packages/graphai/src/node.ts
Updated ComputedNode execution to pass named input maps and optional agentId instead of input arrays
Transaction Logging
packages/graphai/src/transaction_log.ts
Added support for namedInputs in TransactionLog, modified beforeExecute method to handle named inputs and optional agentId
Result Utilities
packages/graphai/src/utils/result.ts
Refined resultsOf function signature, added explicit return typing and improved result accumulation

Estimated Code Review Effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

A rabbit's tale of code so bright,
Named inputs dance with pure delight,
GraphAI leaps through logic's gate,
With named maps that collaborate,
A symphony of data's might! 🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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

🔭 Outside diff range comments (3)
packages/graphai/src/utils/result.ts (1)

17-29: Bug: Placeholder replacement indexes can mismatch when ":" placeholders are not at the same positions as all placeholders

When a ":" placeholder isn’t aligned positionally with the filtered subset, (godResults as any)[key] can read the wrong value (e.g., templateMatch like ["@now", ":foo"] will try to read godResults[1], which is undefined). Build a map keyed by the placeholder text instead of relying on indices.

Apply this diff to make the replacement robust and avoid index mismatches:

-  const godResults = resultsOfInner(
-    templateMatch.filter((text) => text.startsWith(":")),
-    nodes,
-    propFunctions,
-    isSelfNode,
-  );
+  const colonMatches = templateMatch.filter((text) => text.startsWith(":"));
+  const godResults = resultsOfInner(colonMatches, nodes, propFunctions, isSelfNode) as any[];
+  const godResultMap: Record<string, any> = Object.fromEntries(colonMatches.map((ph, i) => [ph, godResults[i]]));

   // utilsFunctions ${@now}
   const utilsFuncResult = templateMatch
     .filter((text) => text.startsWith("@"))
     .reduce((tmp: Record<string, string | number>, key: string) => {
       tmp[key] = utilsFunctions(key, nodes);
       return tmp;
     }, {});
   return Array.from(templateMatch.keys()).reduce((tmp, key) => {
     if (templateMatch[key].startsWith(":")) {
-      return tmp.replaceAll("${" + templateMatch[key] + "}", (godResults as any)[key]);
+      return tmp.replaceAll("${" + templateMatch[key] + "}", String(godResultMap[templateMatch[key]] ?? ""));
     }
-    return tmp.replaceAll("${" + templateMatch[key] + "}", (utilsFuncResult as any)[templateMatch[key]]);
+    return tmp.replaceAll("${" + templateMatch[key] + "}", String((utilsFuncResult as any)[templateMatch[key]] ?? ""));
   }, input);
packages/graphai/src/node.ts (2)

322-343: Fix agentId resolution when agent is provided via data source and can be a function

If the resolved agent is a function, it’s assigned to this.agentFunction but still used as a truthy agentId in subsequent calls (getAgentFunctionInfo, getConfig, logging). This can cause runtime errors and incorrect config/logging. Split resolution into (agent function | string id) and pass only the string id where needed.

Apply this diff to safely handle both cases and pass only string agentId to downstream consumers:

-    const previousResults = this.graph.resultsOf(this.inputs, this.anyInput);
-    const agentId = this.agentId ? (this.graph.resultOf(parseNodeName(this.agentId)) as string) : this.agentId;
-    if (typeof agentId === "function") {
-      this.agentFunction = agentId;
-    }
-    const hasNestedGraph = Boolean(this.nestedGraph) || Boolean(agentId && this.graph.getAgentFunctionInfo(agentId).hasGraphData);
-    const config: ConfigData | undefined = this.getConfig(hasNestedGraph, agentId);
+    const previousResults = this.graph.resultsOf(this.inputs, this.anyInput);
+    const resolvedAgent = this.agentId ? this.graph.resultOf(parseNodeName(this.agentId)) : undefined;
+    let agentIdStr: string | undefined = this.agentId;
+    if (typeof resolvedAgent === "function") {
+      this.agentFunction = resolvedAgent;
+      agentIdStr = undefined;
+    } else if (typeof resolvedAgent === "string") {
+      agentIdStr = resolvedAgent;
+    }
+    const hasNestedGraph =
+      Boolean(this.nestedGraph) || Boolean(agentIdStr && this.graph.getAgentFunctionInfo(agentIdStr).hasGraphData);
+    const config: ConfigData | undefined = this.getConfig(hasNestedGraph, agentIdStr);
@@
-    this.prepareExecute(transactionId, previousResults, agentId);
+    this.prepareExecute(transactionId, previousResults, agentIdStr);
@@
-      const agentFunction = this.agentFunction ?? this.graph.getAgentFunctionInfo(agentId).agent;
+      const agentFunction = this.agentFunction ?? this.graph.getAgentFunctionInfo(agentIdStr).agent;
@@
-      const context = this.getContext(previousResults, localLog, agentId, config);
+      const context = this.getContext(previousResults, localLog, agentIdStr, config);
@@
-      const result = await this.agentFilterHandler(context as AgentFunctionContext, agentFunction, agentId);
+      const result = await this.agentFilterHandler(context as AgentFunctionContext, agentFunction, agentIdStr);

Also applies to: 331-333, 340-343, 367-369


428-435: Action: Narrow DefaultInputData or adjust error logging — current type is too permissive

I inspected the types per your script. Relevant findings:

  • packages/graphai/src/type.ts:
    • export type DefaultResultData = Record<string, any> | string | number | boolean | Array;
    • export type DefaultInputData = Record<string, any>;
    • export type ResultData<...> = ResultType | undefined;
    • export type ResultDataDictionary<...> = Record<string, ResultData>;
  • packages/graphai/src/node.ts (lines ~428-435) logs namedInputs typed as DefaultInputData:
    private errorProcess(error: unknown, transactionId: number, namedInputs: DefaultInputData) {
      ...
      GraphAILogger.error({ namedInputs });
      ...
    }
    

Conclusion and recommended fixes:

  • Problem: DefaultInputData = Record<string, any> is not strictly the same as Record<string, ResultData | undefined> (it’s too permissive), so logging/consuming namedInputs as if they were ResultData can hide mismatches.
  • Fix options (pick one):
    • Narrow the type: change DefaultInputData to the intended shape, e.g.
      • export type DefaultInputData = ResultDataDictionary;
        or
      • export type DefaultInputData = Record<string, ResultData>;
    • Or keep DefaultInputData broad but change errorProcess to accept the correct/result-specific type (ResultDataDictionary) and only log that, or add runtime filtering/serialization before logging.
    • If broadness is intentional, add a comment and runtime validation where namedInputs are consumed to avoid silent type mismatches.

Files to update:

  • packages/graphai/src/type.ts (update DefaultInputData)
  • packages/graphai/src/node.ts (adjust errorProcess signature or logging if you choose not to change the shared type)
🧹 Nitpick comments (2)
packages/graphai/src/node.ts (1)

494-501: Consider redacting sensitive values in console output

JSON stringifying namedInputs directly can leak secrets (tokens, credentials) via logs. Consider redacting known sensitive keys (e.g., apiKey, auth, token, password) or allowing a per-node redact list in console config.

Example masking approach:

-      GraphAILogger.log(JSON.stringify(context.namedInputs, null, 2));
+      const redactKeys = new Set(["apiKey", "auth", "token", "password", "secret"]);
+      const redacted = JSON.parse(
+        JSON.stringify(context.namedInputs, (k, v) => (redactKeys.has(k) ? "[REDACTED]" : v))
+      );
+      GraphAILogger.log(JSON.stringify(redacted, null, 2));
packages/graphai/src/transaction_log.ts (1)

71-74: Optional: inputsData could omit undefined entries to reduce noise

If most named inputs are undefined, logging them as inputsData adds noise without value. Consider filtering undefined.

Possible tweak:

-    const inputs = Object.values(namedInputs);
-    this.inputsData = inputs.length > 0 ? inputs : undefined;
+    const inputs = Object.values(namedInputs).filter((v) => v !== undefined);
+    this.inputsData = inputs.length > 0 ? inputs : undefined;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d520c4d and a2a127f.

📒 Files selected for processing (3)
  • packages/graphai/src/node.ts (2 hunks)
  • packages/graphai/src/transaction_log.ts (2 hunks)
  • packages/graphai/src/utils/result.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/graphai/src/utils/result.ts (2)
packages/graphai/src/node.ts (1)
  • GraphNodes (536-536)
packages/graphai/src/type.ts (2)
  • PropFunction (193-193)
  • ResultData (21-21)
packages/graphai/src/transaction_log.ts (4)
packages/graphai/src/type.ts (1)
  • ResultData (21-21)
packages/graphai/src/node.ts (1)
  • ComputedNode (79-503)
packages/graphai/src/graphai.ts (1)
  • GraphAI (32-447)
packages/graphai/src/utils/nodeUtils.ts (1)
  • dataSourceNodeIds (25-30)
packages/graphai/src/node.ts (4)
agent_filters/http_client_agent_filter/lib/http_client.js (1)
  • agentId (68-68)
packages/graphai/lib/type.d.ts (1)
  • ResultData (19-19)
packages/graphai/src/type.ts (1)
  • ResultData (21-21)
packages/graphai/src/index.ts (2)
  • ResultData (12-12)
  • NodeState (30-30)
🔇 Additional comments (3)
packages/graphai/src/utils/result.ts (1)

49-54: resultsOf typing and accumulator usage: LGTM

Explicit return type and accumulator initialization make the behavior clear and type-safe. Returning the accumulator in the reducer is correct.

packages/graphai/src/node.ts (1)

417-423: prepareExecute refactor: passing namedInputs and agentId into the log is appropriate

Shifting from positional inputs to namedInputs improves observability and aligns with the new logging schema. The call site wiring is correct given the updated TransactionLog API.

packages/graphai/src/transaction_log.ts (1)

17-17: Adding namedInputs to the log model: LGTM

Capturing the full namedInputs map materially improves traceability/debuggability.

Comment on lines +65 to 76
public beforeExecute(node: ComputedNode, graph: GraphAI, transactionId: number, namedInputs: Record<string, ResultData>, agentId?: string) {
this.agentId = agentId;
this.state = node.state;
this.retryCount = node.retryCount > 0 ? node.retryCount : undefined;
this.startTime = transactionId;
this.inputs = dataSourceNodeIds(node.dataSources);
const inputs = Object.values(namedInputs);
this.inputsData = inputs.length > 0 ? inputs : undefined;
this.namedInputs = namedInputs;
graph.setLoopLog(this);
graph.appendLog(this);
}

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

Don’t overwrite agentId with undefined during beforeExecute

initForComputedNode already sets a display-friendly agentId. Overwriting it with undefined loses that context when the runtime agent is a function. Only update when a non-undefined agentId is provided.

Apply this diff:

-    this.agentId = agentId;
+    if (agentId !== undefined) {
+      this.agentId = agentId;
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public beforeExecute(node: ComputedNode, graph: GraphAI, transactionId: number, namedInputs: Record<string, ResultData>, agentId?: string) {
this.agentId = agentId;
this.state = node.state;
this.retryCount = node.retryCount > 0 ? node.retryCount : undefined;
this.startTime = transactionId;
this.inputs = dataSourceNodeIds(node.dataSources);
const inputs = Object.values(namedInputs);
this.inputsData = inputs.length > 0 ? inputs : undefined;
this.namedInputs = namedInputs;
graph.setLoopLog(this);
graph.appendLog(this);
}
public beforeExecute(node: ComputedNode, graph: GraphAI, transactionId: number, namedInputs: Record<string, ResultData>, agentId?: string) {
if (agentId !== undefined) {
this.agentId = agentId;
}
this.state = node.state;
this.retryCount = node.retryCount > 0 ? node.retryCount : undefined;
this.startTime = transactionId;
this.inputs = dataSourceNodeIds(node.dataSources);
const inputs = Object.values(namedInputs);
this.inputsData = inputs.length > 0 ? inputs : undefined;
this.namedInputs = namedInputs;
graph.setLoopLog(this);
graph.appendLog(this);
}
🤖 Prompt for AI Agents
In packages/graphai/src/transaction_log.ts around lines 65 to 76, the
beforeExecute method overwrites an existing display-friendly agentId with
undefined when the runtime agentId argument is not provided; change the
assignment so this.agentId is only updated when the incoming agentId is not
undefined (i.e., check if agentId !== undefined before assigning), leaving
existing agentId untouched otherwise; keep the rest of the method intact (state,
retryCount, startTime, inputs, inputsData, namedInputs, graph.setLoopLog and
graph.appendLog).

@snakajima
snakajima merged commit 64d1141 into receptron:main Aug 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants