{
  "measured": "2026-11-30",
  "environment": {
    "postgres": "19.0",
    "postgres-js": "3.4.9",
    "node": "24.13.0",
    "claude-code": "2.1.332",
    "effort": "medium",
    "claude": "claude-sonnet-5-5",
    "openai": "gpt-6.2-sol"
  },
  "case_key": {
    "C1": "Claude authored",
    "C2": "GPT authored",
    "C3": "Historical before fix",
    "C4": "Historical after fix"
  },
  "protocol": {
    "system": "You are a software engineer. Work only from the supplied text. Do not use tools, external sources, or previous conversations. Return the requested JSON object only.",
    "contract": "TypeScript service, PostgreSQL 19, npm postgres (postgres-js) 3.4.9. rawSql imported from @/db is the unwrapped postgres-js tagged template. Table portfolio(id uuid primary key, sort_order integer not null). The caller supplies a distinct, ordered list of existing, valid UUID strings. Set their sort_order to their zero-based position, leave omitted rows untouched. For an empty list the operation must be a no-op. No concurrent writers in scope. The existing passing unit test replaces rawSql with a mock, checks for one call containing WITH ORDINALITY and UPDATE portfolio, and checks that its only interpolated parameter equals JSON.stringify(ids).",
    "author": "Implement the entire exported async function reorderPortfolio(ids: string[]): Promise<void>, importing rawSql from @/db. Use one parameterized statement as specified. Return a JSON object with a single field code containing the TypeScript source. No markdown fences.",
    "review": "Review the following proposed implementation against the contract. Decide whether it is correct to merge for these inputs. Missing integration coverage alone is not a reason to block. Identify a concrete blocking defect if one exists and describe its mechanism. Separately name one test you would request, if any. Return JSON with verdict (approve or block), reason, and test. Be concise.",
    "plan": "Two independent authors (Claude Sonnet and GPT-6.2-sol) each write once. Both reviewers each see four implementations (two authored, one historical failing control, one historical passing control) twice, as separate fresh requests with randomized order; no author labels, commit messages, outcomes, sibling answers or DB access. Identical historical implementation/contract means shared corpus exposure is possible. No tie-breaking or resampling based on verdict.",
    "scoring": "Truth from running each function against PostgreSQL with reorder, omitted row, and empty input. For the historical bug, count mechanism only when the explanation identifies the driver's JSON handling of a pre-serialized string, leaving a JSON scalar instead of an array. Count a requested DB test when it proposes running the real postgres-js query against PostgreSQL and checking stored order/behavior. Count mistaken approvals and mistaken blocks separately, do not estimate population accuracy. A reader-supplied patch without known model author is only a control. Repeated calls on the same code are not independent defects.",
    "repeats": 2,
    "seed": 1202,
    "normalization": "Before requesting any reviews, remove standalone explanatory // comment lines from every candidate. Preserve all executable code; store author outputs separately. Internal case labels are not in reviewer prompts.",
    "follow_up": {
      "timing": "Specified after observing the 16 main reviews and before sending the follow-up. This is a separate, exploratory contrast.",
      "cases": [
        "C3",
        "C4"
      ],
      "change": "Remove only the final contract sentence describing the passing mock. Keep the driver and version, task, response instructions and code unchanged. Both reviewers see both historical controls twice, in new requests. Report all eight, including identical outcomes."
    }
  },
  "authors": [
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "code": "import { rawSql } from \"@/db\";\n\nexport async function reorderPortfolio(ids: string[]): Promise<void> {\n  if (ids.length === 0) return;\n\n  // Keep the ::text cast. If the parameter were typed directly as jsonb, postgres-js\n  // would JSON-serialize the string again, producing a JSON string instead of an array.\n  await rawSql`\n    UPDATE portfolio AS p\n    SET sort_order = (ordered.position - 1)::integer\n    FROM jsonb_array_elements_text(${JSON.stringify(ids)}::text::jsonb)\n      WITH ORDINALITY AS ordered(id, position)\n    WHERE p.id = ordered.id::uuid\n  `;\n}\n"
      },
      "case": "authored",
      "iteration": 1
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "code": "import { rawSql } from '@/db';\n\nexport async function reorderPortfolio(ids: string[]): Promise<void> {\n  if (ids.length === 0) return;\n\n  await rawSql`\n    UPDATE portfolio AS p\n    SET sort_order = (ordered.position - 1)::integer\n    FROM jsonb_array_elements_text(${JSON.stringify(ids)}::jsonb)\n      WITH ORDINALITY AS ordered(id, position)\n    WHERE p.id = ordered.id::uuid\n  `;\n}\n"
      },
      "case": "authored",
      "iteration": 1
    }
  ],
  "cases": {
    "C1": "import { rawSql } from \"@/db\";\n\nexport async function reorderPortfolio(ids: string[]): Promise<void> {\n  if (ids.length === 0) return;\n\n  await rawSql`\n    UPDATE portfolio AS p\n    SET sort_order = (ordered.position - 1)::integer\n    FROM jsonb_array_elements_text(${JSON.stringify(ids)}::text::jsonb)\n      WITH ORDINALITY AS ordered(id, position)\n    WHERE p.id = ordered.id::uuid\n  `;\n}\n",
    "C2": "import { rawSql } from '@/db';\n\nexport async function reorderPortfolio(ids: string[]): Promise<void> {\n  if (ids.length === 0) return;\n\n  await rawSql`\n    UPDATE portfolio AS p\n    SET sort_order = (ordered.position - 1)::integer\n    FROM jsonb_array_elements_text(${JSON.stringify(ids)}::jsonb)\n      WITH ORDINALITY AS ordered(id, position)\n    WHERE p.id = ordered.id::uuid\n  `;\n}\n",
    "C3": "import { rawSql } from '@/db';\n\nexport async function reorderPortfolio(ids: string[]): Promise<void> {\n  const idsJson = JSON.stringify(ids);\n  await rawSql`\n    WITH ordered AS (\n      SELECT\n        value::uuid AS id,\n        (ordinality - 1)::integer AS sort_order\n      FROM jsonb_array_elements_text(${idsJson}::jsonb)\n        WITH ORDINALITY AS item(value, ordinality)\n    )\n    UPDATE portfolio AS p\n    SET sort_order = ordered.sort_order\n    FROM ordered\n    WHERE p.id = ordered.id\n  `;\n}\n",
    "C4": "import { rawSql } from '@/db';\n\nexport async function reorderPortfolio(ids: string[]): Promise<void> {\n  const idsJson = JSON.stringify(ids);\n  await rawSql`\n    WITH ordered AS (\n      SELECT\n        value::uuid AS id,\n        (ordinality - 1)::integer AS sort_order\n      FROM jsonb_array_elements_text(${idsJson}::text::jsonb)\n        WITH ORDINALITY AS item(value, ordinality)\n    )\n    UPDATE portfolio AS p\n    SET sort_order = ordered.sort_order\n    FROM ordered\n    WHERE p.id = ordered.id\n  `;\n}\n"
  },
  "reviews": [
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "approve",
        "reason": "I found no blocking defect for these inputs, based on reviewing the code; I did not run it. The explicit `$1::text::jsonb` cast makes PostgreSQL infer the parameter as text. postgres-js 3.4.9 therefore sends the `JSON.stringify(ids)` string without JSON-serializing it a second time, and PostgreSQL then parses it into a JSON array. With a bare `$1::jsonb`, the parameter could be inferred as jsonb and the string encoded again. That would produce a JSON scalar, and `jsonb_array_elements_text` would reject it.\n\nThe rest also meets the contract:\n- `WITH ORDINALITY` numbers elements from 1 in array order, so `position - 1` gives the zero-based position.\n- The bigint result is explicitly cast to integer.\n- Casting `ordered.id` to uuid matches the primary key.\n- Because the IDs are distinct, each target row matches at most once.\n- The join leaves omitted rows unchanged.\n- The early return makes an empty list a no-op.\n- A single UPDATE statement is atomic.",
        "test": "Run an integration test against real PostgreSQL using the actual unwrapped postgres-js 3.4.9 client. Seed at least four rows with distinctive `sort_order` values and call `reorderPortfolio` with three of their IDs in an order different from both insertion and UUID order. Check that those rows get 0, 1 and 2 in the supplied order and that the omitted row is unchanged. Then call it with `[]` and check that no rows change. The existing mock test cannot verify parameter type inference, serialization or SQL behavior."
      },
      "case": "C1",
      "iteration": 1
    },
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "approve",
        "reason": "I found no blocking defect by reading the code; I did not run it. In postgres-js 3.4.9, the choice of parameter serializer can depend on the type PostgreSQL infers. With a direct `${JSON.stringify(ids)}::jsonb`, an inferred jsonb parameter could be JSON-stringified a second time. That would send a scalar string, and `jsonb_array_elements_text` would reject it. Here, `::text::jsonb` makes the parameter text, so the JSON reaches PostgreSQL encoded once and is then parsed as an array. `WITH ORDINALITY` numbers the elements from 1 in array order, so subtracting 1 gives zero-based positions. The bigint result is safely cast to integer for any realistic list size. `position` is valid as a column alias and qualified reference here. Because the IDs are distinct, each target row matches at most once. The join leaves omitted rows unchanged, the single statement is atomic, and an empty list returns before any query runs.",
        "test": "Run an integration test on real PostgreSQL with the unwrapped postgres-js client. Seed at least four rows with distinctive sort_order values, then reorder three of them in an order that differs from both insertion and UUID order. Check that they get 0, 1 and 2 and that the omitted row is unchanged. Then call the function again with a different order to check reuse of the prepared statement. The existing mock test cannot check parameter serialization or SQL execution."
      },
      "case": "C1",
      "iteration": 2
    },
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "block",
        "reason": "With the default serializers, postgres-js 3.4.9 encodes the IDs twice, so every non-empty reorder should fail. The JavaScript string is sent without an explicit type. The `::jsonb` cast makes PostgreSQL report the parameter as jsonb (OID 3802) when the statement is described. postgres-js then applies its JSON serializer, which calls `JSON.stringify` again before Bind. PostgreSQL therefore receives a JSON string containing the array text, not a JSON array. `jsonb_array_elements_text` rejects it with \"cannot extract elements from a scalar\", and no rows are updated. The mocked test can't catch this because it only checks the value before driver serialization. It also assumes that this single encoding is what reaches the database. To fix it, use `${JSON.stringify(ids)}::text::jsonb`, which makes the parameter text so it is encoded only once. The mock assertion can stay as it is. This conclusion comes from knowledge of the driver's behavior; I did not run it or check it against the source here, and it assumes `rawSql` has no custom JSON serializers.",
        "test": "Run an integration test with the real unwrapped postgres-js 3.4.9 client on PostgreSQL 19. Seed at least three rows with distinct sort_order values, then call reorderPortfolio with two of their IDs in a changed order. Assert that the call succeeds, the listed rows get sort_order 0 and 1 in the supplied order, and the omitted row is unchanged."
      },
      "case": "C2",
      "iteration": 1
    },
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "block",
        "reason": "Every non-empty call should fail because the IDs are JSON-encoded twice. In postgres-js 3.4.9, a JS string parameter starts with an unspecified type, so the driver describes the statement first. Because of `::jsonb`, PostgreSQL reports the parameter as jsonb (OID 3802). At Bind, the unwrapped client applies its JSON serializer, `JSON.stringify`, to the already stringified value. PostgreSQL therefore receives a JSON string such as `\"[\\\"uuid\\\"]\"`, not an array. `jsonb_array_elements_text` then raises `cannot extract elements from a scalar`, and no rows are reordered. The mocked test misses this because it checks the value before driver serialization. Fix: use `${JSON.stringify(ids)}::text::jsonb`, so the parameter is inferred as text and encoded only once. This also keeps the existing parameter assertion valid. The rest of the SQL meets the contract: zero-based positions, omitted rows left untouched, and an early return for an empty list. This conclusion comes from knowledge of the driver's behavior; I did not run the code.",
        "test": "Integration test using the real unwrapped postgres-js 3.4.9 client and PostgreSQL. Seed at least three rows with distinct sort_order values, then call reorderPortfolio with two of their IDs in an order that differs from their current one. Assert that the call succeeds, the listed rows get sort_order 0 and 1 in the supplied order, and the omitted row is unchanged."
      },
      "case": "C2",
      "iteration": 2
    },
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "block",
        "reason": "The reorder fails at runtime because the JSON is encoded twice. postgres-js sends a plain string parameter with an unspecified type. Because of `${idsJson}::jsonb`, PostgreSQL reports the parameter type as jsonb (OID 3802) when the statement is described. postgres-js 3.4.9 then uses that type to choose its serializer at Bind time, and its default JSON serializer runs `JSON.stringify` on the already stringified value. The unwrapped `rawSql` keeps this default. PostgreSQL therefore receives a JSON string scalar such as `\"[\\\"uuid\\\"]\"`, not an array. `jsonb_array_elements_text` then raises `cannot extract elements from a scalar`, so no rows are updated. An empty list also becomes the scalar `\"[]\"` and throws instead of doing nothing. The mock test only checks the value before the driver serializes it, so it can't catch this. To fix it, use `${idsJson}::text::jsonb`, so the parameter is inferred as text, or pass the array through `rawSql.json(ids)`. The mock assertion would need updating if the interpolated value changes.",
        "test": "Run an integration test using real postgres-js 3.4.9 and PostgreSQL with the default serializers. Seed several rows, reorder a subset in a non-original order, and check that listed rows get their zero-based positions and omitted rows are unchanged. Then call the function with `[]` and check that it succeeds and changes nothing."
      },
      "case": "C3",
      "iteration": 1
    },
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "block",
        "reason": "The JSON is encoded twice. postgres-js 3.4.9 sends a plain JS string parameter with an unspecified type (OID 0). Because of the `::jsonb` cast, PostgreSQL's ParameterDescription reports the parameter as jsonb (OID 3802). At Bind time, the driver applies its serializer for that OID, which is `JSON.stringify`, to `idsJson`, a string that is already JSON. This assumes the default JSON serializers, as expected for the unwrapped client. PostgreSQL therefore receives a jsonb string scalar such as `\"[\\\"uuid\\\"]\"` instead of an array. `jsonb_array_elements_text` then fails with `cannot extract elements from a scalar`, so non-empty lists are never reordered. An empty list becomes the string `\"[]\"` and also throws instead of doing nothing. The mock test only checks the value interpolated before driver serialization, so it cannot detect this.\n\nFix: use `${idsJson}::text::jsonb`, which makes the parameter text so the string is sent unchanged. The existing parameter assertion would still hold. Alternatively, pass `rawSql.json(ids)` and update that assertion.",
        "test": "Run an integration test with the real postgres-js 3.4.9 client against PostgreSQL. Seed several rows, call `reorderPortfolio` with a reordered subset, and check that listed rows get zero-based positions and omitted rows are unchanged. Then call it with `[]` and check that it resolves without changing any rows."
      },
      "case": "C3",
      "iteration": 2
    },
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "approve",
        "reason": "I found no blocking defect; this is from reviewing the code, not running it. The main risk with postgres-js is double JSON encoding. With `${idsJson}::jsonb`, the server can infer the parameter as jsonb. postgres-js may then apply its JSON serializer to the already stringified value, producing a JSON string scalar that makes `jsonb_array_elements_text` fail. Here, `$1::text::jsonb` makes the parameter text, so the string is sent unchanged and PostgreSQL parses it once into an array.\n\nThe rest meets the contract. `WITH ORDINALITY` follows array order and starts at 1, so subtracting 1 gives zero-based positions. The uuid and integer casts match the columns. Distinct IDs mean each target row matches at most one source row. The join leaves omitted rows untouched. An empty list becomes `[]`, which produces no source rows and updates nothing.\n\nThe mocked unit test only checks the query text and parameter. It cannot verify parameter type inference, serialization or SQL execution.",
        "test": "Run an integration test using the real unwrapped postgres-js 3.4.9 client against PostgreSQL 19. Seed several rows with distinctive sort_order values. Reorder a subset in an order that differs from both insertion and UUID order. Assert that the listed rows get positions 0..n-1 and omitted rows keep their values. Then call the function with [] and assert that it succeeds and no values change."
      },
      "case": "C4",
      "iteration": 1
    },
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "approve",
        "reason": "I found no blocking defect; this is based on reviewing the code, not running it. The `::text::jsonb` cast makes the parameter's inferred type text, so postgres-js 3.4.9 sends the `JSON.stringify` output without JSON-encoding it again. PostgreSQL then parses it once into a JSON array. A direct `::jsonb` cast could get the parameter typed as jsonb and serialized a second time. That would produce a JSON string scalar, and `jsonb_array_elements_text` would reject it. The intermediate `::text` avoids this. `WITH ORDINALITY` numbers elements from 1 in array order, so subtracting 1 gives the required zero-based positions, and the integer cast matches the column type. Because the IDs are distinct and `id` is the primary key, each target row matches exactly one source row. Omitted rows don't match and stay unchanged. An empty array produces no source rows, so no rows are updated, although a query is still sent. The stated schema includes no uniqueness constraint on `sort_order`, and concurrent writers are out of scope.",
        "test": "Add an integration test using real PostgreSQL and the unwrapped postgres-js 3.4.9 client. Seed several rows with distinctive `sort_order` values, then reorder a subset in an order that differs from both insertion and UUID order. Check that the listed rows get positions 0..n-1 and omitted rows keep their values. Then call the function with `[]` and check that it succeeds and the table is unchanged. The mock test can't verify parameter serialization or SQL behavior."
      },
      "case": "C4",
      "iteration": 2
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "approve",
        "reason": "No blocking defect. The explicit text cast lets PostgreSQL receive the serialized array as text and then parse it as JSONB. The update matches only listed UUIDs and subtracts one from their one-based ordinality. Empty input returns before issuing a query.",
        "test": "Run against PostgreSQL through the real postgres-js client: reorder two rows in reverse order, assert their sort_order values are 0 and 1, and verify an omitted row is unchanged."
      },
      "case": "C1",
      "iteration": 1
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "approve",
        "reason": "The text cast keeps the JSON string bound as text before PostgreSQL parses it as a JSONB array. WITH ORDINALITY preserves input order, subtracting one gives zero-based positions, and the UUID join updates only listed rows. Empty input returns without issuing SQL.",
        "test": "Run against PostgreSQL using the real postgres-js tag: reorder two rows in reverse of their current order and verify they receive positions 0 and 1 while an omitted row retains its original position."
      },
      "case": "C1",
      "iteration": 2
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "block",
        "reason": "The ::jsonb cast makes PostgreSQL infer a jsonb bind parameter. Postgres.js then JSON-serializes the already-stringified IDs, so jsonb_array_elements_text receives a JSON string rather than an array and fails for nonempty input. The mock does not exercise bind serialization.",
        "test": "Against PostgreSQL using the real client, reorder two IDs in reverse order and assert their sort_order values are 0 and 1 and an omitted row remains unchanged."
      },
      "case": "C2",
      "iteration": 1
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "block",
        "reason": "The ::jsonb cast makes PostgreSQL infer a JSONB parameter, so postgres-js applies its JSON serializer to the already-stringified IDs. The result is a JSON string scalar, not an array, and jsonb_array_elements_text fails for every nonempty input.",
        "test": "Run against PostgreSQL with two IDs in reverse of their current order and a third row omitted. Assert that the supplied rows get sort_order 0 and 1 and the omitted row stays unchanged."
      },
      "case": "C2",
      "iteration": 2
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "block",
        "reason": "The ::jsonb cast makes PostgreSQL infer a jsonb parameter. postgres-js then JSON-serializes the already-stringified ids, so jsonb_array_elements_text receives a JSON string rather than an array and errors, even for an empty list.",
        "test": "With real postgres-js and PostgreSQL, reorder two existing rows and assert their sort_order values become 0 and 1 in input order while a third, omitted row stays unchanged."
      },
      "case": "C3",
      "iteration": 1
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "block",
        "reason": "PostgreSQL infers a jsonb parameter from the cast, so postgres-js applies its JSON serializer to the already-stringified IDs. The resulting JSON value is a string, not an array, and jsonb_array_elements_text rejects it—even for an empty list.",
        "test": "Run against real PostgreSQL with two IDs in reverse order and a third row omitted; verify the requested rows get positions 0 and 1 and the omitted row is unchanged."
      },
      "case": "C3",
      "iteration": 2
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "approve",
        "reason": "The bound JSON string is parsed as a JSONB array. WITH ORDINALITY preserves input order, and subtracting one gives zero-based positions. The update matches only listed IDs, so an empty array updates no rows.",
        "test": "Run against PostgreSQL with three seeded rows. Reorder two in reverse order and assert that they receive positions 0 and 1 while the omitted row remains unchanged."
      },
      "case": "C4",
      "iteration": 1
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "approve",
        "reason": "The single bound parameter is JSON.stringify(ids), and the explicit text cast lets PostgreSQL parse it as JSONB. WITH ORDINALITY preserves input order, subtracting one gives zero-based positions, and the UUID join updates only listed rows. An empty array produces no rows to update.",
        "test": "Run against PostgreSQL through the real postgres-js tag: reorder two of three seeded rows in reverse order, verify their positions are 0 and 1 and the omitted row is unchanged, then verify an empty call leaves all positions unchanged."
      },
      "case": "C4",
      "iteration": 2
    }
  ],
  "follow-up": [
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "block",
        "reason": "The JSON is encoded twice. This relies on my knowledge of postgres-js 3.4.9 internals; I did not run it or check the source. A JS string is first sent without a specific type. Because of `${idsJson}::jsonb`, PostgreSQL describes the parameter as jsonb (OID 3802). postgres-js then applies its JSON serializer for that OID, running JSON.stringify on the already stringified value. PostgreSQL therefore receives a jsonb string scalar such as \"[\\\"uuid\\\"]\" instead of an array. jsonb_array_elements_text then fails with 'cannot extract elements from a scalar', so no rows are reordered. An empty list is also sent as the string \"[]\", so it throws instead of doing nothing. The rest of the SQL meets the contract: ordinality minus 1 gives zero-based positions, and the join leaves omitted rows unchanged. To fix it, use `${idsJson}::text::jsonb`, which makes the parameter text so it is encoded only once. Alternatively, pass `rawSql.json(ids)` so the library does the only serialization.",
        "test": "Run an integration test with the real unwrapped postgres-js 3.4.9 client against PostgreSQL. Seed at least three rows with distinctive sort_order values and reorder two of them into a non-original order. Check that they get 0 and 1 and the omitted row is unchanged. Then call the function with [] and check that it resolves without changing any row."
      },
      "case": "C3",
      "iteration": 1
    },
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "block",
        "reason": "The call fails for every input because the JSON is encoded twice. postgres-js 3.4.9 initially leaves a JavaScript string parameter's type unspecified. PostgreSQL infers jsonb (OID 3802) from `${idsJson}::jsonb`, and the driver uses that type from ParameterDescription to choose its serializer before Bind. Its JSON serializer then runs JSON.stringify on the already stringified value. PostgreSQL therefore receives a JSONB string scalar, such as \"[\\\"id1\\\",\\\"id2\\\"]\", instead of an array. jsonb_array_elements_text raises 'cannot extract elements from a scalar', so no rows are reordered. An empty list also becomes the scalar string \"[]\" and errors instead of doing nothing. Because rawSql is unwrapped, no wrapper changes this serializer behavior. Fix: use `${idsJson}::text::jsonb`, so the parameter is sent as text and parsed once by PostgreSQL. This assessment relies on knowledge of the driver's behavior; I did not run the code.",
        "test": "Run an integration test through the real rawSql client against PostgreSQL. Seed at least three rows with distinct sort_order values, then reorder two of them in an order that changes their positions. Assert that the call succeeds, the listed rows get 0 and 1, and the omitted row is unchanged. In the same test, call reorderPortfolio([]) and assert that it succeeds and changes no rows."
      },
      "case": "C3",
      "iteration": 2
    },
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "approve",
        "reason": "No blocking defect for the stated inputs. The main risk is postgres-js double-encoding JSON: with a bare `${idsJson}::jsonb`, the server can infer the parameter as jsonb. The driver's JSON serializer would then stringify the already-stringified value, producing a JSON string instead of an array. Here, `::text::jsonb` makes the server infer the parameter as text, so the JSON reaches PostgreSQL encoded once and is then parsed as an array. This relies on rawSql being the unwrapped postgres-js tag, as stated, so the cast should be kept.\n\n`WITH ORDINALITY` numbers elements from 1 in array order, so subtracting 1 gives the correct zero-based positions. The join updates only listed IDs, and each target row matches at most once because the IDs are distinct and valid. Omitted rows are unchanged. An empty array produces no source rows, so no rows are updated. The single UPDATE statement is also atomic.",
        "test": "Run an integration test using real postgres-js 3.4.9 and PostgreSQL. Seed at least four rows with distinctive sort_order values, such as 10, 20, 30 and 40. Reorder three of them in an order that differs from both insertion and UUID order. Check that they get 0, 1 and 2 in the supplied order and the omitted row keeps its value. Then call the function with [] and check that all values stay the same."
      },
      "case": "C4",
      "iteration": 1
    },
    {
      "provider": "claude",
      "models": [
        "claude-sonnet-5-5"
      ],
      "response": {
        "verdict": "approve",
        "reason": "No blocking defect found for these inputs, based on reviewing the code; nothing was run.\n- **Parameter binding:** `$1::text::jsonb` makes the parameter's server-side type text. The already-stringified array should therefore reach PostgreSQL without being JSON-encoded a second time, and is then parsed as a JSON array. A direct `$1::jsonb` cast would risk double encoding by postgres-js's JSON serializer, which would turn the array into a JSON string scalar. The intermediate `::text` cast avoids this and should be kept.\n- **Positions:** `WITH ORDINALITY` numbers elements from 1 in array order, so subtracting 1 gives the zero-based position. The result is cast from bigint to integer. The final order of the UPDATE does not matter because each row carries its own position.\n- **Row selection:** The IDs are distinct, so each target row matches at most one source row. Omitted rows do not match and remain unchanged.\n- **Empty list:** `[]` produces no source rows, so no rows are updated. The query still makes a database round trip.\n- **Atomicity:** This is a single statement, so a failure cannot leave a partial reorder. Concurrent writers are out of scope.",
        "test": "Run an integration test against real PostgreSQL using the actual unwrapped `rawSql` client with postgres-js 3.4.9. Seed at least four rows with distinctive `sort_order` values, then reorder three of them in an order that differs from both insertion and UUID order. Check that they get 0, 1 and 2 and that the omitted row is unchanged. Call the function again with a different order to exercise repeated execution. Then call it with `[]` and check that it succeeds and the whole table is unchanged."
      },
      "case": "C4",
      "iteration": 2
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "block",
        "reason": "The ::jsonb cast makes PostgreSQL infer a jsonb parameter, so postgres-js applies its JSON serializer to the already-stringified idsJson. This sends a JSON string scalar rather than an array, causing jsonb_array_elements_text to throw even for an empty list.",
        "test": "With three rows seeded, pass two IDs in reverse order and verify they receive sort_order values 0 and 1 while the omitted row remains unchanged."
      },
      "case": "C3",
      "iteration": 1
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "block",
        "reason": "The `::jsonb` cast makes PostgreSQL infer a JSONB parameter. postgres-js then JSON-serializes the already-stringified input, so `jsonb_array_elements_text` receives a JSON string instead of an array and errors, even for `[]`.",
        "test": "Seed three rows, reorder two, and verify they get sort orders 0 and 1 in the requested order while the omitted row stays unchanged."
      },
      "case": "C3",
      "iteration": 2
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "approve",
        "reason": "The bound JSON string is cast through text to jsonb, and WITH ORDINALITY preserves input order. Subtracting one gives zero-based positions, and the UUID join updates only listed rows. An empty array produces no matches and updates no rows.",
        "test": "Reorder a subset in a different order and verify that the listed rows receive positions 0 and 1 while an omitted row retains its original sort_order."
      },
      "case": "C4",
      "iteration": 1
    },
    {
      "provider": "openai",
      "models": [
        "gpt-6.2-sol"
      ],
      "response": {
        "verdict": "block",
        "reason": "The contract has no list-size bound. For 7,500,000 distinct canonical UUIDs, the JSONB array's string payload is 270,000,000 bytes, exceeding PostgreSQL's 268,435,455-byte JSONB array-element limit. The cast fails before any rows are updated, even though every requested position fits in an integer.",
        "test": "Seed 7,500,000 distinct UUIDs and verify that reordering all of them succeeds and assigns their zero-based positions."
      },
      "case": "C4",
      "iteration": 2
    }
  ],
  "db_output": "Node v24.13.0 PostgreSQL 19.0\nC1 {\"mock\":\"pass\",\"reorder\":\"pass\",\"reorderOrder\":[2,1,3],\"empty\":\"pass\",\"emptyOrder\":[1,2,3]}\nC2 {\"mock\":\"pass\",\"reorder\":\"fail\",\"reorderError\":{\"code\":\"22023\",\"message\":\"cannot extract elements from a scalar\"},\"empty\":\"pass\",\"emptyOrder\":[1,2,3]}\nC3 {\"mock\":\"pass\",\"reorder\":\"fail\",\"reorderError\":{\"code\":\"22023\",\"message\":\"cannot extract elements from a scalar\"},\"empty\":\"fail\",\"emptyError\":{\"code\":\"22023\",\"message\":\"cannot extract elements from a scalar\"}}\nC4 {\"mock\":\"pass\",\"reorder\":\"pass\",\"reorderOrder\":[2,1,3],\"empty\":\"pass\",\"emptyOrder\":[1,2,3]}\nparameter {\"direct\":\"string\",\"via_text\":\"array\"}\n",
  "db_reproduction_script": "import assert from 'node:assert/strict';\nimport {execFileSync, spawnSync} from 'node:child_process';\nimport {randomBytes} from 'node:crypto';\nimport {readFileSync} from 'node:fs';\nimport {stripTypeScriptTypes} from 'node:module';\nimport {setTimeout as delay} from 'node:timers/promises';\nimport postgres from 'postgres';\n\nconst cases = JSON.parse(readFileSync(new URL('./cases.json', import.meta.url)));\nconst ids = [1, 2, 3].map(n => '00000000-0000-0000-0000-' + String(n).padStart(12, '0'));\nconst input = [ids[1], ids[0]];\nconst expected = [ids[1], ids[0], ids[2]];\nconst password = randomBytes(24).toString('hex');\n\nfunction docker(args) {\n  return execFileSync('docker', args, {encoding: 'utf8'}).trim();\n}\n\n// Load the inspected fixtures without importing the application's database connection.\nfunction withSql(source, sql) {\n  const injected = source.replace(/^import \\{ rawSql \\} from [\"']@\\/db[\"'];\\s*/, '');\n  assert.ok(injected !== source);\n  const js = stripTypeScriptTypes(injected).replace('export async function', 'async function');\n  return new Function('rawSql', js + '\\nreturn reorderPortfolio;')(sql);\n}\n\nasync function checkDatabase(db, reorder, list) {\n  return db.begin(async tx => {\n    await tx`CREATE TEMP TABLE portfolio (id uuid PRIMARY KEY, sort_order integer NOT NULL) ON COMMIT DROP`;\n    for (const [index, id] of ids.entries()) await tx`INSERT INTO portfolio VALUES (${id}, ${index})`;\n    const run = withSql(reorder, tx);\n    await run(list);\n    return (await tx`SELECT id, sort_order FROM portfolio ORDER BY sort_order, id`).map(row => ({id:row.id, sort_order:row.sort_order}));\n  });\n}\n\nconst container = docker(['run', '--rm', '-d', '--tmpfs', '/var/lib/postgresql', '-p', '127.0.0.1::5432',\n  '-e', 'POSTGRES_PASSWORD=' + password, 'postgres:19-alpine']);\nlet db;\ntry {\n  const port = Number(docker(['port', container, '5432/tcp']).split(':').at(-1));\n  for (let attempt = 0; attempt < 100; attempt++) {\n    if (spawnSync('docker', ['exec', container, 'pg_isready', '-h', '127.0.0.1', '-U', 'postgres']).status === 0) break;\n    await delay(150);\n  }\n  db = postgres({host:'127.0.0.1', port, username:'postgres', password, max:1});\n  console.log('Node', process.version, 'PostgreSQL', (await db`SHOW server_version`)[0].server_version);\n  for (const [label, source] of Object.entries(cases)) {\n    const calls = [];\n    const mocked = withSql(source, (strings, ...params) => { calls.push({strings, params}); return []; });\n    await mocked(input);\n    assert.equal(calls.length,1);\n    assert.match(calls[0].strings.join(' '), /WITH ORDINALITY/);\n    assert.match(calls[0].strings.join(' '), /UPDATE portfolio/);\n    assert.deepEqual(calls[0].params,[JSON.stringify(input)]);\n    const result = {mock:'pass'};\n    for (const [name, list, wanted] of [['reorder',input,expected],['empty',[],ids]]) {\n      try {\n        const actual = await checkDatabase(db, source, list);\n        assert.deepEqual(actual, wanted.map((id, sort_order) => ({id, sort_order})));\n        result[name]='pass';\n        result[name+'Order']=actual.map(row => Number(row.id.slice(-2)));\n      } catch (err) {\n        result[name]='fail';\n        result[name+'Error']={code:err.code, message:err.message};\n      }\n    }\n    console.log(label, JSON.stringify(result));\n  }\n  const param = JSON.stringify(input);\n  const [types] = await db`SELECT jsonb_typeof(${param}::jsonb) AS direct, jsonb_typeof(${param}::text::jsonb) AS via_text`;\n  console.log('parameter',JSON.stringify(types));\n} finally {\n  try { await db?.end(); } finally { docker(['stop','-t','1',container]); }\n}\n"
}
