File size: 37,560 Bytes
517fae7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
{
  "revision": "coding-rubric-v2",
  "task_id": "bulkcreate_ignore_duplicates",
  "grader_version": "0.6.13",
  "commands": [
    {
      "name": "aligned_inserted",
      "weight": 0.1875,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "CRITERION aligned_inserted: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh aligned_inserted'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 900
        }
      }
    },
    {
      "name": "skipped_honest",
      "weight": 0.125,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "CRITERION skipped_honest: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh skipped_honest'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 900
        }
      }
    },
    {
      "name": "expression_columns",
      "weight": 0.0625,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "CRITERION expression_columns: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh expression_columns'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 900
        }
      }
    },
    {
      "name": "skipped_timestamps",
      "weight": 0.0625,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "CRITERION skipped_timestamps: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh skipped_timestamps'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 900
        }
      }
    },
    {
      "name": "returning_restricted",
      "weight": 0.125,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "CRITERION returning_restricted: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh returning_restricted'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 900
        }
      }
    },
    {
      "name": "date_key",
      "weight": 0.0625,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "CRITERION date_key: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh date_key'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 900
        }
      }
    },
    {
      "name": "children_attachment",
      "weight": 0.0625,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "CRITERION children_attachment: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh children_attachment'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 900
        }
      }
    },
    {
      "name": "key_variants",
      "weight": 0.0625,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "CRITERION key_variants: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh key_variants'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 900
        }
      }
    },
    {
      "name": "untouched_paths",
      "weight": 0.0625,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "CRITERION untouched_paths: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh untouched_paths'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 900
        }
      }
    },
    {
      "name": "no_regression",
      "weight": 0.0625,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "CRITERION no_regression: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh no_regression'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 1800
        }
      }
    },
    {
      "name": "test_quality",
      "weight": 0.0625,
      "value": 1.0,
      "children": null,
      "info": {
        "exit_code": 0,
        "stdout": "  [grader] agent test files: integration/model/bulk-create/ignore-duplicates.test.ts\nCRITERION test_quality: PASS\n",
        "stderr": "",
        "_parameters": {
          "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh test_quality'",
          "cwd": "/workspace/repo",
          "timeout_seconds": 900
        }
      }
    }
  ],
  "status": "graded",
  "patch_sha256": "a19e606fc3fa9a6d1dfb1a40783e4b09cd4ec91dc25d73b4a36cd490b54f39c4",
  "result": {
    "reward": 1.0,
    "done": true,
    "content": null,
    "info": {
      "diff_stat": {
        "files": [
          "packages/core/src/model.js",
          "packages/core/test/integration/model/bulk-create/ignore-duplicates.test.ts"
        ],
        "added": 444,
        "removed": 1
      },
      "graded_diff": "diff --git a/packages/core/src/model.js b/packages/core/src/model.js\nindex cb25a68..da84d68 100644\n--- a/packages/core/src/model.js\n+++ b/packages/core/src/model.js\n@@ -2327,6 +2327,10 @@ ${associationOwner._getAssociationDebugList()}`);\n \n       const modelDefinition = model.modelDefinition;\n \n+      // Instances whose row the database skipped (ignoreDuplicates). They are\n+      // left as the caller built them: unsaved, and carrying no other row's values.\n+      const skipped = new Set();\n+\n       options.fields = options.fields || Array.from(modelDefinition.attributes.keys());\n       const createdAtAttr = modelDefinition.timestampAttributeNames.createdAt;\n       const updatedAtAttr = modelDefinition.timestampAttributeNames.updatedAt;\n@@ -2497,6 +2501,21 @@ ${associationOwner._getAssociationDebugList()}`);\n           );\n         }\n \n+        // With ignoreDuplicates, a RETURNING dialect only hands back the rows\n+        // it actually inserted, so the returned rows cannot be matched to the\n+        // records by position. They are matched on the model's candidate keys\n+        // instead; make sure those columns come back even when the caller\n+        // restricted the returning list.\n+        const identityKeys =\n+          options.ignoreDuplicates &&\n+          options.returning &&\n+          model.sequelize.dialect.supports.returnValues\n+            ? model._bulkCreateIdentityKeys()\n+            : null;\n+        if (identityKeys && Array.isArray(options.returning)) {\n+          options.returning = uniq([...options.returning, ...identityKeys.flat()]);\n+        }\n+\n         const results = await model.queryInterface.bulkInsert(\n           model.table,\n           records,\n@@ -2504,9 +2523,17 @@ ${associationOwner._getAssociationDebugList()}`);\n           fieldMappedAttributes,\n         );\n         if (Array.isArray(results)) {\n-          for (const [i, result] of results.entries()) {\n+          const resultForInstance = identityKeys\n+            ? model._matchReturnedRows(instances, records, results, identityKeys, skipped)\n+            : results;\n+\n+          for (const [i, result] of resultForInstance.entries()) {\n             const instance = instances[i];\n \n+            if (!result) {\n+              continue;\n+            }\n+\n             for (const key in result) {\n               if (!Object.hasOwn(result, key)) {\n                 continue;\n@@ -2555,6 +2582,12 @@ ${associationOwner._getAssociationDebugList()}`);\n               const associationInstanceIndexToInstanceMap = [];\n \n               for (const instance of instances) {\n+                if (skipped.has(instance)) {\n+                  // the parent row was not created by this call, so its key\n+                  // is unknown; its children must not be stored under it\n+                  continue;\n+                }\n+\n                 let associated = instance.get(include.as);\n                 if (!Array.isArray(associated)) {\n                   associated = [associated];\n@@ -2660,6 +2693,20 @@ ${associationOwner._getAssociationDebugList()}`);\n \n       // map fields back to attributes\n       for (const instance of instances) {\n+        if (skipped.has(instance)) {\n+          // the timestamps this call filled in were never stored for a\n+          // skipped record; drop them so the instance shows only its own state\n+          if (createdAtAttr && instance.dataValues[createdAtAttr] === now) {\n+            delete instance.dataValues[createdAtAttr];\n+          }\n+\n+          if (updatedAtAttr && instance.dataValues[updatedAtAttr] === now) {\n+            delete instance.dataValues[updatedAtAttr];\n+          }\n+\n+          continue;\n+        }\n+\n         const attributeDefs = modelDefinition.attributes;\n \n         for (const attribute of attributeDefs.values()) {\n@@ -2692,6 +2739,165 @@ ${associationOwner._getAssociationDebugList()}`);\n     return await recursiveBulkCreate(instances, options);\n   }\n \n+  /**\n+   * The column sets a returned row can be identified by: the primary key and\n+   * every non-partial unique index. Used by {@link Model.bulkCreate} to match\n+   * the rows a RETURNING dialect hands back to the records that were sent\n+   * when `ignoreDuplicates` may have skipped some of them.\n+   *\n+   * @returns {string[][]} column names, one array per candidate key\n+   * @private\n+   */\n+  static _bulkCreateIdentityKeys() {\n+    const keys = [];\n+    const seen = new Set();\n+    const add = columns => {\n+      const normalized = columns.map(column => (typeof column === 'string' ? column : column.name));\n+      const id = normalized.join('\\0');\n+      if (normalized.length > 0 && !seen.has(id)) {\n+        seen.add(id);\n+        keys.push(normalized);\n+      }\n+    };\n+\n+    add(Object.values(this.primaryKeys).map(attribute => attribute.field));\n+    for (const index of this.getIndexes()) {\n+      if (index.unique && !index.where && index.fields) {\n+        add(index.fields);\n+      }\n+    }\n+\n+    return keys;\n+  }\n+\n+  /**\n+   * Pairs the rows returned by a bulk INSERT with the records that produced\n+   * them. A row belongs to the first not-yet-paired record that agrees with\n+   * it on one of the candidate keys; the row order is never relied on.\n+   * Records that no row matches were skipped by the database and are added\n+   * to `skipped`. Refuses to guess: if a returned row cannot be attributed\n+   * to any record, an error is thrown rather than assigning it by position.\n+   *\n+   * @param {Model[]} instances the instances, in record order\n+   * @param {object[]} records the column-keyed values sent for each instance\n+   * @param {object[]} results the rows the database returned\n+   * @param {string[][]} identityKeys from {@link Model._bulkCreateIdentityKeys}\n+   * @param {Set<Model>} skipped receives the instances whose row was not inserted\n+   * @returns {Array<object|null>} the matching row for each instance, or null\n+   * @private\n+   */\n+  static _matchReturnedRows(instances, records, results, identityKeys, skipped) {\n+    const modelDefinition = this.modelDefinition;\n+\n+    const normalize = value => {\n+      if (value instanceof Date) {\n+        return value.toISOString();\n+      }\n+\n+      if (Buffer.isBuffer(value)) {\n+        return value.toString('hex');\n+      }\n+\n+      return String(value);\n+    };\n+\n+    const parseRow = row => {\n+      const out = pojo();\n+      for (const column of Object.keys(row)) {\n+        const attribute = modelDefinition.columns.get(column);\n+        out[column] =\n+          row[column] != null && attribute?.type instanceof AbstractDataType\n+            ? attribute.type.parseDatabaseValue(row[column])\n+            : row[column];\n+      }\n+\n+      return out;\n+    };\n+\n+    // every key signature a column-keyed value set can be identified by\n+    const signaturesOf = values => {\n+      const signatures = [];\n+      for (const [k, key] of identityKeys.entries()) {\n+        const parts = [];\n+        for (const column of key) {\n+          if (values[column] == null) {\n+            parts.length = 0;\n+            break;\n+          }\n+\n+          parts.push(normalize(values[column]));\n+        }\n+\n+        if (parts.length > 0) {\n+          signatures.push(`${k}:${parts.join('\\0')}`);\n+        }\n+      }\n+\n+      return signatures;\n+    };\n+\n+    const rowsBySignature = new Map();\n+    const unpaired = new Set(results);\n+    for (const row of results) {\n+      for (const signature of signaturesOf(parseRow(row))) {\n+        if (!rowsBySignature.has(signature)) {\n+          rowsBySignature.set(signature, []);\n+        }\n+\n+        rowsBySignature.get(signature).push(row);\n+      }\n+    }\n+\n+    const paired = instances.map(() => null);\n+    const withoutKey = [];\n+    for (const [i, instance] of instances.entries()) {\n+      const signatures = signaturesOf(records[i]);\n+      if (signatures.length === 0) {\n+        withoutKey.push(i);\n+        continue;\n+      }\n+\n+      for (const signature of signatures) {\n+        const row = (rowsBySignature.get(signature) ?? []).find(candidate =>\n+          unpaired.has(candidate),\n+        );\n+        if (row) {\n+          paired[i] = row;\n+          unpaired.delete(row);\n+          break;\n+        }\n+      }\n+\n+      if (!paired[i]) {\n+        skipped.add(instance);\n+      }\n+    }\n+\n+    // Records that carry no value for any candidate key cannot have\n+    // conflicted, so the leftover rows are theirs, provided the counts agree.\n+    if (withoutKey.length > 0) {\n+      if (unpaired.size !== withoutKey.length) {\n+        throw new Error(\n+          `bulkCreate could not attribute the rows returned by the database to the records: ${unpaired.size} returned row(s) left for ${withoutKey.length} record(s) without a key value.`,\n+        );\n+      }\n+\n+      const leftovers = results.filter(row => unpaired.has(row));\n+      for (const [j, i] of withoutKey.entries()) {\n+        paired[i] = leftovers[j];\n+        unpaired.delete(leftovers[j]);\n+      }\n+    }\n+\n+    if (unpaired.size > 0) {\n+      throw new Error(\n+        `bulkCreate could not attribute ${unpaired.size} row(s) returned by the database to any record. Every candidate key column must be part of the returned columns.`,\n+      );\n+    }\n+\n+    return paired;\n+  }\n+\n   /**\n    * Truncates the table associated with the model.\n    *\ndiff --git a/packages/core/test/integration/model/bulk-create/ignore-duplicates.test.ts b/packages/core/test/integration/model/bulk-create/ignore-duplicates.test.ts\nnew file mode 100644\nindex 0000000..69e8c1a\n--- /dev/null\n+++ b/packages/core/test/integration/model/bulk-create/ignore-duplicates.test.ts\n@@ -0,0 +1,237 @@\n+import type {\n+  CreationOptional,\n+  InferAttributes,\n+  InferCreationAttributes,\n+  NonAttribute,\n+} from '@sequelize/core';\n+import { DataTypes, Model } from '@sequelize/core';\n+import { expect } from 'chai';\n+import { beforeAll2, sequelize, setResetMode } from '../../support';\n+\n+const dialect = sequelize.dialect;\n+\n+// With ignoreDuplicates, a RETURNING dialect only returns the rows it actually\n+// inserted. The instances bulkCreate returns must still line up with the\n+// records that were passed in.\n+describe('Model.bulkCreate with ignoreDuplicates on a RETURNING dialect', () => {\n+  if (\n+    !dialect.supports.returnValues ||\n+    !(dialect.supports.inserts.ignoreDuplicates || dialect.supports.inserts.onConflictDoNothing)\n+  ) {\n+    return;\n+  }\n+\n+  setResetMode('destroy');\n+\n+  const vars = beforeAll2(async () => {\n+    class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {\n+      declare id: CreationOptional<number>;\n+      declare uniqueName: string;\n+      declare secretValue: string | null;\n+      declare createdAt: CreationOptional<Date>;\n+      declare updatedAt: CreationOptional<Date>;\n+      declare tasks?: NonAttribute<Task[]>;\n+    }\n+\n+    class Task extends Model<InferAttributes<Task>, InferCreationAttributes<Task>> {\n+      declare id: CreationOptional<number>;\n+      declare title: string;\n+      declare userId: CreationOptional<number | null>;\n+    }\n+\n+    class Seat extends Model<InferAttributes<Seat>, InferCreationAttributes<Seat>> {\n+      declare id: CreationOptional<number>;\n+      declare room: string;\n+      declare number: number;\n+      declare label: string | null;\n+    }\n+\n+    class Code extends Model<InferAttributes<Code>, InferCreationAttributes<Code>> {\n+      declare code: string;\n+      declare label: string | null;\n+    }\n+\n+    User.init(\n+      {\n+        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n+        uniqueName: { type: DataTypes.STRING, unique: true, allowNull: false },\n+        secretValue: DataTypes.STRING,\n+      },\n+      { sequelize },\n+    );\n+    Task.init(\n+      {\n+        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n+        title: { type: DataTypes.STRING, allowNull: false },\n+      },\n+      { sequelize },\n+    );\n+    Seat.init(\n+      {\n+        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n+        room: { type: DataTypes.STRING, allowNull: false },\n+        number: { type: DataTypes.INTEGER, allowNull: false },\n+        label: DataTypes.STRING,\n+      },\n+      { sequelize, indexes: [{ unique: true, fields: ['room', 'number'] }] },\n+    );\n+    Code.init(\n+      {\n+        code: { type: DataTypes.STRING, primaryKey: true },\n+        label: DataTypes.STRING,\n+      },\n+      { sequelize },\n+    );\n+\n+    User.hasMany(Task, { as: 'tasks', foreignKey: 'userId' });\n+\n+    await sequelize.sync({ force: true });\n+\n+    return { User, Task, Seat, Code };\n+  });\n+\n+  it('assigns each returned row to its own record when some records are skipped', async () => {\n+    const { User } = vars;\n+    await User.bulkCreate([\n+      { uniqueName: 'Peter', secretValue: '42' },\n+      { uniqueName: 'Paul', secretValue: '23' },\n+    ]);\n+\n+    const statements: string[] = [];\n+    const result = await User.bulkCreate(\n+      [\n+        { uniqueName: 'Peter', secretValue: 'dup' },\n+        { uniqueName: 'Michael', secretValue: '26' },\n+        { uniqueName: 'Paul', secretValue: 'dup' },\n+        { uniqueName: 'Anna', secretValue: '27' },\n+      ],\n+      { ignoreDuplicates: true, logging: sql => statements.push(sql) },\n+    );\n+\n+    expect(statements).to.have.length(1);\n+    expect(result.map(user => user.uniqueName)).to.deep.equal(['Peter', 'Michael', 'Paul', 'Anna']);\n+\n+    const rows = await User.findAll({ order: ['id'], raw: true });\n+    expect(rows.map(row => row.uniqueName)).to.deep.equal(['Peter', 'Paul', 'Michael', 'Anna']);\n+\n+    const byName = new Map(rows.map(row => [row.uniqueName, row]));\n+    for (const inserted of [result[1], result[3]]) {\n+      expect(inserted.isNewRecord).to.equal(false);\n+      expect(inserted.id).to.equal(byName.get(inserted.uniqueName)!.id);\n+      expect(inserted.secretValue).to.equal(byName.get(inserted.uniqueName)!.secretValue);\n+      expect(inserted.changed()).to.equal(false);\n+    }\n+\n+    for (const skipped of [result[0], result[2]]) {\n+      expect(skipped.isNewRecord).to.equal(true);\n+      expect(skipped.id).to.equal(null);\n+      expect(skipped.secretValue).to.equal('dup');\n+      // nothing was stored for it, so it carries no generated timestamps either\n+      expect(skipped.createdAt).to.equal(undefined);\n+      expect(skipped.updatedAt).to.equal(undefined);\n+    }\n+  });\n+\n+  it('does not report any record as persisted when every row is skipped', async () => {\n+    const { User } = vars;\n+    await User.bulkCreate([{ uniqueName: 'Peter' }, { uniqueName: 'Paul' }]);\n+\n+    const result = await User.bulkCreate([{ uniqueName: 'Peter' }, { uniqueName: 'Paul' }], {\n+      ignoreDuplicates: true,\n+    });\n+\n+    expect(result.map(user => user.uniqueName)).to.deep.equal(['Peter', 'Paul']);\n+    for (const user of result) {\n+      expect(user.isNewRecord).to.equal(true);\n+      expect(user.id).to.equal(null);\n+    }\n+\n+    expect(await User.count()).to.equal(2);\n+  });\n+\n+  it('does not store the children of a skipped record under another record', async () => {\n+    const { User, Task } = vars;\n+    await User.bulkCreate([{ uniqueName: 'Peter' }]);\n+\n+    const records = [\n+      { uniqueName: 'Peter', secretValue: null, tasks: [{ title: 'peter-task' }] },\n+      { uniqueName: 'Michael', secretValue: null, tasks: [{ title: 'michael-task' }] },\n+    ];\n+    const result = await User.bulkCreate(records, {\n+      ignoreDuplicates: true,\n+      include: [{ model: Task, as: 'tasks' }],\n+    });\n+\n+    const michael = await User.findOne({ where: { uniqueName: 'Michael' }, rejectOnEmpty: true });\n+    expect(result[1].id).to.equal(michael.id);\n+\n+    const tasks = await Task.findAll({ order: ['id'], raw: true });\n+    expect(tasks).to.have.length(1);\n+    expect(tasks[0].title).to.equal('michael-task');\n+    expect(tasks[0].userId).to.equal(michael.id);\n+\n+    expect(result[0].isNewRecord).to.equal(true);\n+    expect(result[0].tasks![0].isNewRecord).to.equal(true);\n+  });\n+\n+  it('matches on a composite unique key', async () => {\n+    const { Seat } = vars;\n+    await Seat.bulkCreate([{ room: 'A', number: 1, label: 'taken' }]);\n+\n+    const result = await Seat.bulkCreate(\n+      [\n+        { room: 'A', number: 1, label: 'dup' },\n+        { room: 'A', number: 2, label: 'new' },\n+        { room: 'B', number: 1, label: 'new' },\n+      ],\n+      { ignoreDuplicates: true },\n+    );\n+\n+    const rows = await Seat.findAll({ order: ['id'], raw: true });\n+    expect(rows).to.have.length(3);\n+    expect(result[0].isNewRecord).to.equal(true);\n+    expect(result[0].label).to.equal('dup');\n+    expect(result[1].id).to.equal(rows[1].id);\n+    expect(result[1].room + result[1].number).to.equal('A2');\n+    expect(result[2].id).to.equal(rows[2].id);\n+    expect(result[2].room + result[2].number).to.equal('B1');\n+  });\n+\n+  it('matches on a caller-supplied primary key', async () => {\n+    const { Code } = vars;\n+    await Code.bulkCreate([{ code: 'x', label: 'taken' }]);\n+\n+    const result = await Code.bulkCreate(\n+      [\n+        { code: 'x', label: 'dup' },\n+        { code: 'y', label: 'new' },\n+      ],\n+      { ignoreDuplicates: true },\n+    );\n+\n+    expect(result[0].isNewRecord).to.equal(true);\n+    expect(result[0].label).to.equal('dup');\n+    expect(result[1].isNewRecord).to.equal(false);\n+    expect(result[1].label).to.equal('new');\n+    expect((await Code.findByPk('x', { rejectOnEmpty: true })).label).to.equal('taken');\n+  });\n+\n+  it('keeps the rows aligned when the returning list omits the key columns', async () => {\n+    const { User } = vars;\n+    await User.bulkCreate([{ uniqueName: 'Peter', secretValue: '42' }]);\n+\n+    const result = await User.bulkCreate(\n+      [\n+        { uniqueName: 'Peter', secretValue: 'dup' },\n+        { uniqueName: 'Michael', secretValue: '26' },\n+      ],\n+      { ignoreDuplicates: true, returning: ['id'] },\n+    );\n+\n+    const michael = await User.findOne({ where: { uniqueName: 'Michael' }, rejectOnEmpty: true });\n+    expect(result[0].isNewRecord).to.equal(true);\n+    expect(result[0].id).to.equal(null);\n+    expect(result[1].id).to.equal(michael.id);\n+    expect(result[1].isNewRecord).to.equal(false);\n+  });\n+});\n"
    },
    "isError": false,
    "subscores": [
      {
        "name": "aligned_inserted",
        "weight": 0.1875,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "CRITERION aligned_inserted: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh aligned_inserted'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 900
          }
        }
      },
      {
        "name": "skipped_honest",
        "weight": 0.125,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "CRITERION skipped_honest: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh skipped_honest'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 900
          }
        }
      },
      {
        "name": "expression_columns",
        "weight": 0.0625,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "CRITERION expression_columns: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh expression_columns'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 900
          }
        }
      },
      {
        "name": "skipped_timestamps",
        "weight": 0.0625,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "CRITERION skipped_timestamps: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh skipped_timestamps'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 900
          }
        }
      },
      {
        "name": "returning_restricted",
        "weight": 0.125,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "CRITERION returning_restricted: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh returning_restricted'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 900
          }
        }
      },
      {
        "name": "date_key",
        "weight": 0.0625,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "CRITERION date_key: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh date_key'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 900
          }
        }
      },
      {
        "name": "children_attachment",
        "weight": 0.0625,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "CRITERION children_attachment: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh children_attachment'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 900
          }
        }
      },
      {
        "name": "key_variants",
        "weight": 0.0625,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "CRITERION key_variants: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh key_variants'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 900
          }
        }
      },
      {
        "name": "untouched_paths",
        "weight": 0.0625,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "CRITERION untouched_paths: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh untouched_paths'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 900
          }
        }
      },
      {
        "name": "no_regression",
        "weight": 0.0625,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "CRITERION no_regression: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh no_regression'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 1800
          }
        }
      },
      {
        "name": "test_quality",
        "weight": 0.0625,
        "value": 1.0,
        "children": null,
        "info": {
          "exit_code": 0,
          "stdout": "  [grader] agent test files: integration/model/bulk-create/ignore-duplicates.test.ts\nCRITERION test_quality: PASS\n",
          "stderr": "",
          "_parameters": {
            "command": "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs env HOME=/tmp/agent-home bash -lc 'bash /hud/grader/run_grading.sh test_quality'",
            "cwd": "/workspace/repo",
            "timeout_seconds": 900
          }
        }
      },
      {
        "name": "maintainer_review",
        "weight": 0.0625,
        "value": 1.0,
        "children": [
          {
            "name": "The diff changes the behaviour of the bulk-create path in packages/core/src/model.js (a diff that adds only comments, whitespace or formatting does not) and stays on-ticket: changes are confined to that path and closely related code, plus its tests. No unrelated drive-by edits, and no edits to pre-existing test files.",
            "weight": 1.0,
            "value": 1.0,
            "children": null,
            "info": {
              "reason": "The diff makes substantive behavioural changes to the bulkCreate path in packages/core/src/model.js (matching returned rows by identity keys, tracking skipped instances, skipping children of skipped parents, dropping generated timestamps). The changes are confined to bulkCreate and two new private helper methods that it uses. The only test change is a new file, ignore-duplicates.test.ts, and no pre-existing test files are edited. There are no unrelated drive-by edits."
            }
          },
          {
            "name": "Judge only the lines the diff adds to packages/core/src/model.js; ignore test files and every other file. The ticket requires the behaviour to hold \"whatever the model definition\". Check this mechanically: list every quoted string literal (single, double or backtick quotes) in those added lines. Answer No only if one of those literals is exactly equal to one of these names used by the ticket's or the tests' models: 'id', 'uniqueName', 'secretValue', 'createdAt', 'updatedAt', 'deletedAt', 'room', 'number', 'code', 'label', 'title', 'userId', 'users', 'User', 'Task', 'Seat', 'Code'. Every other literal counts as Yes, for example type names in typeof checks such as 'string' or 'object', encodings such as 'hex', separators such as '\\0' or ':', option names such as 'ignoreDuplicates' or 'returning', dialect names, error messages, and keys the code makes up for its own bookkeeping. Reading names through variables, loops, attribute.field, primaryKeys, rawAttributes, getIndexes() or other model metadata is not a quoted literal and counts as Yes. If no added line contains one of the listed names as a whole quoted literal, answer Yes. Do not mark this No for weaknesses in the matching logic itself; other checks grade behaviour.",
            "weight": 1.0,
            "value": 1.0,
            "children": null,
            "info": {
              "reason": "The string literals in the added model.js lines are 'string', 'hex', '\\0', and two template literals (the `${k}:...` signature and the error messages). None of them exactly equals a listed model-specific name such as 'id', 'uniqueName', 'room' or 'User'. Key names come from metadata (primaryKeys, attribute.field, getIndexes(), index.fields), not from quoted literals."
            }
          },
          {
            "name": "At least one test file added by the diff calls bulkCreate with ignoreDuplicates: true on a batch in which at least one record conflicts with a row already in the table, and asserts on the instances returned by that same call: for an inserted record, isNewRecord is false and its primary key equals the key of its row in the table; for a skipped record, isNewRecord is true. Assertions made only on the table contents (count, findAll) do not meet this criterion.",
            "weight": 1.0,
            "value": 1.0,
            "children": null,
            "info": {
              "reason": "The first integration test calls bulkCreate with ignoreDuplicates on a batch with conflicting records and asserts on the returned instances: inserted ones have isNewRecord false and id equal to the table row's id (looked up by uniqueName), and skipped ones have isNewRecord true."
            }
          }
        ],
        "info": {
          "model": "anthropic/claude-sonnet-5.5",
          "_parameters": {
            "answer": "(answer elided; 18224 chars)",
            "criteria": [
              "The diff changes the behaviour of the bulk-create path in packages/core/src/model.js (a diff that adds only comments, whitespace or formatting does not) and stays on-ticket: changes are confined to that path and closely related code, plus its tests. No unrelated drive-by edits, and no edits to pre-existing test files.",
              "Judge only the lines the diff adds to packages/core/src/model.js; ignore test files and every other file. The ticket requires the behaviour to hold \"whatever the model definition\". Check this mechanically: list every quoted string literal (single, double or backtick quotes) in those added lines. Answer No only if one of those literals is exactly equal to one of these names used by the ticket's or the tests' models: 'id', 'uniqueName', 'secretValue', 'createdAt', 'updatedAt', 'deletedAt', 'room', 'number', 'code', 'label', 'title', 'userId', 'users', 'User', 'Task', 'Seat', 'Code'. Every other literal counts as Yes, for example type names in typeof checks such as 'string' or 'object', encodings such as 'hex', separators such as '\\0' or ':', option names such as 'ignoreDuplicates' or 'returning', dialect names, error messages, and keys the code makes up for its own bookkeeping. Reading names through variables, loops, attribute.field, primaryKeys, rawAttributes, getIndexes() or other model metadata is not a quoted literal and counts as Yes. If no added line contains one of the listed names as a whole quoted literal, answer Yes. Do not mark this No for weaknesses in the matching logic itself; other checks grade behaviour.",
              "At least one test file added by the diff calls bulkCreate with ignoreDuplicates: true on a batch in which at least one record conflicts with a row already in the table, and asserts on the instances returned by that same call: for an inserted record, isNewRecord is false and its primary key equals the key of its row in the table; for a skipped record, isNewRecord is true. Assertions made only on the table contents (count, findAll) do not meet this criterion."
            ],
            "question": "(question elided; 441 chars)",
            "model": "anthropic/claude-sonnet-5.5"
          }
        }
      }
    ]
  },
  "judge": {
    "model": "anthropic/claude-sonnet-5.5",
    "endpoint": "openrouter.ai"
  }
}