Skip to content

test(core): plugin-storage numeric filters/order compare lexically on Postgres - #2150

Closed
vedanshujain wants to merge 1 commit into
emdash-cms:mainfrom
vedanshujain:test/plugin-storage-postgres-numeric-regression
Closed

vedanshujain wants to merge 1 commit into
emdash-cms:mainfrom
vedanshujain:test/plugin-storage-postgres-numeric-regression

Conversation

@vedanshujain

@vedanshujain vedanshujain commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Draft — failing test that reproduces a live bug. Opening this as a runnable repro to confirm the diagnosis before proposing a fix. The Postgres assertions fail on main by design — that is the bug — so the pnpm test checkbox below is intentionally left unchecked. SQLite passes.

This adds failing tests that will be fixed by #2152

Plugin storage still compares numeric field values lexically on Postgres. _plugin_storage.data is a plain text column. #1898 (fixing #920) added the (data)::jsonb->>'field' cast, which correctly resolved the operator does not exist: text ->> unknown parse error and the boolean/equality filters — but ->> still returns text, and the query / count / order paths compare that text directly. So a numeric guard is evaluated lexically:

'9' >= '10'   →  TRUE   (lexical)     9 >= 10   →  false (numeric)

The user-visible consequences are a silent over-count / oversell and wrong ordering.

Reproduction — this PR adds a dialect-parametric integration suite (via the existing describeEachDialect harness) at packages/core/tests/integration/plugins/storage-postgres-numeric-regression.test.ts. It seeds stock values 9 / 10 / 100 (chosen so lexical and numeric order disagree):

Case Assertion SQLite Postgres (main)
(a) query({ where: { stock: { gte: 10 } } }) returns exactly {10, 100} ✅ ❌ returns {9, 10, 100}
(b) count({ stock: { gte: 10 } }) 2 ✅ ❌ 3
(c) UNIQUE expression index via createStorageIndexes created & enforced ✅ ✅ (already fixed by #1898 — kept as a guard)
(d) query({ orderBy: { stock: 'asc' } }) [9, 10, 100] ✅ ❌ [10, 100, 9]

SQLite passes throughout because json_extract already returns a typed value — which is why this went unnoticed.

EMDASH_TEST_PG=postgres://… pnpm --filter emdash exec vitest run \
  tests/integration/plugins/storage-postgres-numeric-regression.test.ts

Suggested fix direction: apply a type-guarded numeric cast to the extracted value in the numeric comparison and ORDER BY paths on Postgres (cast to numeric only when the jsonb value is a number, so non-numeric/null rows are excluded rather than erroring) — mirroring the typed value SQLite's json_extract already returns. Happy to follow up with the fix if the diagnosis looks right.

Related: #920 (closed by #1898). No existing issue tracks the remaining numeric case.

Type of change

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes (or targeted tests for my change) — intentionally unchecked: the Postgres assertions fail on main, which is the bug this PR demonstrates; SQLite passes
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation (if applicable) — N/A, no admin UI strings
  • I have added a changeset (if this PR changes a published package) — N/A, test-only, no published behavior change
  • New features link to an approved Discussion — N/A, not a feature

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 4.8 (Claude Code)

Screenshots / test output

Postgres dialect on current main (RED on a/b/d, GREEN on c; all SQLite green):

× [postgres] numeric RangeFilter { gte: 10 } ...   expected [ 'p10','p100','p9' ] to deeply equal [ 'p10','p100' ]
× [postgres] count({ stock: { gte: 10 } }) ...      expected 3 to be 2
✓ [postgres] UNIQUE expression index (guard) ...
× [postgres] orderBy { stock: 'asc' } ...           expected [ 10,100,9 ] to deeply equal [ 9,10,100 ]
  Tests  3 failed | 5 passed (8)

@changeset-bot

changeset-bot Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: a8c0e5f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

… Postgres

`_plugin_storage.data` is a `text` column. emdash-cms#1898 added the `(data)::jsonb->>'…'`
cast so extraction no longer errors and boolean/equality filters work, but `->>`
still yields text and the query/count/order paths compare it directly. On
Postgres that means numeric guards compare lexically — `'9' >= '10'` is TRUE —
so a `{ stock: { gte: 10 } }` filter over 9/10/100 silently includes 9
(over-count / oversell) and numeric orderBy returns [10, 100, 9].

Adds a dialect-parametric suite (describeEachDialect) pinning the remaining
failure modes. SQLite's json_extract is typed, so it stays green; the Postgres
dialect fails on the range/count/order cases on current main. Postgres runs only
when EMDASH_TEST_PG is set.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01TX9YciGFRZX9aF2UcQ6rUW
@vedanshujain
vedanshujain force-pushed the test/plugin-storage-postgres-numeric-regression branch from 5f2ab6d to a8c0e5f Compare July 20, 2026 16:58
@vedanshujain

Copy link
Copy Markdown
Contributor Author

I have read the CLA Document and I hereby sign the CLA

github-actions Bot added a commit that referenced this pull request Jul 20, 2026
@vedanshujain
vedanshujain marked this pull request as ready for review July 20, 2026 18:41
@github-actions github-actions Bot added the review/needs-review No maintainer or bot review yet label Jul 20, 2026
@vedanshujain

Copy link
Copy Markdown
Contributor Author

Closing in favor of #2152

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The diagnosis is right and the test is a clean, focused repro. #1898 switched Postgres plugin-storage access to (data)::jsonb->>'field', which fixed the parse error and string/boolean filters but still compares the extracted text for ranges and ordering. The new file seeds values (9/10/100) where lexical and numeric order diverge, so it correctly fails on current Postgres for the gte filter, count, and orderBy cases while staying green on SQLite.

I read PluginStorageRepository, storage-query, dialect-helpers, storage-indexes, test-db, the _plugin_storage migration, and the existing storage-dialect.test.ts. The assertions are accurate, the dialect harness is used correctly, and the test doesn't duplicate the existing storage-dialect.test.ts cases (which use 1/2/3 and therefore can't expose lexical ordering). No AGENTS.md violations: test-only so no changeset/i18n/Discussion required, and the AI disclosure is checked.

The only concern is merge readiness: this PR adds tests that are deliberately red on Postgres main. That will break pnpm test in any CI job that sets EMDASH_TEST_PG. Per AGENTS.md's TDD flow, the failing test should land together with the production fix (or the known-failing Postgres cases should be marked it.fails while the repro is shared). I would not merge this as-is.

stock: number;
}

describeEachDialect("Plugin storage numeric comparison on Postgres", (dialect) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[needs fixing] This describeEachDialect block intentionally contains three Postgres assertions that fail on current main (the gte range filter, count, and orderBy cases). Those failures are exactly the bug being demonstrated, but they also mean this file will keep pnpm test red whenever EMDASH_TEST_PG is configured. A deliberately failing test suite on main is not mergeable.

Either land this together with the production fix, or mark the known-failing Postgres cases as expected failures so CI stays green while the repro is shared. For example:

Suggested change
describeEachDialect("Plugin storage numeric comparison on Postgres", (dialect) => {
const itFailsOnPostgres = dialect === "postgres" ? it.fails : it;
// (a) The load-bearing case: a lexical `>=` includes stock 9 in a `>= 10`
// filter — a silent over-count / oversell.
itFailsOnPostgres("numeric RangeFilter { gte: 10 } returns exactly {10, 100}, never 9", async () => {
const repo = await seedProducts();
const result = await repo.query({ where: { stock: { gte: 10 } } });
expect(result.items.map((i) => i.id).toSorted()).toEqual(["p10", "p100"]);
expect(result.items.map((i) => i.data.stock).toSorted((a, b) => a - b)).toEqual([10, 100]);
});
// (b) Same lexical bug via the aggregate path.
itFailsOnPostgres("count({ stock: { gte: 10 } }) is numerically correct (2, not 3)", async () => {
const repo = await seedProducts();
expect(await repo.count({ stock: { gte: 10 } })).toBe(2);
});

(Apply the same wrapper to the orderBy case as well.) Once the production fix lands, the it.fails cases will start passing and Vitest will flag them so you can remove the wrapper.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant