ab: deleting a document in one collection removes the A/B experiment rows of another collection's document with the same id
维护者通常 1 天内回复
还没有人认领这个 Issue。
评估
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 新手友好度
- 88/100
- Issue 类型
- 缺陷
- 描述清晰度
- 描述清楚
- 活跃度
- 活跃
- 技术栈
- postgresql, typescript
调研方向
从 packages/payload-plugin-ab/src/hooks/buildParentAfterDeleteHook.ts 中的 delete 调用开始;parentCollectionSlug 已经是一个参数。修改 where,把 parentDocId 与 parentCollection 组合起来,然后使用 issue 中的内存 delete mock 添加 tests/hooks/buildParentAfterDeleteHook.test.ts。在 packages/payload-plugin-ab 中运行 bun run test,然后运行 build 和 lint。当另一个 collection 中具有相同 id 的行仍然存在、被删除 collection 的行已消失,并且 package 检查通过时,就完成了。
由索引模型根据 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 小时
- 30 天内合并 PR
- 41
环境准备
这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 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 一周以上 新手友好度 35/100
focusreactive/payload-plugins#210 · 10 条评论 ·
维护者通常 1 天内回复
-
[translator] Re-extract the traversal engine into its own package可能重新可做 @SearheiParkhamchuk 于 41 天前认领,目前没有进行中的 PR。 未关闭chore low priority translator
focusreactive/payload-plugins#203 · 已指派 1 人 ·
维护者通常 1 天内回复
-
[translator] Open the seam to hosts: export the module type and provenance()可能重新可做 @SearheiParkhamchuk 于 41 天前认领,目前没有进行中的 PR。 未关闭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 天内回复