Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@aguspdana
Copy link
Collaborator

@aguspdana aguspdana commented Dec 30, 2025

Important

Introduces a new SurrealDB query pipeline with logical planner, optimizer, and batched SurQL execution, along with a benchmark suite and Docker scripts for performance testing.

  • New Features
    • Introduces surql2 pipeline with logical builder, optimizer, SurQL generator, result processor, and batched transactions.
    • Adds draft schema enrichment for SurrealDB with index support.
    • Implements benchmark suite with data generator, insert/query scripts, custom runner, and Docker setup for SurrealDB v2/v3.
    • Adds npm script bench:surrealdb.
    • Moves deepRemoveMetaData to src/helpers and updates mutation parser.
    • Adds zod v4 for request parsing.
  • Migration
    • Supports targetRole for link fields targeting a role.
    • Adds optional indexes array on entities and relations.
    • Updates imports to use deepRemoveMetaData from src/helpers.

This description was created by Ellipsis for 978e4da. You can customize this summary. It will automatically update as commits are pushed.



Summary by cubic

Introduces a new SurrealDB query pipeline with a logical planner, optimizer, and batched SurQL execution to reduce query cost and improve performance. Adds a benchmark suite and Docker scripts to measure v2 vs v3 behavior.

  • New Features

    • New surql2 pipeline: logical builder, optimizer, SurQL generator, result processor, and batched transactions.
    • Draft schema enrichment for SurrealDB with index support.
    • Bench suite: data generator, insert/query scripts, custom runner, and Docker setup for SurrealDB v2/v3; added npm script bench:surrealdb.
    • deepRemoveMetaData moved to src/helpers; mutation parser updated.
    • New BQL request parser with zod v4; array filters are treated as OR.
  • Migration

    • For link fields targeting a role, set targetRole (e.g., user-space, user-session).
    • Optional indexes array now supported on entities and relations.
    • Update imports to use deepRemoveMetaData from src/helpers.

Written for commit 978e4da. Summary will update on new commits.

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed everything up to cc54408 in 2 minutes and 30 seconds. Click for details.
  • Reviewed 4456 lines of code in 33 files
  • Skipped 0 files when reviewing.
  • Skipped posting 9 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. tests/unit/queries/query.ts:2036
  • Draft comment:
    When testing for errors from asynchronous calls, avoid awaiting the result and then calling toThrow. Instead, use 'await expect(ctx.query(...)).rejects.toThrow(TypeError)'. This ensures the promise rejection is captured correctly.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
2. tests/unit/queries/query.ts:2198
  • Draft comment:
    Several tests are marked as TODO{TS} (e.g. batched queries with $as, deep nested queries with repeated paths, computed fields with missing dependencies). Consider using test.skip or grouping these tests so that unfinished scenarios do not cause false negatives.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
3. tests/unit/bench/bench.ts:12
  • Draft comment:
    The benchmarks repeatedly use deepSort and deepRemoveMetaData to normalize results. Consider extracting common result assertions into helper functions (or custom matchers) to reduce repetition and improve readability.
  • Reason this comment was not posted:
    Comment was on unchanged code.
4. benches/v2.bench.ts:80
  • Draft comment:
    Typographical note: The comment says 'Pick in the middle of the b array + 2', but the code still uses '+ 1' (as seen in the previous bench). Please check if the comment should be updated to match the code or if the index calculation is incorrect.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% This is a new file (benchmark file), so all code is new. The comment is pointing out an inconsistency between a code comment and the actual implementation. Line 72 says "+ 1" and uses + 1. Line 80 says "+ 2" but uses + 1. This could be either: (1) the comment is wrong and should say "+ 1", or (2) the code is wrong and should use + 2. Since this is a benchmark file testing different scenarios, it would make sense to use different data points for each test. The automated tool is asking the author to verify which is correct. However, according to the rules, I should NOT keep comments that ask the author to confirm, verify, check, or ensure things. The comment says "Please check if the comment should be updated to match the code or if the index calculation is incorrect" which is explicitly asking the author to verify/check. While this does identify a real inconsistency, the rules explicitly state "Do NOT ask the PR author to confirm their intention, to explain, to double-check things, to ensure the behavior is intended" and this comment is doing exactly that - asking them to check/verify. The comment doesn't definitively state what the fix should be. The critique is valid. Even though there's a genuine inconsistency between the comment and code, the automated comment is phrased as a request for the author to verify/check rather than stating a definitive issue. According to the rules, this type of comment should be removed. This comment should be deleted because it asks the author to "check" and verify which is correct, rather than stating a definitive issue. It violates the rule against asking authors to confirm, verify, or double-check things.
5. src/stateMachine/query/surql2/buildSurql.ts:333
  • Draft comment:
    Typo in the JSDoc comment for the esc function: the comment reads "Escape identifier with for SurrealDB" which appears incomplete. Consider clarifying (e.g., "Escape identifier using angle brackets for SurrealDB") for better readability.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% This is a documentation/comment improvement suggestion, not a code logic issue. The rules state "Do NOT comment unless there is clearly a code change required" and "Do NOT make comments that are obvious or unimportant." While the typo exists, fixing JSDoc comments is relatively minor and could be considered obvious/unimportant. However, the rules also say "Comments that suggest code quality refactors are good! But only if they are actionable and clear." This is actionable and clear. The key question is whether a JSDoc typo rises to the level of importance to keep the comment. Given that this is a new file being added, and the typo makes the documentation unclear about what escaping method is used, it could be valuable to fix. But it's borderline. This is just a documentation typo, not a functional issue. The code works fine regardless of the JSDoc comment. The rules emphasize not making obvious or unimportant comments, and a JSDoc typo might fall into that category. Additionally, the rule states to only comment when "there is clearly a code change required" - fixing documentation might not count as a required code change. While it's true this is just documentation, having clear and accurate documentation is part of code quality. The JSDoc is objectively incomplete/incorrect (missing text between "with" and "for"), and the suggestion is specific and actionable. However, given the emphasis in the rules on avoiding unimportant comments and only commenting when code changes are required, this likely doesn't meet the bar. This comment should be deleted. While the typo exists and the suggestion is valid, it's a minor documentation issue that doesn't affect functionality. The rules emphasize not making obvious or unimportant comments, and documentation typos typically fall into that category unless they cause significant confusion.
6. src/stateMachine/query/surql2/logical.ts:41
  • Draft comment:
    The comment starting with "This is the cardinality of" appears to be incomplete. Please complete or remove it for clarity.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% The comment is asking the PR author to complete or remove an incomplete comment. This falls under asking the author to update the PR description or similar, which is against the rules. Therefore, this comment should be removed.
7. src/types/schema/enriched.draft.ts:2
  • Draft comment:
    Typo in the file header: "These types are design for SurrealDB query in mind." should likely read "These types are designed for SurrealDB queries in mind."
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative, pointing out a typo in the file header. It doesn't provide a suggestion for code improvement or address any of the specific rules or guidelines provided.
8. tests/mocks/schema.ts:370
  • Draft comment:
    Typographical issue: There is a missing space in '2)replace only'. It would be clearer as '2) replace only' to maintain consistency with the other items listed.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative and focuses on a typographical issue, which does not impact the functionality or logic of the code. It does not align with the rules for useful comments, which should focus on code logic, functionality, or potential issues.
9. tests/unit/queries/query.ts:1485
  • Draft comment:
    Typo: There's an extra space in the commented out line (double space before 'email'). Consider reducing it to a single space for consistency.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is about a minor formatting issue in a comment, which doesn't affect the functionality of the code. It doesn't provide a meaningful improvement to the code's logic or structure, and it doesn't align with the rules provided. Therefore, it should be removed.

Workflow ID: wflow_KIYPbEz2a8k0vrvu

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

40 issues found across 33 files

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="src/index.ts">

<violation number="1" location="src/index.ts:156">
P2: Rule violated: **Flag Security Vulnerabilities**

Logging full error objects during initialization can expose sensitive data (connection strings, credentials) in production logs. Consider sanitizing the error output or using a structured logger that filters sensitive information.</violation>

<violation number="2" location="src/index.ts:210">
P1: Rule violated: **Check System Design and Architectural Patterns**

The condition `Date.now() &gt; 0` is always true and appears to be a debugging hack rather than a proper feature flag. This architectural anti-pattern:
- Forces the new code path without proper configuration controls
- Makes the branching logic meaningless (always takes new path when surrealDBClient exists)
- Bypasses existing `runQueryMachine` entirely without a proper toggle mechanism

Consider using a proper feature flag via configuration (e.g., `qConfig.useSurrealDbQueryMachine2`) or environment variable to control this behavior.</violation>
</file>

<file name="src/stateMachine/query/surql2/optimize.ts">

<violation number="1" location="src/stateMachine/query/surql2/optimize.ts:96">
P2: Rule violated: **Check System Design and Architectural Patterns**

DRY violation: Role field validation logic is duplicated in `convertRefFilterToRelationshipTraversal` (lines 85-94) and `convertNestedFilterToRelationshipTraversal` (lines 119-128). Extract this into a helper function like `validateRoleFieldForTraversal` to avoid maintenance issues.</violation>

<violation number="2" location="src/stateMachine/query/surql2/optimize.ts:160">
P2: Rule violated: **Check System Design and Architectural Patterns**

Dead code: `optimizeProjection` and `optimizeProjectionField` are defined but never called. The main entry point `optimizeLogicalQuery` passes through `query.projection` without optimization (line 14). Either wire up the projection optimization or remove these unused functions to avoid maintenance burden.</violation>

<violation number="3" location="src/stateMachine/query/surql2/optimize.ts:173">
P2: Wrong `thing` passed for nested reference optimization. The parent `thing` is used instead of resolving the nested field&#39;s target from the schema. This would cause incorrect filter optimization for nested references.</violation>
</file>

<file name="benches/v2.bench.ts">

<violation number="1" location="benches/v2.bench.ts:12">
P2: Rule violated: **Flag Security Vulnerabilities**

Hardcoded credentials detected. Even in benchmark/test code, database credentials should be loaded from environment variables to prevent accidental exposure in version control and to follow security best practices. Use `process.env` with dotenv to load these values.</violation>

<violation number="2" location="benches/v2.bench.ts:73">
P2: Comment says &quot;+ 2&quot; but code uses `+ 1`. This appears to be a copy-paste error from the previous bench test. Both tests will query the same element, which may not be the intended behavior.</violation>

<violation number="3" location="benches/v2.bench.ts:101">
P2: Rule violated: **Check System Design and Architectural Patterns**

DRY violation: The `createSurql`, `connect`, and `createSurqlBaseSet` functions are duplicated from `v2-2.bench.ts`. Extract these shared benchmark utilities to a common module (e.g., `benches/utils/surrealdb-helpers.ts`) to avoid maintenance burden and ensure consistency across benchmark files.</violation>
</file>

<file name="src/enrichSchema.draft.ts">

<violation number="1" location="src/enrichSchema.draft.ts:227">
P2: Bug: `oppositeRole` is an object, so this error message will display `[object Object]`. Use `lf.targetRole` to show the role name instead.</violation>

<violation number="2" location="src/enrichSchema.draft.ts:258">
P1: Rule violated: **Check System Design and Architectural Patterns**

This fallback logic is documented as incorrect in the TODO comment above it. The code knowingly implements behavior that will cause bugs in query transformations (as noted: queries using this will produce incorrect results). Either fix the implementation or throw an error when `targetingRelation` is not found, rather than falling back to `targetingRole` which produces semantically incorrect queries.</violation>

<violation number="3" location="src/enrichSchema.draft.ts:281">
P2: Rule violated: **Check System Design and Architectural Patterns**

Console.log statements violate proper architectural layering. Include this diagnostic information in the error message instead, or use a proper logging abstraction. This debug output will pollute stdout in production.</violation>
</file>

<file name="benches/insertData.v3.ts">

<violation number="1" location="benches/insertData.v3.ts:6">
P1: Rule violated: **Flag Security Vulnerabilities**

Hardcoded database credentials detected. Use environment variables instead (the project has `dotenv` as a dependency). Credentials in source code can be exposed through version control history.</violation>

<violation number="2" location="benches/insertData.v3.ts:24">
P2: Database connection is never closed. After the query completes, call `db.close()` to release the WebSocket connection and prevent resource leaks.</violation>

<violation number="3" location="benches/insertData.v3.ts:41">
P1: Rule violated: **Check System Design and Architectural Patterns**

This file duplicates code that already exists in `./generateData.ts`. The project has an established pattern where `insertData.v2.ts` imports shared types and the `generateData` function from that module. Instead of duplicating ~70 lines of code (interfaces `Base`, `A`, `B`, `generateData` function, and `uid` function), import them from the existing shared module to maintain consistency and reduce maintenance burden.</violation>

<violation number="4" location="benches/insertData.v3.ts:119">
P2: Rule violated: **Ensure all TypeScript code adheres to ECMAScript 2025 standards**

Use `nanoid` instead of custom `uid()` with `Math.random()`. The project already has `nanoid@^5.1.5` as a dependency, which is more secure (uses `crypto.getRandomValues`), more performant, and follows modern best practices for ID generation. `Math.random()` is not cryptographically secure and is considered a risky pattern for generating unique identifiers.</violation>
</file>

<file name="benches/rundb.v3.sh">

<violation number="1" location="benches/rundb.v3.sh:1">
P1: Add `set -euo pipefail` after the shebang to ensure the script exits on errors. This is a critical best practice for shell scripts to prevent silent failures.</violation>

<violation number="2" location="benches/rundb.v3.sh:5">
P1: Rule violated: **Flag Security Vulnerabilities**

Hardcoded credentials detected. The username and password (`borm_bench/borm_bench`) are hardcoded in the script. Even for benchmarking scripts, credentials should be sourced from environment variables (e.g., `${DB_USER:-default}`) to prevent accidental exposure and allow secure configuration.</violation>

<violation number="3" location="benches/rundb.v3.sh:49">
P3: Add a newline at the end of the file. POSIX requires text files to end with a newline character.</violation>
</file>

<file name="benches/insertData.v2.ts">

<violation number="1" location="benches/insertData.v2.ts:8">
P1: Rule violated: **Flag Security Vulnerabilities**

Hardcoded credentials detected. Even in benchmark files, passwords should not be committed to source control. Use environment variables with dotenv (already a project dependency) instead:
```typescript
const USERNAME = process.env.SURREAL_USERNAME ?? &#39;borm_bench&#39;;
const PASSWORD = process.env.SURREAL_PASSWORD ?? &#39;borm_bench&#39;;
```</violation>

<violation number="2" location="benches/insertData.v2.ts:22">
P2: Database connection is never closed after use. Consider calling `db.close()` after the query completes to properly release resources.</violation>
</file>

<file name="benches/rundb.v2.sh">

<violation number="1" location="benches/rundb.v2.sh:5">
P1: Rule violated: **Flag Security Vulnerabilities**

Hardcoded credentials detected. Even for benchmark/test scripts, credentials should be loaded from environment variables or a `.env` file (not committed to version control) rather than hardcoded in the script. This prevents accidental exposure and makes the script more secure.

Consider using:
```bash
USER=${SURREAL_USER:-borm_bench}
PASSWORD=${SURREAL_PASSWORD:-borm_bench}
```</violation>

<violation number="2" location="benches/rundb.v2.sh:22">
P2: Rule violated: **Flag Security Vulnerabilities**

The `--allow-all` flag grants all capabilities to SurrealDB, which is overly permissive. Even for benchmarking, consider specifying only the required capabilities explicitly to follow the principle of least privilege.</violation>

<violation number="3" location="benches/rundb.v2.sh:50">
P3: File is missing a newline at the end. POSIX requires text files to end with a newline character.</violation>
</file>

<file name="src/helpers.ts">

<violation number="1" location="src/helpers.ts:439">
P1: `Object.keys()` only returns string keys, never symbol keys. This filter will always return an empty array, so symbols will never be deleted. Use `Object.getOwnPropertySymbols(value)` instead.</violation>
</file>

<file name="benches/generateData.ts">

<violation number="1" location="benches/generateData.ts:27">
P2: Rule violated: **Ensure all TypeScript code adheres to ECMAScript 2025 standards**

String concatenation in loops is a less performant older pattern. Consider using `Array.from()` with `.join()` for more idiomatic modern JavaScript.</violation>

<violation number="2" location="benches/generateData.ts:60">
P1: Potential infinite loop: if `params.few.max` or `params.many.max` exceeds `params.records`, these while loops will never terminate because the Set cannot contain more unique IDs than exist in array `b`. Consider adding a guard condition or capping the length to `Math.min(fewLength, b.length)`.</violation>

<violation number="3" location="benches/generateData.ts:79">
P2: Rule violated: **Ensure all TypeScript code adheres to ECMAScript 2025 standards**

Use `nanoid` instead of custom `uid()` implementation. The project already has `nanoid@^5.1.5` as a dependency, which is a modern, cryptographically secure, and performant unique ID generator. The custom implementation using `Math.random()` is an older pattern that&#39;s less reliable.</violation>
</file>

<file name="src/stateMachine/query/surql2/buildLogical.ts">

<violation number="1" location="src/stateMachine/query/surql2/buildLogical.ts:72">
P2: Error message will display `[object Object]` because `field` is an object at this point. Use `field.$path` for a meaningful error message.</violation>

<violation number="2" location="src/stateMachine/query/surql2/buildLogical.ts:497">
P1: Incorrect operator mapping for `$contains` - it maps to `&#39;NOT IN&#39;` instead of a containment operator. The ternary `op === &#39;$eq&#39; ? &#39;IN&#39; : &#39;NOT IN&#39;` doesn&#39;t properly handle `$contains` and `$containsNot` cases.</violation>
</file>

<file name="benches/query.v3.ts">

<violation number="1" location="benches/query.v3.ts:8">
P2: Rule violated: **Flag Security Vulnerabilities**

Hardcoded credentials in source code. Even for benchmark files, use environment variables to avoid accidentally exposing secrets. Since the project includes `dotenv`, credentials should be loaded from environment variables (e.g., `process.env.USERNAME`).</violation>

<violation number="2" location="benches/query.v3.ts:22">
P2: Database connection is never closed after use. Call `db.close()` to properly release the connection resources before exiting. This prevents potential resource leaks, especially important if this benchmark pattern is reused elsewhere.</violation>
</file>

<file name="benches/schema.v2.surql">

<violation number="1" location="benches/schema.v2.surql:14">
P2: Type inconsistency: `array::first()` returns a single value, but fallback `|| []` returns an empty array. Consider using `|| NONE` instead to maintain consistent typing for a singular field.</violation>

<violation number="2" location="benches/schema.v2.surql:85">
P2: Logic bug: When `$var` is NONE/null, this returns `[null]` instead of an empty array `[]`. Consider adding a null check: `IF $var IS NONE THEN [] ELSE ...`</violation>
</file>

<file name="src/stateMachine/query/surql2/logical.ts">

<violation number="1" location="src/stateMachine/query/surql2/logical.ts:37">
P2: Misplaced JSDoc comment: This comment describes cardinality behavior but is positioned above the `filter` field instead of `cardinality`. Additionally, the actual `cardinality` field has an incomplete JSDoc comment that cuts off mid-sentence.</violation>
</file>

<file name="src/stateMachine/query/surql2/buildSurql.ts">

<violation number="1" location="src/stateMachine/query/surql2/buildSurql.ts:218">
P1: Bug: Double parameterization. `right[0]` is already a formatted string like `type::record($key)` from line 221, but it&#39;s being inserted as a parameter value again. This should directly use `right[0]` instead of re-parameterizing it.</violation>

<violation number="2" location="src/stateMachine/query/surql2/buildSurql.ts:286">
P1: Potential bug: `buildFilter` can return `undefined`, which would result in `NOT(undefined)` - invalid SQL. Add a null check before wrapping in NOT().</violation>

<violation number="3" location="src/stateMachine/query/surql2/buildSurql.ts:324">
P1: Rule violated: **Ensure all TypeScript code adheres to ECMAScript 2025 standards**

Replace custom `Math.random()`-based key generation with `nanoid`. The project already has `nanoid` as a dependency, which is a modern, secure, and performant solution for generating unique strings. `Math.random()` is not cryptographically secure and is considered a risky pattern for unique key generation.</violation>

<violation number="4" location="src/stateMachine/query/surql2/buildSurql.ts:337">
P1: Rule violated: **Flag Security Vulnerabilities**

Query injection vulnerability: The `esc` function does not escape the closing delimiter `⟩` within identifiers. An attacker-controlled identifier like `field⟩; DELETE * FROM users; --` would be wrapped as `⟨field⟩; DELETE * FROM users; --⟩`, breaking out of the escaping. Consider sanitizing `⟩` characters within identifiers (e.g., by escaping or rejecting them).</violation>
</file>

<file name="benches/v2-2.bench.ts">

<violation number="1" location="benches/v2-2.bench.ts:12">
P2: Rule violated: **Flag Security Vulnerabilities**

Hardcoded database credentials should be loaded from environment variables instead of being committed to source code. Even for benchmarks/tests, use `process.env` to avoid credential exposure in version control.</violation>

<violation number="2" location="benches/v2-2.bench.ts:175">
P2: Rule violated: **Flag Security Vulnerabilities**

Potential SurrealQL injection vulnerability: `data.string_1` is directly interpolated into the query without escaping special characters like quotes. Consider using parameterized queries or properly escaping string values.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

const queries = isBatched ? query : [query];

const surrealDBClient = initialized.dbHandles.surrealDB?.get('default')?.client;
if (surrealDBClient && Date.now() > 0) {
Copy link

@cubic-dev-ai cubic-dev-ai bot Dec 30, 2025

Choose a reason for hiding this comment

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

P1: Rule violated: Check System Design and Architectural Patterns

The condition Date.now() > 0 is always true and appears to be a debugging hack rather than a proper feature flag. This architectural anti-pattern:

  • Forces the new code path without proper configuration controls
  • Makes the branching logic meaningless (always takes new path when surrealDBClient exists)
  • Bypasses existing runQueryMachine entirely without a proper toggle mechanism

Consider using a proper feature flag via configuration (e.g., qConfig.useSurrealDbQueryMachine2) or environment variable to control this behavior.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/index.ts, line 210:

<comment>The condition `Date.now() &gt; 0` is always true and appears to be a debugging hack rather than a proper feature flag. This architectural anti-pattern:
- Forces the new code path without proper configuration controls
- Makes the branching logic meaningless (always takes new path when surrealDBClient exists)
- Bypasses existing `runQueryMachine` entirely without a proper toggle mechanism

Consider using a proper feature flag via configuration (e.g., `qConfig.useSurrealDbQueryMachine2`) or environment variable to control this behavior.</comment>

<file context>
@@ -201,6 +206,12 @@ class BormClient {
     const queries = isBatched ? query : [query];
 
+    const surrealDBClient = initialized.dbHandles.surrealDB?.get(&#39;default&#39;)?.client;
+    if (surrealDBClient &amp;&amp; Date.now() &gt; 0) {
+      const result = await runSurrealDbQueryMachine2(queries, initialized.draftSchema, qConfig, surrealDBClient);
+      return isBatched ? result : result[0];
</file context>
Fix with Cubic

if ((field.type !== 'role' && field.type !== 'link') || (filter.op !== 'IN' && filter.op !== 'CONTAINSANY')) {
return undefined;
}
if (field.type === 'role') {
Copy link

@cubic-dev-ai cubic-dev-ai bot Dec 30, 2025

Choose a reason for hiding this comment

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

P2: Rule violated: Check System Design and Architectural Patterns

DRY violation: Role field validation logic is duplicated in convertRefFilterToRelationshipTraversal (lines 85-94) and convertNestedFilterToRelationshipTraversal (lines 119-128). Extract this into a helper function like validateRoleFieldForTraversal to avoid maintenance issues.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/stateMachine/query/surql2/optimize.ts, line 96:

<comment>DRY violation: Role field validation logic is duplicated in `convertRefFilterToRelationshipTraversal` (lines 85-94) and `convertNestedFilterToRelationshipTraversal` (lines 119-128). Extract this into a helper function like `validateRoleFieldForTraversal` to avoid maintenance issues.</comment>

<file context>
@@ -0,0 +1,406 @@
+  if ((field.type !== &#39;role&#39; &amp;&amp; field.type !== &#39;link&#39;) || (filter.op !== &#39;IN&#39; &amp;&amp; filter.op !== &#39;CONTAINSANY&#39;)) {
+    return undefined;
+  }
+  if (field.type === &#39;role&#39;) {
+    // We can&#39;t do this optimization for role fields that are not played by a link field with target &#39;relation&#39;.
+    // This relation is only used as intermediary relation.
</file context>
Fix with Cubic

return traversal;
}

const optimizeProjection = (projection: Projection, schema: DRAFT_EnrichedBormSchema, thing: DRAFT_EnrichedBormEntity | DRAFT_EnrichedBormRelation): Projection => {
Copy link

@cubic-dev-ai cubic-dev-ai bot Dec 30, 2025

Choose a reason for hiding this comment

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

P2: Rule violated: Check System Design and Architectural Patterns

Dead code: optimizeProjection and optimizeProjectionField are defined but never called. The main entry point optimizeLogicalQuery passes through query.projection without optimization (line 14). Either wire up the projection optimization or remove these unused functions to avoid maintenance burden.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/stateMachine/query/surql2/optimize.ts, line 160:

<comment>Dead code: `optimizeProjection` and `optimizeProjectionField` are defined but never called. The main entry point `optimizeLogicalQuery` passes through `query.projection` without optimization (line 14). Either wire up the projection optimization or remove these unused functions to avoid maintenance burden.</comment>

<file context>
@@ -0,0 +1,406 @@
+  return traversal;
+}
+
+const optimizeProjection = (projection: Projection, schema: DRAFT_EnrichedBormSchema, thing: DRAFT_EnrichedBormEntity | DRAFT_EnrichedBormRelation): Projection =&gt; {
+  return {
+    fields: projection.fields.map((field) =&gt; optimizeProjectionField(field, schema, thing)),
</file context>
Fix with Cubic

return db;
}

const createSurql = (data: { a: A[]; b: B[]; }): string => {
Copy link

@cubic-dev-ai cubic-dev-ai bot Dec 30, 2025

Choose a reason for hiding this comment

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

P2: Rule violated: Check System Design and Architectural Patterns

DRY violation: The createSurql, connect, and createSurqlBaseSet functions are duplicated from v2-2.bench.ts. Extract these shared benchmark utilities to a common module (e.g., benches/utils/surrealdb-helpers.ts) to avoid maintenance burden and ensure consistency across benchmark files.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At benches/v2.bench.ts, line 101:

<comment>DRY violation: The `createSurql`, `connect`, and `createSurqlBaseSet` functions are duplicated from `v2-2.bench.ts`. Extract these shared benchmark utilities to a common module (e.g., `benches/utils/surrealdb-helpers.ts`) to avoid maintenance burden and ensure consistency across benchmark files.</comment>

<file context>
@@ -0,0 +1,149 @@
+    return db;
+}
+
+const createSurql = (data: { a: A[]; b: B[]; }): string =&gt; {
+  const lines = [&#39;BEGIN TRANSACTION;&#39;];
+
</file context>
Fix with Cubic

if (isEqual(newField, existing)) {
return;
}
console.log('\n> assertNoDuplicateField/newField\n', JSON.stringify(newField, null, 2));
Copy link

@cubic-dev-ai cubic-dev-ai bot Dec 30, 2025

Choose a reason for hiding this comment

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

P2: Rule violated: Check System Design and Architectural Patterns

Console.log statements violate proper architectural layering. Include this diagnostic information in the error message instead, or use a proper logging abstraction. This debug output will pollute stdout in production.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/enrichSchema.draft.ts, line 281:

<comment>Console.log statements violate proper architectural layering. Include this diagnostic information in the error message instead, or use a proper logging abstraction. This debug output will pollute stdout in production.</comment>

<file context>
@@ -0,0 +1,453 @@
+  if (isEqual(newField, existing)) {
+    return;
+  }
+  console.log(&#39;\n&gt; assertNoDuplicateField/newField\n&#39;, JSON.stringify(newField, null, 2));
+  console.log(&#39;\n&gt; assertNoDuplicateField/existing\n&#39;, JSON.stringify(existing, null, 2));
+  throw new Error(`Duplicate field name &quot;${newField.name}&quot; in &quot;${thing}&quot;`);
</file context>
Fix with Cubic

const NAMESPACE = 'borm_bench';
const DATABASE = 'borm_bench';
const USERNAME = 'borm_bench';
const PASSWORD = 'borm_bench';
Copy link

@cubic-dev-ai cubic-dev-ai bot Dec 30, 2025

Choose a reason for hiding this comment

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

P2: Rule violated: Flag Security Vulnerabilities

Hardcoded credentials in source code. Even for benchmark files, use environment variables to avoid accidentally exposing secrets. Since the project includes dotenv, credentials should be loaded from environment variables (e.g., process.env.USERNAME).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At benches/query.v3.ts, line 8:

<comment>Hardcoded credentials in source code. Even for benchmark files, use environment variables to avoid accidentally exposing secrets. Since the project includes `dotenv`, credentials should be loaded from environment variables (e.g., `process.env.USERNAME`).</comment>

<file context>
@@ -0,0 +1,41 @@
+const NAMESPACE = &#39;borm_bench&#39;;
+const DATABASE = &#39;borm_bench&#39;;
+const USERNAME = &#39;borm_bench&#39;;
+const PASSWORD = &#39;borm_bench&#39;;
+
+const query = async () =&gt; {
</file context>
Fix with Cubic

};

const createSurqlBaseSet = (data: Base): string => {
return `string_1 = "${data.string_1}", number_1 = ${data.number_1}, boolean_1 = ${data.boolean_1}, datetime_1 = type::datetime("${data.datetime_1.toISOString()}")`;
Copy link

@cubic-dev-ai cubic-dev-ai bot Dec 30, 2025

Choose a reason for hiding this comment

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

P2: Rule violated: Flag Security Vulnerabilities

Potential SurrealQL injection vulnerability: data.string_1 is directly interpolated into the query without escaping special characters like quotes. Consider using parameterized queries or properly escaping string values.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At benches/v2-2.bench.ts, line 175:

<comment>Potential SurrealQL injection vulnerability: `data.string_1` is directly interpolated into the query without escaping special characters like quotes. Consider using parameterized queries or properly escaping string values.</comment>

<file context>
@@ -0,0 +1,176 @@
+};
+
+const createSurqlBaseSet = (data: Base): string =&gt; {
+  return `string_1 = &quot;${data.string_1}&quot;, number_1 = ${data.number_1}, boolean_1 = ${data.boolean_1}, datetime_1 = type::datetime(&quot;${data.datetime_1.toISOString()}&quot;)`;
+};
\ No newline at end of file
</file context>
Fix with Cubic

const NAMESPACE = 'borm_bench';
const DATABASE = 'borm_bench';
const USERNAME = 'borm_bench';
const PASSWORD = 'borm_bench';
Copy link

@cubic-dev-ai cubic-dev-ai bot Dec 30, 2025

Choose a reason for hiding this comment

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

P2: Rule violated: Flag Security Vulnerabilities

Hardcoded database credentials should be loaded from environment variables instead of being committed to source code. Even for benchmarks/tests, use process.env to avoid credential exposure in version control.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At benches/v2-2.bench.ts, line 12:

<comment>Hardcoded database credentials should be loaded from environment variables instead of being committed to source code. Even for benchmarks/tests, use `process.env` to avoid credential exposure in version control.</comment>

<file context>
@@ -0,0 +1,176 @@
+const NAMESPACE = &#39;borm_bench&#39;;
+const DATABASE = &#39;borm_bench&#39;;
+const USERNAME = &#39;borm_bench&#39;;
+const PASSWORD = &#39;borm_bench&#39;;
+
+let client: BormClient;
</file context>
Fix with Cubic

s();
}
} catch (e) {
console.error('error initializing', e);
Copy link

@cubic-dev-ai cubic-dev-ai bot Dec 30, 2025

Choose a reason for hiding this comment

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

P2: Rule violated: Flag Security Vulnerabilities

Logging full error objects during initialization can expose sensitive data (connection strings, credentials) in production logs. Consider sanitizing the error output or using a structured logger that filters sensitive information.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/index.ts, line 156:

<comment>Logging full error objects during initialization can expose sensitive data (connection strings, credentials) in production logs. Consider sanitizing the error output or using a structured logger that filters sensitive information.</comment>

<file context>
@@ -149,6 +153,7 @@ class BormClient {
         s();
       }
     } catch (e) {
+      console.error(&#39;error initializing&#39;, e);
       const subscribers = this.subscribers;
       this.subscribers = [];
</file context>
Fix with Cubic

* Escape identifier with for SurrealDB
* Only escapes when identifier contains non-alphanumeric characters or starts with a number
*/
const esc = (identifier: string): string => {
Copy link

@cubic-dev-ai cubic-dev-ai bot Dec 30, 2025

Choose a reason for hiding this comment

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

P1: Rule violated: Flag Security Vulnerabilities

Query injection vulnerability: The esc function does not escape the closing delimiter within identifiers. An attacker-controlled identifier like field⟩; DELETE * FROM users; -- would be wrapped as ⟨field⟩; DELETE * FROM users; --⟩, breaking out of the escaping. Consider sanitizing characters within identifiers (e.g., by escaping or rejecting them).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/stateMachine/query/surql2/buildSurql.ts, line 337:

<comment>Query injection vulnerability: The `esc` function does not escape the closing delimiter `⟩` within identifiers. An attacker-controlled identifier like `field⟩; DELETE * FROM users; --` would be wrapped as `⟨field⟩; DELETE * FROM users; --⟩`, breaking out of the escaping. Consider sanitizing `⟩` characters within identifiers (e.g., by escaping or rejecting them).</comment>

<file context>
@@ -0,0 +1,341 @@
+ * Escape identifier with  for SurrealDB
+ * Only escapes when identifier contains non-alphanumeric characters or starts with a number
+ */
+const esc = (identifier: string): string =&gt; {
+  // Check if identifier starts with a number or contains non-alphanumeric characters (excluding underscore)
+  const needsEscaping = /^[0-9]/.test(identifier) || /[^a-zA-Z0-9_]/.test(identifier);
</file context>
Fix with Cubic

Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed 978e4da in 1 minute and 9 seconds. Click for details.
  • Reviewed 13 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 1 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. benches/bench.ts:97
  • Draft comment:
    Switching 'first' to use variant.durations[0] ensures it reflects the first iteration’s timing rather than the minimum. Confirm this is the intended behavior.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% The comment is asking for confirmation of the intended behavior, which violates the rule against asking the PR author to confirm their intention. It does not provide a specific code suggestion or ask for a test to be written. Therefore, it should be removed.

Workflow ID: wflow_b7mNPgpcRGqy82hS

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

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