ab: deleting a document in one collection removes the A/B experiment rows of another collection's document with the same id
Maintainer thường phản hồi trong vòng 1 ngày
Chưa có ai nhận issue này.
Đánh giá
- Độ khó
- 2/5
- Thời gian dự kiến
- 1-3 giờ
- Mức phù hợp với người mới
- 88/100
- Loại issue
- Lỗi
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức độ hoạt động
- Sôi nổi
- Công nghệ
- postgresql, typescript
Hướng nghiên cứu
Bắt đầu trong packages/payload-plugin-ab/src/hooks/buildParentAfterDeleteHook.ts tại lời gọi delete; parentCollectionSlug đã là một đối số. Thay đổi where để kết hợp parentDocId với parentCollection, sau đó thêm tests/hooks/buildParentAfterDeleteHook.test.ts bằng cách dùng mock delete trong bộ nhớ từ issue. Chạy bun run test trong packages/payload-plugin-ab, sau đó build và lint. Xong khi hàng của một collection khác có cùng id vẫn còn, các hàng của collection đã xóa biến mất và các kiểm tra của package đều qua.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
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.
- Ngôn ngữ chính
- TypeScript
- Star
- 34
- Fork
- 5
- Merge trung bình
- 2 ngày 4 giờ
- Pull request đã merge (30 ngày)
- 41
Chuẩn bị môi trường
Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của focusreactive/payload-plugins
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 82/100
focusreactive/payload-plugins#279 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
comments, seo, analytics, and presets publish ESM that fails to load in Node.js (follow-up to #149)Đang mở
Độ khó 3/5 1-2 ngày Mức phù hợp với người mới 62/100
focusreactive/payload-plugins#240 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
released released on @next
Độ khó 5/5 Hơn một tuần Mức phù hợp với người mới 35/100
focusreactive/payload-plugins#210 · 10 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[translator] Re-extract the traversal engine into its own packageCó thể làm lại được @SearheiParkhamchuk đã nhận 41 ngày trước và không có pull request nào đang mở. Đang mởchore low priority translator
focusreactive/payload-plugins#203 · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[translator] Open the seam to hosts: export the module type and provenance()Có thể làm lại được @SearheiParkhamchuk đã nhận 41 ngày trước và không có pull request nào đang mở. Đang mởenhancement low priority translator
focusreactive/payload-plugins#202 · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của focusreactive/payload-plugins
Issue tương tự
-
verified whatsapp
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 77/100
Maintainer thường phản hồi trong vòng 6 ngày
-
Feature: use a darkmode logoĐang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 68/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 68/100
Maintainer thường phản hồi trong vòng 2 ngày
-
openidconnect: option to use client_secret_post (client_id with "-" rejected by LemonLDAP::NG 2.21)Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Amélioration du résumé regĐang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 62/100
MTES-MCT/monitorenv#3257 ·
Maintainer thường phản hồi trong vòng 1 ngày