Skip to content

Unflattening array fix for very large arrays #1432

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ jobs:
SESSION_SECRET: "secret"
MAGIC_LINK_SECRET: "secret"
ENCRYPTION_KEY: "secret"


Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove trailing whitespace.

There are trailing spaces on this line that should be removed.

Apply this diff to fix the formatting:

-      
+
📝 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
🧰 Tools
🪛 yamllint

[error] 41-41: trailing spaces

(trailing-spaces)

- name: 🧪 Run Package Unit Tests
run: pnpm run test --filter "@trigger.dev/*"

- name: 🧪 Run Internal Unit Tests
run: pnpm run test --filter "@internal/*"
45 changes: 28 additions & 17 deletions packages/core/src/v3/utils/flattenAttributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,36 +95,47 @@ export function unflattenAttributes(
const result: Record<string, unknown> = {};

for (const [key, value] of Object.entries(obj)) {
const parts = key.split(".").reduce((acc, part) => {
if (part.includes("[")) {
// Handling nested array indices
const subparts = part.split(/\[|\]/).filter((p) => p !== "");
acc.push(...subparts);
} else {
acc.push(part);
}
return acc;
}, [] as string[]);
const parts = key.split(".").reduce(
(acc, part) => {
if (part.startsWith("[") && part.endsWith("]")) {
// Handle array indices more precisely
const match = part.match(/^\[(\d+)\]$/);
if (match && match[1]) {
acc.push(parseInt(match[1]));
} else {
// Remove brackets for non-numeric array keys
acc.push(part.slice(1, -1));
}
} else {
acc.push(part);
}
return acc;
},
[] as (string | number)[]
);
Comment on lines +98 to +115
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider adding numeric bounds validation for array indices.

While the regex pattern correctly identifies numeric indices, it doesn't prevent the issue with very large numbers. Consider adding a size check to prevent array allocation attacks.

Apply this diff to add bounds validation:

 const match = part.match(/^\[(\d+)\]$/);
 if (match && match[1]) {
+  const index = parseInt(match[1]);
+  if (index > Number.MAX_SAFE_INTEGER) {
+    // Treat very large numbers as string keys
+    acc.push(part);
+  } else {
-    acc.push(parseInt(match[1]));
+    acc.push(index);
+  }
 } else {
📝 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
const parts = key.split(".").reduce(
(acc, part) => {
if (part.startsWith("[") && part.endsWith("]")) {
// Handle array indices more precisely
const match = part.match(/^\[(\d+)\]$/);
if (match && match[1]) {
acc.push(parseInt(match[1]));
} else {
// Remove brackets for non-numeric array keys
acc.push(part.slice(1, -1));
}
} else {
acc.push(part);
}
return acc;
},
[] as (string | number)[]
);
const parts = key.split(".").reduce(
(acc, part) => {
if (part.startsWith("[") && part.endsWith("]")) {
// Handle array indices more precisely
const match = part.match(/^\[(\d+)\]$/);
if (match && match[1]) {
const index = parseInt(match[1]);
if (index > Number.MAX_SAFE_INTEGER) {
// Treat very large numbers as string keys
acc.push(part);
} else {
acc.push(index);
}
} else {
// Remove brackets for non-numeric array keys
acc.push(part.slice(1, -1));
}
} else {
acc.push(part);
}
return acc;
},
[] as (string | number)[]
);
🧰 Tools
🪛 Biome

[error] 103-103: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


let current: any = result;
for (let i = 0; i < parts.length - 1; i++) {
const part = parts[i];
const nextPart = parts[i + 1];

if (!part) {
if (!part && part !== 0) {
continue;
}

const nextPart = parts[i + 1];
const isArray = nextPart && /^\d+$/.test(nextPart);
if (isArray && !Array.isArray(current[part])) {
current[part] = [];
} else if (!isArray && current[part] === undefined) {
if (typeof nextPart === "number") {
// Ensure we create an array for numeric indices
current[part] = Array.isArray(current[part]) ? current[part] : [];
} else if (current[part] === undefined) {
// Create an object for non-numeric paths
Comment on lines +126 to +130
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Strengthen type safety in array/object creation.

The current implementation could benefit from more explicit type checking and array initialization.

Consider these improvements:

-if (typeof nextPart === "number") {
+if (typeof nextPart === "number" && Number.isInteger(nextPart) && nextPart >= 0) {
   // Ensure we create an array for numeric indices
-  current[part] = Array.isArray(current[part]) ? current[part] : [];
+  current[part] = Array.isArray(current[part]) ? current[part] : new Array();
 } else if (current[part] === undefined) {
   // Create an object for non-numeric paths
-  current[part] = {};
+  current[part] = Object.create(null);
 }
📝 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
if (typeof nextPart === "number") {
// Ensure we create an array for numeric indices
current[part] = Array.isArray(current[part]) ? current[part] : [];
} else if (current[part] === undefined) {
// Create an object for non-numeric paths
if (typeof nextPart === "number" && Number.isInteger(nextPart) && nextPart >= 0) {
// Ensure we create an array for numeric indices
current[part] = Array.isArray(current[part]) ? current[part] : new Array();
} else if (current[part] === undefined) {
// Create an object for non-numeric paths
current[part] = Object.create(null);

current[part] = {};
}

current = current[part];
}

const lastPart = parts[parts.length - 1];
if (lastPart) {
if (lastPart !== undefined) {
current[lastPart] = rehydrateNull(value);
}
}
Expand Down
14 changes: 14 additions & 0 deletions packages/core/test/flattenAttributes.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
import { flattenAttributes, unflattenAttributes } from "../src/v3/utils/flattenAttributes.js";

describe("flattenAttributes", () => {
it("handles number keys correctl", () => {
expect(flattenAttributes({ bar: { "25": "foo" } })).toEqual({ "bar.25": "foo" });
expect(unflattenAttributes({ "bar.25": "foo" })).toEqual({ bar: { "25": "foo" } });
expect(flattenAttributes({ bar: ["foo", "baz"] })).toEqual({
"bar.[0]": "foo",
"bar.[1]": "baz",
});
expect(unflattenAttributes({ "bar.[0]": "foo", "bar.[1]": "baz" })).toEqual({
bar: ["foo", "baz"],
});
expect(flattenAttributes({ bar: { 25: "foo" } })).toEqual({ "bar.25": "foo" });
expect(unflattenAttributes({ "bar.25": "foo" })).toEqual({ bar: { 25: "foo" } });
});
Comment on lines +4 to +16
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add test cases for large numeric keys.

While the test covers basic number keys, it doesn't verify the specific issue mentioned in the PR objectives regarding very large numeric keys. Consider adding test cases that validate the fix for keys like "akey.with.a.large.number.1234567890123".

Add these test cases:

expect(flattenAttributes({ "akey.with.a.large.number.1234567890123": "value" }))
  .toEqual({ "akey.with.a.large.number.1234567890123": "value" });

expect(unflattenAttributes({ "akey.with.a.large.number.1234567890123": "value" }))
  .toEqual({ "akey.with.a.large.number.1234567890123": "value" });

// Verify that array indices still work correctly
expect(flattenAttributes({ array: ["value"] }))
  .toEqual({ "array.[0]": "value" });


it("handles null correctly", () => {
expect(flattenAttributes(null)).toEqual({ "": "$@null((" });
expect(unflattenAttributes({ "": "$@null((" })).toEqual(null);
Expand Down
Loading