ab: deleting a document in one collection removes the A/B experiment rows of another collection's document with the same id
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 2/5
- 見積もり時間
- 1〜3時間
- 初心者へのやさしさ
- 88/100
- issue の種類
- バグ
- 明瞭さ
- 明確に書かれている
- 活発さ
- 活発
- 技術スタック
- postgresql, typescript
調査の方向性
packages/payload-plugin-ab/src/hooks/buildParentAfterDeleteHook.ts の delete 呼び出しから始めてください。parentCollectionSlug はすでに引数です。where を変更して parentDocId と parentCollection を組み合わせ、次に issue のインメモリ delete モックを使って tests/hooks/buildParentAfterDeleteHook.test.ts を追加してください。packages/payload-plugin-ab で bun run test を実行し、その後 build と lint を行ってください。同じ id を持つ別のコレクションの行が残り、削除されたコレクションの行が消え、パッケージのチェックが通ったら完了です。
索引モデルが issue の本文から書いたものです。
説明
TL;DR
Deleting any non-variant document in an A/B-enabled collection also deletes, without an error or log entry, the ab-experiments rows of an A/B test that runs on a document with the same id in another A/B-enabled collection. With the Postgres adapter's default serial ids every collection counts from 1, so two configured collections are enough. The A/B test drops out of the analytics plugin's A/B overview until the next publish of its document or one of its variants, which creates the row again with a new start date; its variants, traffic split and GA4 data are not touched. The fix is one extra condition in one where clause, plus a unit test. Neither the reproduction nor the proposed test has been run; both were traced through the code.
Implementation details are in the next section.
For the implementing agent
Scope
- Package:
packages/payload-plugin-ab(@focus-reactive/payload-plugin-ab). The same code ships in 2.10.1 and 2.11.0. - Source file to change:
packages/payload-plugin-ab/src/hooks/buildParentAfterDeleteHook.ts. New test file:packages/payload-plugin-ab/tests/hooks/buildParentAfterDeleteHook.test.ts. - Line numbers refer to commit daf914b7. If they have moved, locate the code by the snippet
where: { parentDocId: { equals: String(id) } }.
Root cause
packages/payload-plugin-ab/src/hooks/buildParentAfterDeleteHook.ts:68-78:
const experimentsSlug = pluginConfig.experimentsCollectionSlug ?? AB_EXPERIMENTS_SLUG;
await payload
.delete({
collection: experimentsSlug as CollectionSlug,
where: { parentDocId: { equals: String(id) } },
overrideAccess: true,
req,
})
.catch(() => {
// non-fatal: nothing to delete if no experiment was ever recorded
});
packages/payload-plugin-ab/src/plugin.ts:57-60adds this hook to every collection listed in the plugin'scollectionsoption, passingcollection.slugas the first argument.- That argument is
parentCollectionSlug(buildParentAfterDeleteHook.ts:9). The hook already uses it for the variant lookup and unlinking (lines 44 and 56), but not for this delete. - Every experiment row stores both keys. The only writer is
packages/payload-plugin-ab/src/hooks/ensureExperimentRecords.ts:56-67, which setsparentDocId: String(parentId)(line 60) andparentCollection: parentCollectionSlug(line 61). - The delete runs for every non-variant document (variants return at lines 19-34), whether or not that document has a test. It removes every row whose
parentDocIdequals the deleted id, whichever collection the row belongs to. - The analytics plugin's A/B overview lists experiments from these rows (
packages/payload-plugin-analytics/src/services/queries/getAbOverview.ts:50), so a deleted row removes the A/B test from it.
Change
Replace the where at line 72 and leave the rest of the call, including the .catch, as it is:
// before
where: { parentDocId: { equals: String(id) } },
// after
where: {
and: [
{ parentDocId: { equals: String(id) } },
{ parentCollection: { equals: parentCollectionSlug } },
],
},
Checked at daf914b7:
parentCollectionis the field name in the experiments collection:name: "parentCollection",type: "text",required: true(packages/payload-plugin-ab/src/collections/buildExperimentsCollection.ts:31-35).- The stored value has the same form as the hook's argument.
ensureExperimentRecordsis called frompackages/payload-plugin-ab/src/hooks/buildParentAfterChangeHook.ts:28and:55with that factory'sparentCollectionSlug, whichplugin.ts:55sets tocollection.slug, the same valueplugin.ts:59passes to the delete hook. - The
andform is how the package combines conditions elsewhere:where: { and: conditions }(packages/payload-plugin-ab/src/hooks/buildParentBeforeChangeHook.ts:41),{ and: conditions }(packages/payload-plugin-ab/src/utils/recomputeManifest.ts:44),and: [ ... ](packages/payload-plugin-ab/src/utils/injectAdminFields.ts:117).
Test to add
How the package is tested at daf914b7:
- Vitest 2 (
"vitest": "^2.1.8",packages/payload-plugin-ab/package.json:122), script"test": "vitest run"(package.json:88). packages/payload-plugin-ab/vitest.config.ts:environment: "node",globals: false(importdescribe,it,expect,vifromvitest), filestests/**/*.test.{ts,tsx}.- Hook tests live in
packages/payload-plugin-ab/tests/hooks/(buildParentAfterChangeHook,buildParentBeforeChangeHook,ensureExperimentRecords) and run without a database: each calls the hook or function directly with a hand-builtreq, mockingreq.payloadmethods withvi.fn()or, in the afterChange test, the helper modules withvi.mock. There is no test forbuildParentAfterDeleteHookyet. - Models: the mocked payload in
packages/payload-plugin-ab/tests/hooks/ensureExperimentRecords.test.ts:18-46and the hook call through a cast inpackages/payload-plugin-ab/tests/hooks/buildParentAfterChangeHook.test.ts:25-28.
Add packages/payload-plugin-ab/tests/hooks/buildParentAfterDeleteHook.test.ts. Starting point (not run):
import { describe, expect, it, vi } from "vitest";
import { buildParentAfterDeleteHook } from "../../src/hooks/buildParentAfterDeleteHook";
import type { AbTestingPluginConfig, CollectionABConfig } from "../../src/types/config";
type Row = Record<string, string>;
type Where = Record<string, unknown>;
const abConfig: CollectionABConfig = { generatePath: () => null };
const pluginConfig = {
collections: { pages: abConfig, posts: abConfig },
storage: {} as never,
} as AbTestingPluginConfig;
// Supports what the hook sends: `and` and `equals`.
function matches(row: Row, where: Where): boolean {
return Object.entries(where).every(([field, condition]) => {
if (field === "and") return (condition as Where[]).every((w) => matches(row, w));
return row[field] === (condition as { equals: unknown }).equals;
});
}
function makeReq(rows: Row[]) {
const store = { rows };
const payload = {
config: { localization: false },
find: vi.fn().mockResolvedValue({ docs: [] }),
delete: vi.fn().mockImplementation(({ where }: { where: Where }) => {
store.rows = store.rows.filter((row) => !matches(row, where));
return Promise.resolve({ docs: [] });
}),
};
return { req: { payload } as never, store };
}
const run = (collection: string, id: number, req: never) =>
(
buildParentAfterDeleteHook(collection, abConfig, pluginConfig) as unknown as (
args: Record<string, unknown>
) => Promise<unknown>
)({ doc: { id }, id, req });
describe("buildParentAfterDeleteHook", () => {
it("keeps another collection's experiment row when the ids are equal", async () => {
const { req, store } = makeReq([
{ parentCollection: "pages", parentDocId: "1" },
{ parentCollection: "posts", parentDocId: "1" },
]);
await run("posts", 1, req);
expect(store.rows).toEqual([{ parentCollection: "pages", parentDocId: "1" }]);
});
it("removes every row of the deleted parent", async () => {
const { req, store } = makeReq([
{ parentCollection: "pages", parentDocId: "1", locale: "en" },
{ parentCollection: "pages", parentDocId: "1", locale: "de" },
{ parentCollection: "pages", parentDocId: "2", locale: "en" },
]);
await run("pages", 1, req);
expect(store.rows).toEqual([{ parentCollection: "pages", parentDocId: "2", locale: "en" }]);
});
});
Why the mock is this small: generatePath: () => null skips storage.clear (hook lines 36-41), config.localization: false makes getLocales return [undefined] (packages/payload-plugin-ab/src/utils/getLocales.ts:6), and find returning no docs skips the variant unlinking (lines 43-66). The delete mock applies the where to an in-memory list, so the test checks which rows survive, not the shape of the query. With the current code the first case fails (both rows are removed) and the second passes; after the change both pass.
Run: bun install at the repo root (CLAUDE.md:74), then bun run test in packages/payload-plugin-ab. One app pulls a private git repository (apps/content-agent-demo/package.json:36). If the install fails on it, install as CI does with bun install --frozen-lockfile --filter '!./apps/*' (.github/workflows/release.yml:55-62). That install leaves out the apps, so the pre-push hook's repo-wide check-types (lefthook.yml:13-16) fails in apps this change does not touch (release.yml:21-24). Push with LEFTHOOK=0 in that case, as CI does.
Behavioural spec, end to end with the Local API (traced through the code, not run):
- Payload 3 with
@payloadcms/db-postgres(defaultserialids) and an empty database. - Two collections,
pagesandposts, each with aslugtext field and withoutversions.drafts. Plugin config:
import { abTestingPlugin } from "@focus-reactive/payload-plugin-ab";
import { payloadGlobalAdapter } from "@focus-reactive/payload-plugin-ab/adapters/payload-global";
abTestingPlugin({
storage: payloadGlobalAdapter(),
collections: {
pages: { generatePath: ({ doc }) => (doc.slug ? `/${doc.slug}` : null) },
posts: { generatePath: ({ doc }) => (doc.slug ? `/blog/${doc.slug}` : null) },
},
})
- Run:
const page = await payload.create({ collection: "pages", data: { slug: "about" } });
await payload.create({
collection: "pages",
data: { slug: "about--v1", _abVariantOf: page.id, _abPassPercentage: 50 },
});
const post = await payload.create({ collection: "posts", data: { slug: "hello" } });
// empty database: page.id === post.id === 1
const where = { parentCollection: { equals: "pages" } };
const before = await payload.find({ collection: "ab-experiments", where });
// before.totalDocs === 1 (manifestKey "/about")
await payload.delete({ collection: "posts", id: post.id });
const after = await payload.find({ collection: "ab-experiments", where });
// today: after.totalDocs === 0; expected after the fix: 1
Expected: deleting posts 1 removes only rows with parentCollection = "posts" and parentDocId = "1", and the pages row stays. Today every row with parentDocId = "1" is removed. With debug: true the experiments collection is visible in the admin (buildExperimentsCollection.ts:7), so the same check can be done there.
Acceptance criteria
- Deleting a non-variant document in collection A removes only experiment rows with
parentCollection= A andparentDocId=String(id); rows of collection B with the sameparentDocIdremain. - Deleting a non-variant document still removes all of its own rows (one per locale in a localized config).
- The new test file fails on the current code and passes with the change.
-
bun run testinpackages/payload-plugin-abpasses. -
bun run buildinpackages/payload-plugin-absucceeds. The package has nocheck-typesscript (package.json:85-94), and itstsconfig.jsonincludes onlysrc/**/*. -
bun run lintinpackages/payload-plugin-abreports no problems in the two touched files. Warnings it reports in other files are out of scope; the repository carries legacy lint warnings (lefthook.yml:17-20). - No other file is changed.
Out of scope / do not change
- No schema change and no data migration:
parentCollectionis required and always written (see Root cause and Change). - Rows already lost to this bug are not restored by the fix.
ensureExperimentRecordsre-creates a row, with a newstartedAt(ensureExperimentRecords.ts:63), on the next non-draft save of the parent or of one of its variants (buildParentAfterChangeHook.ts:28and:55), when the parent'sgeneratePathreturns a non-null path and the variant lookup finds at least one variant (ensureExperimentRecords.ts:31-44). That lookup usesdraft: falsewithout a_statusfilter, so in a collection with drafts a variant that has never been published counts too. - The rest of the hook stays as it is: the variant branch, the manifest clearing and the variant unlinking already work on the deleting collection only.
- No change to the experiments collection definition,
ensureExperimentRecords, the manifest or variant logic, orpackages/payload-plugin-analytics.
Commit and PR
Releases run through multi-semantic-release with conventional commit types (CLAUDE.md:83-104, .releaserc.json). Use a fix commit, which gives a patch release; this package's changelog entries use the ab scope (packages/payload-plugin-ab/CHANGELOG.md:6, :13), for example fix(ab): scope experiment row cleanup on delete to the deleted document's collection. Do not edit CHANGELOG.md or the version field: the release job writes both (.releaserc.json:14-28, CLAUDE.md:122).
Open a PR against main. Do not push to main directly: every push to main runs the Release workflow (.github/workflows/release.yml:3-6), which publishes the changed packages to npm (.releaserc.json:21, CLAUDE.md:89-90), so merging the PR publishes the patch release.
Other places checked
Searched packages/payload-plugin-ab/src and packages/payload-plugin-analytics/src for experimentsCollectionSlug, AB_EXPERIMENTS_SLUG, ab-experiments, parentDocId and parentCollection, and for every call that writes data:
payload-plugin-ab: the experiments collection is read or written in two files.ensureExperimentRecords.ts:46-53finds a row bymanifestKey, and:56-67creates it.buildParentAfterDeleteHook.ts:68-78is the only delete and the onlyparentDocId-only filter.plugin.ts:66-67builds the collection andplugin.ts:71registers it. The other writes in the package (payload.updateatpackages/payload-plugin-ab/src/utils/applyVariantPercentage.ts:24,:38andbuildParentAfterDeleteHook.ts:55,payload.db.updateOneatapplyVariantPercentage.ts:61,payload.duplicateatpackages/payload-plugin-ab/src/endpoints/duplicateVariant.ts:50,payload.updateGlobalatpackages/payload-plugin-ab/src/adapters/payloadGlobal/index.ts:17,:36, and the Edge Config request atpackages/payload-plugin-ab/src/adapters/vercelEdge/api/updateEdgeConfig.ts:11) target content documents or the manifest, not experiment rows.payload-plugin-analytics: read-only.packages/payload-plugin-analytics/src/services/queries/getAbExperimentRecords.ts:25-31reads all rows, and:41-48reads one bymanifestKey. Callers passparentCollectionandparentDocIdtogether togetExperimentBucketMeta(packages/payload-plugin-analytics/src/services/queries/getAbOverview.ts:160-166,packages/payload-plugin-analytics/src/services/queries/getAbExperimentStats.ts:75-81), which queries theparentCollectioncollection byparentDocId(packages/payload-plugin-analytics/src/services/queries/getExperimentBucketMeta.ts:28-30). No writes and noparentDocId-only filter.
- 主要言語
- TypeScript
- スター
- 34
- フォーク
- 5
- 平均マージ
- 2日 4時間
- マージ済み PR(30日)
- 41
環境構築
このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
focusreactive/payload-plugins のほかの issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
focusreactive/payload-plugins#279 ·
メンテナーはふだん 1 日以内に返信
-
comments, seo, analytics, and presets publish ESM that fails to load in Node.js (follow-up to #149)オープン
難易度 3/5 1〜2日 初心者へのやさしさ 62/100
focusreactive/payload-plugins#240 ·
メンテナーはふだん 1 日以内に返信
-
released released on @next
難易度 5/5 1週間以上 初心者へのやさしさ 35/100
focusreactive/payload-plugins#210 · コメント 10 件 ·
メンテナーはふだん 1 日以内に返信
-
[translator] Re-extract the traversal engine into its own package再び着手できるかも @SearheiParkhamchuk が 41 日前に担当しましたが、オープン中のプルリクエストはありません。 オープンchore low priority translator
focusreactive/payload-plugins#203 · 担当者 1 名 ·
メンテナーはふだん 1 日以内に返信
-
[translator] Open the seam to hosts: export the module type and provenance()再び着手できるかも @SearheiParkhamchuk が 41 日前に担当しましたが、オープン中のプルリクエストはありません。 オープンenhancement low priority translator
focusreactive/payload-plugins#202 · 担当者 1 名 ·
メンテナーはふだん 1 日以内に返信
focusreactive/payload-plugins の issue をすべて見る
似ている issue
-
verified whatsapp
難易度 2/5 1〜3時間 初心者へのやさしさ 77/100
メンテナーはふだん 6 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 68/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 68/100
メンテナーはふだん 2 日以内に返信
-
openidconnect: option to use client_secret_post (client_id with "-" rejected by LemonLDAP::NG 2.21)オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 62/100
MTES-MCT/monitorenv#3257 ·
メンテナーはふだん 1 日以内に返信