Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M15-202): The M15 gate: conformance.sh --assert exits 0, and 'follow one request end to end' becomes a test that fails when someone breaks it

ralphde2090d7aad0
diff --git a/apps/api/e2e/legacy-job-proof.ts b/apps/api/e2e/legacy-job-proof.ts
index 2f689a2b1..63d4adcf8 100644
--- a/apps/api/e2e/legacy-job-proof.ts
+++ b/apps/api/e2e/legacy-job-proof.ts
@@ -286,6 +286,7 @@ async function main() {
const deps: AppDeps = {
db: undefined as unknown as AppDeps['db'],
+ prisma: undefined as unknown as AppDeps['prisma'],
ch: undefined as unknown as AppDeps['ch'],
redis: undefined as unknown as AppDeps['redis'],
clients: undefined as unknown as AppDeps['clients'],
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index 3ca47ea65..f4643c801 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -83,7 +83,7 @@ import {
type WorkerHandle,
} from '@openpanel/core';
import { ch } from '@openpanel/db/src/clickhouse/client';
-import { db } from '@openpanel/db/src/prisma-client';
+import { db, Prisma } from '@openpanel/db/src/prisma-client';
import { getRedisCache, getRedisPub, getRedisQueue } from '@openpanel/redis';
import { Elysia } from 'elysia';
import pino from 'pino';
@@ -186,6 +186,10 @@ function buildDeps(): AppDeps {
// the cache Redis, handed down so a service reaches them through its
// request-scoped `Ctx` instead of importing them (TECH_DEBT §4).
db,
+ // Prisma's two JSON sentinels, so the four modules that write a nullable
+ // `Json?` column read them off the scope instead of importing the client
+ // (ADR-022 R6).
+ prisma: { DbNull: Prisma.DbNull, JsonNull: Prisma.JsonNull },
ch,
redis: getRedisCache(),
clients: createClients(),
diff --git a/docs/TECH_DEBT.md b/docs/TECH_DEBT.md
index 67810ceb6..70184d053 100644
--- a/docs/TECH_DEBT.md
+++ b/docs/TECH_DEBT.md
@@ -2043,3 +2043,79 @@ agree with the three new places.
the new `bun-version.test.ts`.
No ClickHouse SQL touched; no lockfile or manifest changed.
+
+## 2026-09-11 — M15-202, ADR-022's "Existing implementation" table re-measured
+
+Ran by: ralph (M15-202 implement task), on the finished M15 tree (branch
+`rewrite/v2`, working tree at `20f63a8f` plus this task's own diff).
+
+ADR-022's *Existing implementation* section measured the shape of the tree on
+2026-09-07/08 — before the fix wave — and every row of it was a defect the
+wave was authorised to remove. This is the same table, re-measured, so the
+claim "the wave is done" is a number rather than a feeling. Nothing here is
+carried over from the ADR's own run: each "after" figure is from a command
+run today, and the command is named beside it.
+
+**How the after column was measured.** Twelve of the thirteen rows are read
+straight off `bash tooling/gates/conformance.sh --report`, whose
+BASELINE REPRODUCTION block prints exactly these counts; the greps beside
+them are the cross-check, and where a grep and the gate disagree the reason is
+given. The gate's own two traps (an eight-line factory signature a line grep
+misses; a `ReturnType<typeof create` match that is a comment) are covered by
+`tooling/gates/conformance/rules.test.ts`.
+
+| ADR-022 row | Before (2026-09-07/08) | After (2026-09-11) | How |
+|---|---:|---:|---|
+| Composition — factories not on `(deps, services: () => Services)` | 36 of 36 | **0 of 36** | gate `R3`; `grep -rn 'export function create[A-Za-z]*Service('` over `*.service.ts` still finds all 36 factories |
+| Typing — hand-written `export interface XService` outside `services.ts` | 37 | **0** | gate `R5`; `grep -rn '^export interface [A-Za-z]*Service '` → 0 |
+| Typing — `Services` members typed `ReturnType<typeof createXService>` | 0 of 36 | **36 of 36** | gate `R5` (in code, not in the comment that documents the rule) |
+| Sibling access — `load*` dependency loaders | 55 | **0**, of 2 `load*` functions left | gate `R6`. The two survivors are the allowlisted asset loaders ADR-022 names by hand: `clients/geo.ts:27 loadDatabase` (a MaxMind `.mmdb` file) and `modules/integration/src/flush-exports.ts:330 loadCursor` (an export cursor row, read through the handle it was handed) |
+| Compat layer — `v1-compat.ts` | 2,104 lines, 71 importers | **file does not exist** | `ls packages/core/src/v1-compat.ts` → no such file. The 5 remaining textual matches under `packages/core/src` are all in three `*.sql.proof.md` files, prose describing what the seam used to do |
+| Compat layer — unsanctioned `createServices(` call sites | 1 | **0** | gate `R6` |
+| Env — `process.env.` reads in `packages/core/src` (non-test) | 172 across 50 files | **0 across 0 files** | gate `R7`, which counts the bracketed form too. The one raw-grep match left, `rpc/base.ts:251`, is a comment saying core reads none — the same false positive ADR-022 recorded against its own baseline |
+| Auth — `require(Login\|ReadAccess\|WriteAccess\|Access)` definitions outside `rpc/base.ts` and `modules/auth/` | 38 | **0** | gate `R10`. One definition survives in the tree and it is in the auth stack: `modules/auth/auth.service.ts:150 requireLogin` |
+| Layering — `shared/` importing upward | 7 | **0** | gate `R22` (`core-layers-shared-is-the-bottom`, delegated to dependency-cruiser at `error`) |
+| Layering — `http/*` and `rpc/base.ts` deep-importing `modules/*/src/*` | 8 | **0** | gate `R22` (`core-layers-transport-below-modules`) |
+| Duplication — util copies across `apps/*` and `packages/*` | 5 | **0** | gate `R21`. `packages/redis/json.ts` — the file that carried its own "keep in sync with packages/core" comment — is gone; `@openpanel/shared` exists and declares no workspace dependency |
+| Residue — `NEXT_PUBLIC_` in `packages/core/src` | 5 (of 26 in 12 files) | **0** | gate `R14` |
+| Enforcement — `dependency-cruiser` declared | installed into a cache at gate time | **declared**, `"dependency-cruiser": "18.2.0"` in the root `devDependencies` | `package.json:88`; R22 therefore ships as the cruiser rule, not ADR-022's grep fallback |
+
+**`bash tooling/gates/conformance.sh --assert` exits 0** on this tree — the
+M15 gate. Total asserted violations: 0.
+
+### One count fixed here, two still wrong, one script still red
+
+**Fixed here (ADR-022 R15, CONFORMANCE_PLAN.md §1l).** The module-scope
+construction checker looked only at `ts.isIdentifier(node.expression)`, so a
+qualified `new Arctic.Google(...)` was invisible to it, and its constructor
+set did not contain `GitHub` at all. Both spellings are in
+`modules/auth/src/oauth.ts`. The checker now resolves a qualified `new A.B()`
+to its rightmost name before the lookup, and `GitHub`/`Google` joined
+`CONNECTION_CONSTRUCTOR_NAMES`; two tests in
+`tooling/gates/conformance/rules.test.ts` pin both spellings, at module scope
+(2 violations) and inside a factory body (0). **R15 still reports 0** — all
+three arctic clients are built per call, from `config.auth.*` — so the number
+is now trustworthy rather than flattering.
+
+Worth knowing while reading that: **`rules.test.ts` is in no suite.** The root
+`test` script runs four packages plus `vitest run` over
+`vitest.workspace.ts`'s two, and `tooling/` is in neither list, so the gate's
+own regression tests — including the two ADR-022 named as mandatory before
+acceptance — only run when someone runs them by hand
+(`cd tooling/gates/conformance && bun test`: 18 pass, 0 fail, 2026-09-11).
+Pre-existing, and wiring it in means editing the root `package.json`.
+
+**Still under-counted: R14's residue scan does not reach `packages/`.**
+`tooling/gates/conformance/cli.ts:124` builds `residueFiles` from
+`packages/core`, `apps/api` and `apps/start` only, so the one surviving
+`NEXT_PUBLIC_` reference outside `apps/public` —
+`packages/payments/src/polar.ts:66` — is not seen by the rule whose label
+says "elsewhere outside `apps/public/`". Recorded, not fixed: R14 was
+M15-201's target and widening the scan is a change to what that gate asserts.
+
+**Still failing for an unrelated reason:
+`verification/golden/queue-keys/check.sh`.** It imports
+`CRON_SCHEDULES` from `packages/core/src/jobs/schedulers.ts`, which ADR-021
+moved onto the jobs themselves; the export is gone and the script dies on
+`sch.CRON_SCHEDULES.map`. Verified pre-existing by stashing this task's diff
+and re-running: same failure at `20f63a8f`.
diff --git a/packages/core/src/context.test.ts b/packages/core/src/context.test.ts
index a999b1078..9e9127b1d 100644
--- a/packages/core/src/context.test.ts
+++ b/packages/core/src/context.test.ts
@@ -69,6 +69,7 @@ function stubDeps(): {
scoped,
deps: {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/src/context.ts b/packages/core/src/context.ts
index 6129c3b52..ac4d77897 100644
--- a/packages/core/src/context.ts
+++ b/packages/core/src/context.ts
@@ -42,10 +42,17 @@ export type PrismaNamespace =
* Prisma's JSON sentinels (`DbNull`, `JsonNull`): frozen constants that write
* an explicit SQL NULL — or a JSON `null` — onto a nullable `Json?` column.
* They are values on the namespace, not a client, so nothing about them is
- * per-request and `ServiceDeps` carries no field for them.
+ * per-request — but they are still `@openpanel/db` VALUES, and the four
+ * modules that write a `Json?` column each reached them through a lazy
+ * `load*` back into this file. ADR-022 R6 has one answer for that: the scope
+ * carries it. `main.ts` reads the two off the namespace once and puts them on
+ * `AppDeps`; every writer reads `deps.prisma.DbNull`. Two named fields, not
+ * the namespace itself — nothing else on it belongs in a request scope, and
+ * `Prisma` is a very large type for every consumer's `tsc` to walk.
*/
-export function prismaSentinels(): Promise<PrismaNamespace> {
- return import('@openpanel/db/src/prisma-client').then((m) => m.Prisma);
+export interface PrismaSentinels {
+ DbNull: PrismaNamespace['DbNull'];
+ JsonNull: PrismaNamespace['JsonNull'];
}
/**
@@ -83,6 +90,7 @@ export type { CoreConfig } from './config';
/** Boot scope. Built once in apps/api's main.ts, closed once in shutdown. */
export interface AppDeps {
db: Db;
+ prisma: PrismaSentinels;
ch: ClickHouseClient;
redis: RedisClient;
clients: ServiceClients;
@@ -95,6 +103,7 @@ export interface AppDeps {
/** Work scope. One per HTTP request, RPC call, job run or Kafka batch. */
export interface Ctx {
db: Db;
+ prisma: PrismaSentinels;
ch: ClickHouseClient;
redis: RedisClient;
clients: ServiceClients;
@@ -134,6 +143,7 @@ export interface ScopeMeta {
export function createCtx(deps: AppDeps, scope: ScopeMeta): Ctx {
const ctx: Ctx = {
db: deps.db,
+ prisma: deps.prisma,
ch: deps.ch,
redis: deps.redis,
clients: deps.clients,
@@ -170,6 +180,7 @@ function installLazyServices(ctx: Ctx): void {
get() {
built ??= createServices({
db: ctx.db,
+ prisma: ctx.prisma,
ch: ctx.ch,
redis: ctx.redis,
clients: ctx.clients,
diff --git a/packages/core/src/jobs/workers.test.ts b/packages/core/src/jobs/workers.test.ts
index 00609b08a..5875660ca 100644
--- a/packages/core/src/jobs/workers.test.ts
+++ b/packages/core/src/jobs/workers.test.ts
@@ -26,6 +26,7 @@ function stubLogger(): Logger {
function stubDeps(): AppDeps {
return {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.ts
index 74415485e..9d33b6d81 100644
--- a/packages/core/src/modules/auth/auth.rpc.ts
+++ b/packages/core/src/modules/auth/auth.rpc.ts
@@ -119,5 +119,7 @@ export const authRouter = createTRPCRouter({
signInShare: publicProcedure
.input(zSignInShare)
- .mutation(({ input, ctx }) => signInToShare(ctx, input, ctx.setCookie)),
+ .mutation(({ input, ctx }) =>
+ signInToShare(() => ctx.services, input, ctx.setCookie)
+ ),
});
diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.ts
index ff21b3dcf..df221d7d7 100644
--- a/packages/core/src/modules/auth/auth.service.ts
+++ b/packages/core/src/modules/auth/auth.service.ts
@@ -18,10 +18,15 @@
import { z } from 'zod';
import type { CoreConfig } from '../../config';
import type { ServiceDeps, Services } from '../../services';
-import type {
- getClientAccess as GetClientAccessFn,
- getOrganizationAccess as GetOrganizationAccessFn,
- IProjectAccess,
+// Aliased: three members of `createAuthService` below carry the same names,
+// and this file is the ONE place the ladder is bound to these lookups.
+import {
+ canWriteProject,
+ getClientAccess as getClientAccessLookup,
+ getOrganizationAccess as getOrganizationAccessLookup,
+ getProjectAccess as getProjectAccessLookup,
+ getProjectById,
+ type IProjectAccess,
} from '../../shared/access-lookups';
import type { ISetCookie } from '../../shared/cookie';
import { type AccessChecks, createAccessChecks } from './src/access';
@@ -84,10 +89,6 @@ export {
verifyTotpCode,
} from './src/totp';
-function loadAccessLookups() {
- return import('../../shared/access-lookups');
-}
-
/** The ladder contract this module binds and `createAuthService` satisfies. */
type ProjectAccessChecks = AccessChecks<IProjectAccess>;
@@ -95,13 +96,15 @@ let accessChecksPromise: Promise<ProjectAccessChecks> | undefined;
/**
* The single binding of the ladder to real lookups
- * (M10-002, docs/TECH_DEBT.md §5b) — lazy AND memoized: `createAccessChecks`
- * itself runs exactly once per process, on however many requests, no matter
- * how many of this function's callers invoke it. Nothing here runs at
- * module-import time or at `createAuthService` construction time — both
- * `access-lookups.ts` and `project.service.ts` are reached only through the
- * dynamic imports below, the first time an actual check is made. An earlier
- * attempt bound this at module scope and hung `bun test` for 30 minutes.
+ * (M10-002, docs/TECH_DEBT.md §5b) — memoized: `createAccessChecks` runs
+ * exactly once per process, on however many requests, no matter how many of
+ * this function's callers invoke it. Nothing runs at module-import time or at
+ * `createAuthService` construction time; the binding is built on the first
+ * actual check. An earlier attempt bound it at module scope and hung
+ * `bun test` for 30 minutes.
+ *
+ * Still a `Promise` because the contract is awaited at every call site and
+ * was what each module's own access file used to resolve lazily.
*
* `integration.service.ts` and `subscription.service.ts` import this
* directly instead of going through `ctx.services.auth`: both are called with
@@ -109,19 +112,13 @@ let accessChecksPromise: Promise<ProjectAccessChecks> | undefined;
*/
export function getAccessChecks(): Promise<ProjectAccessChecks> {
if (!accessChecksPromise) {
- accessChecksPromise = loadAccessLookups().then(
- ({
- getProjectAccess,
+ accessChecksPromise = Promise.resolve(
+ createAccessChecks({
+ getProjectAccess: getProjectAccessLookup,
canWriteProject,
- getOrganizationAccess,
+ getOrganizationAccess: getOrganizationAccessLookup,
getProjectById,
- }) =>
- createAccessChecks({
- getProjectAccess,
- canWriteProject,
- getOrganizationAccess,
- getProjectById,
- })
+ })
);
}
return accessChecksPromise;
@@ -191,23 +188,23 @@ export function createAuthService(
return (await getAccessChecks()).requireProjectAdmin(args);
}
- async function getProjectAccess(args: {
+ function getProjectAccess(args: {
userId: string;
projectId: string;
}): Promise<IProjectAccess | null> {
- return (await loadAccessLookups()).getProjectAccess(args);
+ return getProjectAccessLookup(args);
}
- async function getOrganizationAccess(
- ...args: Parameters<typeof GetOrganizationAccessFn>
- ): ReturnType<typeof GetOrganizationAccessFn> {
- return (await loadAccessLookups()).getOrganizationAccess(...args);
+ function getOrganizationAccess(
+ ...args: Parameters<typeof getOrganizationAccessLookup>
+ ): ReturnType<typeof getOrganizationAccessLookup> {
+ return getOrganizationAccessLookup(...args);
}
- async function getClientAccess(
- ...args: Parameters<typeof GetClientAccessFn>
- ): ReturnType<typeof GetClientAccessFn> {
- return (await loadAccessLookups()).getClientAccess(...args);
+ function getClientAccess(
+ ...args: Parameters<typeof getClientAccessLookup>
+ ): ReturnType<typeof getClientAccessLookup> {
+ return getClientAccessLookup(...args);
}
/**
@@ -287,10 +284,10 @@ export function createAuthService(
//
// Session/registration access is `deps.db`, via static imports of
// `./src/login-session` and `./src/registration` (M10-004) — neither cycles
-// back to this file, so there is nothing to keep lazy there. `loadShare`
-// stays a lazy, dynamic import of `../share/share.service`: share.service.ts
-// statically imports this file's own `hashPassword`, so the two ARE a real
-// cycle (M6-004), unlike the other two.
+// back to this file, so there is nothing to keep lazy there. Share is the one
+// real cycle (M6-004) — share.service.ts statically imports this file's own
+// `hashPassword` — so `signInToShare` reaches it through the composition
+// root's `services()` thunk instead of importing it at all.
//
// None of these functions take a `TrpcContext`/`Ctx` directly — they take a
// `deps: ServiceDeps` plus exactly the other primitives they touch
@@ -326,16 +323,6 @@ interface CookieReader {
get(name: string): string | undefined;
}
-// GENUINE CYCLE, kept lazy: `../share/share.service` statically imports this
-// file's `hashPassword`, and `signInToShare` below needs share's three
-// lookups. auth.service.ts <-> share.service.ts is the cycle; the dynamic
-// import is what keeps it a cycle ESM can evaluate. It is NOT a
-// `@openpanel/db` loader — the share lookups take `deps` like everything
-// else since M10-003.
-function loadShare() {
- return import('../share/share.service');
-}
-
/**
* Best-effort consumption of an invite for a user that just authenticated.
* Failures (expired/invalid invite) must not block the sign-in itself, so we
@@ -862,26 +849,29 @@ export interface SignInShareInput {
shareType?: 'overview' | 'dashboard' | 'report';
}
+/** Share's three lookups arrive through the composition root's thunk
+ * (ADR-022 R3), not a dynamic import: `share.service.ts` statically imports
+ * this file's `hashPassword`, so a static edge back would be a real cycle. */
export async function signInToShare(
- deps: ServiceDeps,
+ services: () => Services,
input: SignInShareInput,
setCookie: ISetCookie
): Promise<true> {
const { password, shareId, shareType = 'overview' } = input;
const { getShareOverviewById, getShareDashboardById, getShareReportById } =
- await loadShare();
+ services().share;
let share: { password: string | null; public: boolean } | null = null;
let cookieName = '';
if (shareType === 'overview') {
- share = await getShareOverviewById(deps, shareId);
+ share = await getShareOverviewById(shareId);
cookieName = `shared-overview-${shareId}`;
} else if (shareType === 'dashboard') {
- share = await getShareDashboardById(deps, shareId);
+ share = await getShareDashboardById(shareId);
cookieName = `shared-dashboard-${shareId}`;
} else if (shareType === 'report') {
- share = await getShareReportById(deps, shareId);
+ share = await getShareReportById(shareId);
cookieName = `shared-report-${shareId}`;
}
diff --git a/packages/core/src/modules/cohort/cohort.jobs.test.ts b/packages/core/src/modules/cohort/cohort.jobs.test.ts
index a73095892..ddf37ec86 100644
--- a/packages/core/src/modules/cohort/cohort.jobs.test.ts
+++ b/packages/core/src/modules/cohort/cohort.jobs.test.ts
@@ -69,6 +69,7 @@ function stubJobCtx(
};
return {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/src/modules/event/event.rpc.ts b/packages/core/src/modules/event/event.rpc.ts
index 01aa0cf3e..ec3fb7cd5 100644
--- a/packages/core/src/modules/event/event.rpc.ts
+++ b/packages/core/src/modules/event/event.rpc.ts
@@ -96,7 +96,7 @@ export const eventRouter = createTRPCRouter({
level: 'read',
});
- const details = await getEventDetails(ctx, input);
+ const details = await getEventDetails(ctx, () => ctx.services, input);
if (!details) {
throw new TRPCNotFoundError('Event not found');
}
diff --git a/packages/core/src/modules/event/event.service.ts b/packages/core/src/modules/event/event.service.ts
index 1c0f2c826..adfdf526c 100644
--- a/packages/core/src/modules/event/event.service.ts
+++ b/packages/core/src/modules/event/event.service.ts
@@ -23,17 +23,20 @@
// `loadDb` / `loadChClient` / `loadDbBuffers` lazy loaders are gone, and so
// are the two `import('@openpanel/core')` self-barrel hops this file made for
// `resolveDateRange` — imported straight from `shared/`
-// (docs/TECH_DEBT.md §2, §4). What stays lazy is named and
-// argued at each remaining `load*` below; none of them reach @openpanel/db.
+// (docs/TECH_DEBT.md §2, §4). M15-202 removed the last three lazy loaders
+// here: the filter compiler and `getCache` are plain static imports, and the
+// session lookup arrives through the composition root's thunk (ADR-022 R3).
import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';
import type { EventMeta, Prisma } from '@openpanel/db/src/prisma-client';
+import { getCache } from '@openpanel/redis';
import { DateTime, resolveDateRange, toDots } from '@openpanel/shared';
import { clone, mergeDeepRight, uniq } from 'ramda';
import { cacheablePerDeps } from '../../cacheable-per-deps';
import { chQuery } from '../../ch-query';
import type { ServiceDeps, Services } from '../../services';
import { getEventFiltersWhereClause } from '../chart/src/filter-where';
+import { buildFilterWhere } from '../chart/src/table-filter-where';
import {
getProfileById,
getProfilesCached,
@@ -103,26 +106,6 @@ const QUERY_EVENTS_FILTER_TARGET = {
groupsExpr: 'groups',
} as const;
-// Lazy for the same reason subscription.service.ts's is: core tests that
-// partially mock `@openpanel/redis` (no `getCache`) reach this module through
-// the core barrel.
-function loadCache() {
- return import('@openpanel/redis').then((m) => m.getCache);
-}
-
-function loadFilterCompiler() {
- return import('../chart/src/table-filter-where');
-}
-
-// Lazy: session.service → session-end → this module is a static chain, and a
-// static edge back would be a plain import cycle evaluated in the wrong order.
-// Keep this the ONLY dynamic edge on that loop — a second one (e.g. session-end
-// lazily importing this module) panics rolldown when apps/worker bundles the
-// workspace (module_finalizers "no entry found for key").
-function loadSessionService() {
- return import('../session/session.service');
-}
-
export type IImportedEvent = Omit<
IClickhouseEvent,
'properties' | 'profile' | 'meta' | 'imported_at'
@@ -918,7 +901,6 @@ export async function getTopEventNames(
deps: ServiceDeps,
projectId: string
): Promise<string[]> {
- const getCache = await loadCache();
return getCache(
`mcp:event-names:${projectId}`,
TOP_EVENT_NAMES_CACHE_SECONDS,
@@ -1054,7 +1036,6 @@ export async function queryEventsCore(
): Promise<IClickhouseEvent[]> {
let filterClauses: CompiledFilterClauses = {};
if (input.filters?.length) {
- const { buildFilterWhere } = await loadFilterCompiler();
filterClauses = buildFilterWhere(
input.filters,
input.projectId,
@@ -1106,8 +1087,12 @@ export async function updateEventMeta(
});
}
+/** The session half arrives through the composition root's thunk (ADR-022 R3):
+ * `session.service` → `session-end` → this module is a static chain, so an
+ * import back would be a plain cycle evaluated in the wrong order. */
export async function getEventDetails(
deps: ServiceDeps,
+ services: () => Services,
input: {
projectId: string;
id: string;
@@ -1118,11 +1103,10 @@ export async function getEventDetails(
if (!event) {
return null;
}
- const { getSessionById } = await loadSessionService();
const session = event.sessionId
- ? await getSessionById(deps, event.sessionId, input.projectId).catch(
- () => undefined
- )
+ ? await services()
+ .session.getById(event.sessionId, input.projectId)
+ .catch(() => undefined)
: undefined;
return { event, session };
}
diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.ts
index c914fa4a3..6111dd2ab 100644
--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts
+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts
@@ -69,6 +69,7 @@ function stubJobCtx(
};
return {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
@@ -147,6 +148,7 @@ test('gscSync fans out one gscProjectSync enqueue per connected project', async
const producers = createRecordingProducers(queues);
const ctx: JobCtx = {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/src/modules/import/import.jobs.test.ts b/packages/core/src/modules/import/import.jobs.test.ts
index e47a1eb73..114d8df62 100644
--- a/packages/core/src/modules/import/import.jobs.test.ts
+++ b/packages/core/src/modules/import/import.jobs.test.ts
@@ -68,6 +68,7 @@ function stubJobCtx(
};
return {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/src/modules/import/import.service.test.ts b/packages/core/src/modules/import/import.service.test.ts
index 87415c835..959c956f0 100644
--- a/packages/core/src/modules/import/import.service.test.ts
+++ b/packages/core/src/modules/import/import.service.test.ts
@@ -148,6 +148,7 @@ test('ImportService.enqueue adds the import job onto the import queue', async ()
const service = createImportService(
{
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.ts
index 06a341f8d..f06d83644 100644
--- a/packages/core/src/modules/insight/insight.jobs.test.ts
+++ b/packages/core/src/modules/insight/insight.jobs.test.ts
@@ -73,6 +73,7 @@ function stubJobCtx(
};
return {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
@@ -134,6 +135,7 @@ test('insightsDaily fans out one insightsProject enqueue per candidate, jobId de
const producers = createRecordingProducers(queues);
const ctx: JobCtx = {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/src/modules/insight/insight.service.test.ts b/packages/core/src/modules/insight/insight.service.test.ts
index 86635187c..d0f7579bc 100644
--- a/packages/core/src/modules/insight/insight.service.test.ts
+++ b/packages/core/src/modules/insight/insight.service.test.ts
@@ -183,6 +183,7 @@ test('createInsightService binds every InsightService method', () => {
const service = subject.createInsightService(
{
db: undefined as unknown as AppDeps['db'],
+ prisma: undefined as unknown as AppDeps['prisma'],
ch: undefined as unknown as AppDeps['ch'],
redis: undefined as unknown as AppDeps['redis'],
clients: undefined as unknown as AppDeps['clients'],
diff --git a/packages/core/src/modules/insight/insight.service.ts b/packages/core/src/modules/insight/insight.service.ts
index 168a9985f..ebe85802c 100644
--- a/packages/core/src/modules/insight/insight.service.ts
+++ b/packages/core/src/modules/insight/insight.service.ts
@@ -11,9 +11,9 @@
// M10-009: every exported function takes `ServiceDeps` and reaches Postgres
// as `deps.db` and ClickHouse as `deps.ch`; the `loadDb()`/`loadCh()` lazy
// loaders are gone, so the requestId minted at the edge reaches the query
-// (ADR-018, docs/TECH_DEBT.md §4). The remaining `load*` functions are
-// intra-package lazy imports (engine, store, detection modules) kept lazy for
-// their own import cost, not for a client's.
+// (ADR-018, docs/TECH_DEBT.md §4). M15-202 removed the last five `load*`
+// functions here — engine, store, detection modules, referrer spikes and the
+// legacy detector are all plain static imports of this module's own `src/`.
//
// M12-007: the engine and its five detection modules run on the `sql` tag
// (ADR-013); `createEngine` therefore takes the scope's deps rather than a bare
@@ -27,7 +27,7 @@
import { sendEmail } from '../../clients/email';
import type { Logger } from '../../logger';
import type { ServiceDeps, Services } from '../../services';
-import type { EngineConfig } from './src/engine';
+import { createEngine, type EngineConfig } from './src/engine';
import {
ENRICH_VERSION,
enrichInsights,
@@ -38,12 +38,24 @@ import {
generateInsightExplanation,
type InsightExplanation,
} from './src/explain';
-import type { Insight as LegacyInsight } from './src/legacy-scan';
+import {
+ createLegacyInsightsScanner,
+ type Insight as LegacyInsight,
+} from './src/legacy-scan';
+import {
+ devicesModule,
+ entryPagesModule,
+ geoModule,
+ pageTrendsModule,
+ referrersModule,
+} from './src/modules';
import { generateWeeklyNarrative } from './src/narrative';
-import type {
- GetReferrerSpikesInput,
- ReferrerSpikeCluster,
+import {
+ type GetReferrerSpikesInput,
+ getReferrerSpikes as getReferrerSpikesQuery,
+ type ReferrerSpikeCluster,
} from './src/referrer-spikes';
+import { createInsightStore } from './src/store';
const DAY_MS = 24 * 60 * 60 * 1000;
const EXPLAIN_CACHE_TTL_SEC = 24 * 60 * 60;
@@ -75,26 +87,6 @@ const DEFAULT_ENGINE_CONFIG: EngineConfig = {
},
};
-function loadEngine() {
- return import('./src/engine');
-}
-
-function loadStore(deps: ServiceDeps) {
- return import('./src/store').then((m) => m.createInsightStore(deps));
-}
-
-function loadDetectionModules() {
- return import('./src/modules');
-}
-
-function loadReferrerSpikesQuery() {
- return import('./src/referrer-spikes').then((m) => m.getReferrerSpikes);
-}
-
-function loadLegacyDetector() {
- return import('./src/legacy-scan').then((m) => m.createLegacyInsightsScanner);
-}
-
export interface DailyInsightCandidate {
projectId: string;
date: string;
@@ -124,7 +116,7 @@ export async function listDailyInsightCandidates(
deps: ServiceDeps,
date: string
): Promise<DailyInsightCandidate[]> {
- const insightStore = await loadStore(deps);
+ const insightStore = createInsightStore(deps);
const projectIds = await insightStore.listProjectIdsForCadence('daily');
return projectIds.map((projectId) => ({ projectId, date }));
}
@@ -237,20 +229,15 @@ export async function runProjectInsights(
}
): Promise<void> {
const { projectId, date, logger } = args;
- const [{ createEngine }, insightStore, detectionModules] = await Promise.all([
- loadEngine(),
- loadStore(deps),
- loadDetectionModules(),
- ]);
-
+ const insightStore = createInsightStore(deps);
const engine = createEngine({
store: insightStore,
modules: [
- detectionModules.referrersModule,
- detectionModules.entryPagesModule,
- detectionModules.pageTrendsModule,
- detectionModules.geoModule,
- detectionModules.devicesModule,
+ referrersModule,
+ entryPagesModule,
+ pageTrendsModule,
+ geoModule,
+ devicesModule,
],
deps,
config: DEFAULT_ENGINE_CONFIG,
@@ -679,8 +666,7 @@ export async function getReferrerSpikes(
deps: ServiceDeps,
input: GetReferrerSpikesInput
): Promise<ReferrerSpikeCluster[]> {
- const query = await loadReferrerSpikesQuery();
- return query(deps, input);
+ return getReferrerSpikesQuery(deps, input);
}
/** Pre-engine detector, kept for parity with V1 — no live callers today. */
@@ -688,7 +674,6 @@ export async function scanLegacyInsights(
deps: ServiceDeps,
projectId: string
): Promise<LegacyInsight[]> {
- const createLegacyInsightsScanner = await loadLegacyDetector();
return createLegacyInsightsScanner(deps).generateInsights(projectId);
}
diff --git a/packages/core/src/modules/insight/src/store.ts b/packages/core/src/modules/insight/src/store.ts
index 3552504f9..a545c6813 100644
--- a/packages/core/src/modules/insight/src/store.ts
+++ b/packages/core/src/modules/insight/src/store.ts
@@ -1,8 +1,8 @@
// M10-009: the store is a FACTORY over `ServiceDeps` — `deps.db` is the boot
// scope's client, so the requestId minted at the edge reaches every insight
// write (ADR-018, docs/TECH_DEBT.md §4). `Prisma` here is the namespace's JSON
-// sentinel (`DbNull`), reached through `context.ts`'s declared seam
-// (`prismaSentinels()`) rather than by importing `@openpanel/db` from core.
+// sentinel (`DbNull`), which arrives on the same scope as `deps.prisma`
+// (M15-202) rather than by importing `@openpanel/db` from core.
import type { Prisma } from '@openpanel/db/src/prisma-client';
import type { ServiceDeps } from '../../../services';
@@ -40,16 +40,11 @@ function toPersistedInsight(row: InsightRow): PersistedInsight {
};
}
-/** `Prisma.DbNull` is a plain sentinel value that lives in the same module as
- * the constructed client — reached through `context.ts`'s seam so this file
- * value-imports nothing from `@openpanel/db`. Lazy: `context.ts`
- * value-imports `services.ts`, and this module is part of that graph. */
-function loadPrismaSentinels() {
- return import('../../../context').then((m) => m.prismaSentinels());
-}
-
export function createInsightStore(deps: ServiceDeps): InsightStore {
const db = deps.db;
+ // `Prisma.DbNull` lives in the same module as the constructed client, so it
+ // arrives on the scope (ADR-022 R6) rather than through a lazy import.
+ const { DbNull } = deps.prisma;
return {
// `cadence` isn't read — there is only one today ('daily') — but it stays
// on the signature because InsightStore's contract names it (V1 parity).
@@ -206,7 +201,6 @@ export function createInsightStore(deps: ServiceDeps): InsightStore {
changeTo,
now,
}): Promise<void> {
- const { DbNull } = await loadPrismaSentinels();
await db.insightEvent.create({
data: {
insightId,
diff --git a/packages/core/src/modules/mcp/mcp.service.test.ts b/packages/core/src/modules/mcp/mcp.service.test.ts
index 7746ca0db..efb5b0c73 100644
--- a/packages/core/src/modules/mcp/mcp.service.test.ts
+++ b/packages/core/src/modules/mcp/mcp.service.test.ts
@@ -94,6 +94,9 @@ const noopLogger = {
const deps = {
db: { project: { findUnique: mockFindUnique } },
+ // The tool runtime is handed `Prisma.DbNull` off the scope (ADR-022 R6);
+ // nothing in this suite writes a Json column, so a marker is enough.
+ prisma: { DbNull: 'DbNull', JsonNull: 'JsonNull' },
logger: noopLogger,
} as unknown as ServiceDeps;
diff --git a/packages/core/src/modules/mcp/mcp.service.ts b/packages/core/src/modules/mcp/mcp.service.ts
index c7985a885..d0c829cec 100644
--- a/packages/core/src/modules/mcp/mcp.service.ts
+++ b/packages/core/src/modules/mcp/mcp.service.ts
@@ -50,25 +50,6 @@ export interface McpHttpResult {
body: unknown;
}
-/**
- * `Prisma.DbNull` — the explicit-SQL-NULL sentinel `dashboard-management.ts`
- * writes onto a nullable Json column. A frozen CONSTANT, not a client and not
- * a service graph: nothing about it is per-request, and resolving it opens no
- * connection.
- *
- * It comes off `context.ts` because that is the ONE file in this package
- * `core-uses-ctx-not-db-internals` lets name `@openpanel/db`'s Prisma
- * namespace, and `ServiceDeps` has no field for it — the same door
- * `notification.service.ts`, `subscription.service.ts` and
- * `insight/src/store.ts` use for the same sentinel. The tool tree itself
- * reaches Postgres and ClickHouse through `deps`.
- */
-function dbJsonNull(): Promise<unknown> {
- return import('../../context').then((m) =>
- m.prismaSentinels().then((prisma) => prisma.DbNull)
- );
-}
-
/**
* Handle one stateless MCP POST request end-to-end.
*
@@ -107,7 +88,7 @@ export async function handleStatelessMcpRequest(
'method' in message && message.method === 'initialize';
const start = Date.now();
const response = await runOnEphemeralServer(
- { context, deps, dbJsonNull: await dbJsonNull(), services },
+ { context, deps, dbJsonNull: deps.prisma.DbNull, services },
message,
isInitializeRequest
);
diff --git a/packages/core/src/modules/misc/misc.service.ts b/packages/core/src/modules/misc/misc.service.ts
index 977f3cb51..5f8180eef 100644
--- a/packages/core/src/modules/misc/misc.service.ts
+++ b/packages/core/src/modules/misc/misc.service.ts
@@ -16,14 +16,13 @@
// guarded by their `.parity.test.ts` siblings). Converting the STATEMENTS is
// ADR-013's P7 work, not this wave's.
//
-// `getCache` (not `getRedisCache`) is lazy for the same reason
-// subscription.service.ts's header gives: a static `import { getCache } from
-// '@openpanel/redis'` here broke every core test that partially mocks
-// `@openpanel/redis` with no `getCache` export (e.g.
-// organization.service.test.ts, gsc.service.test.ts).
+// M15-202: `getCache` is a plain static import (ADR-022 R6). It was lazy to
+// survive core tests that partially mock `@openpanel/redis` without a
+// `getCache` export; those mocks snapshot the real module and spread it now,
+// so the loader bought nothing.
import crypto from 'node:crypto';
-import { getRedisCache } from '@openpanel/redis';
+import { getCache, getRedisCache } from '@openpanel/redis';
import {
assertPublicUrl,
BlockedUrlError,
@@ -48,10 +47,6 @@ import {
} from './src/image-proxy';
import { parseUrlMeta } from './src/parse-url-meta';
-function loadCache() {
- return import('@openpanel/redis').then((m) => m.getCache);
-}
-
const CACHE_TTL_SECONDS = 60 * 60 * 24; // 24h — binary favicon/og cache
const MAX_FETCH_BYTES = 1_000_000; // 1MB cap
const FETCH_TIMEOUT_MS = 10_000;
@@ -371,7 +366,6 @@ export interface StatsResult {
}
export async function getStats(deps: ServiceDeps): Promise<StatsResult> {
- const getCache = await loadCache();
const res = await getCache(
STATS_CACHE_KEY,
STATS_CACHE_TTL_SECONDS,
diff --git a/packages/core/src/modules/notification/notification.jobs.test.ts b/packages/core/src/modules/notification/notification.jobs.test.ts
index 5552157ba..61bee8e4f 100644
--- a/packages/core/src/modules/notification/notification.jobs.test.ts
+++ b/packages/core/src/modules/notification/notification.jobs.test.ts
@@ -68,6 +68,7 @@ function stubJobCtx(
};
return {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/src/modules/notification/notification.service.ts b/packages/core/src/modules/notification/notification.service.ts
index 81d6ab4fd..64b66cf97 100644
--- a/packages/core/src/modules/notification/notification.service.ts
+++ b/packages/core/src/modules/notification/notification.service.ts
@@ -10,11 +10,10 @@
// exported below. They are a separate file only so the enqueue side is not
// dragged into every import of this one.
//
-// db/ch access is LAZY (`load*` below), not a static top-level import — see
-// insight.service.ts's header for the full reasoning (jobs.registry.ts and
-// services.ts pull this module into the eager barrel chain nearly every core
-// test file reaches, and constructing @openpanel/db's clients at import time
-// would spawn a pino-pretty transport worker thread per test file).
+// Postgres is `deps.db` and `Prisma.DbNull` is `deps.prisma.DbNull`
+// (M15-202): nothing here imports @openpanel/db as a value, which is what
+// keeps constructing a client out of the eager barrel chain that
+// jobs.registry.ts and services.ts pull this module into.
import type { Integration, Prisma } from '@openpanel/db/src/prisma-client';
import { stripLeadingAndTrailingSlashes } from '@openpanel/shared';
@@ -37,13 +36,6 @@ import type {
IChartEventFilter,
} from '../report/report.constants';
-/** Lazy: `context.ts` value-imports `services.ts`, so a static import here
- * would put the whole service graph in this module's import graph — and this
- * module is part of that graph. */
-function loadPrismaSentinels() {
- return import('../../context').then((m) => m.prismaSentinels());
-}
-
import type { ICreateNotificationRule } from './notification.constants';
export const APP_NOTIFICATION_INTEGRATION_ID = 'app';
@@ -334,7 +326,6 @@ export async function deliverNotification(
});
const payload = notification.payload;
- const PrismaRuntime = await loadPrismaSentinels();
// Returning rather than throwing here (and in the missing-config branch
// below) resolves `notificationQueueJobs.sendNotification`'s promise
// normally, so BullMQ records the job as completed instead of failed —
@@ -345,8 +336,8 @@ export async function deliverNotification(
if (
!isValidPayload<INotificationPayload>(
payload,
- PrismaRuntime.JsonNull,
- PrismaRuntime.DbNull
+ deps.prisma.JsonNull,
+ deps.prisma.DbNull
)
) {
return new Error('Invalid payload');
diff --git a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
index 371934c7d..959aeae2f 100644
--- a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
+++ b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
@@ -69,6 +69,7 @@ function stubJobCtx(
};
return {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/src/modules/onboarding/onboarding.rpc.ts b/packages/core/src/modules/onboarding/onboarding.rpc.ts
index 3f5fcf1b3..9fafbbf8f 100644
--- a/packages/core/src/modules/onboarding/onboarding.rpc.ts
+++ b/packages/core/src/modules/onboarding/onboarding.rpc.ts
@@ -24,10 +24,6 @@ import {
createOnboardingProject,
} from './onboarding.service';
-function loadOrganizationAccess() {
- return import('../../shared/access-lookups');
-}
-
export const onboardingRouter = createTRPCRouter({
skipOnboardingCheck: publicProcedure.query(({ ctx }) =>
canSkipOnboarding(ctx, ctx.session.userId)
@@ -39,8 +35,10 @@ export const onboardingRouter = createTRPCRouter({
const userId = ctx.session.userId;
if (input.organizationId) {
- const { getOrganizationAccess } = await loadOrganizationAccess();
- const access = await getOrganizationAccess({
+ // The auth service owns every access lookup (ADR-022 R10); this
+ // procedure is protected but the organization is an input, so the
+ // builder cannot decide it.
+ const access = await ctx.services.auth.getOrganizationAccess({
userId,
organizationId: input.organizationId,
});
diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.ts
index eb742c751..0aff8e479 100644
--- a/packages/core/src/modules/onboarding/onboarding.service.ts
+++ b/packages/core/src/modules/onboarding/onboarding.service.ts
@@ -16,6 +16,7 @@ import { stripTrailingSlash } from '@openpanel/shared';
import { format } from 'date-fns';
import type { Logger } from '../../logger';
import type { ServiceDeps, Services } from '../../services';
+import { getId } from '../../slug-id';
import { hashPassword } from '../auth/auth.service';
import {
runSequence,
@@ -35,10 +36,6 @@ const TRIAL_DURATION_IN_DAYS = 30;
// "limit exceeded" (the limit defaults to 0, which trips on the first event).
const TRIAL_EVENTS_LIMIT = 10_000_000;
-function loadIdService() {
- return import('../../slug-id');
-}
-
export async function canSkipOnboarding(
deps: ServiceDeps,
userId: string | null | undefined
@@ -77,7 +74,6 @@ async function createOrGetOnboardingOrganization(
return null;
}
- const { getId } = await loadIdService();
const db = deps.db;
const organizationId = await getId(deps, 'organization', input.organization);
@@ -154,7 +150,6 @@ export async function createOnboardingProject(
cors.push('*');
}
- const { getId } = await loadIdService();
const db = deps.db;
const project = await db.project.create({
diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.ts
index 6289f7473..800f78333 100644
--- a/packages/core/src/modules/organization/organization.jobs.test.ts
+++ b/packages/core/src/modules/organization/organization.jobs.test.ts
@@ -69,6 +69,7 @@ function stubJobCtx(
};
return {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/src/modules/profile/profile.service.ts b/packages/core/src/modules/profile/profile.service.ts
index 20ae80bba..a5521ae4a 100644
--- a/packages/core/src/modules/profile/profile.service.ts
+++ b/packages/core/src/modules/profile/profile.service.ts
@@ -13,14 +13,15 @@
// M10-005: every function that touches ClickHouse or the profile buffer takes
// `ServiceDeps` and reaches them as `deps.ch` (through ch-query.ts) and
// `deps.buffers.profile`. The `loadChClient` / `loadProfileBuffer` lazy
-// loaders are gone (docs/TECH_DEBT.md §2, §4); `loadFilterCompiler` stays and
-// reaches a core sibling, not @openpanel/db.
+// loaders are gone (docs/TECH_DEBT.md §2, §4), and M15-202 made the last one
+// — the shared filter compiler — a plain static sibling import (ADR-022 R6).
import { strip, toObject } from '@openpanel/shared';
import { assocPath, flatten, map, pathOr, pipe, prop, sort, uniq } from 'ramda';
import { cacheablePerDeps } from '../../cacheable-per-deps';
import { chQuery } from '../../ch-query';
import type { ServiceDeps, Services } from '../../services';
+import { buildFilterWhere } from '../chart/src/table-filter-where';
import type { IClickhouseEvent } from '../event/event.service';
import type { IChartEventFilter } from '../report/report.constants';
import type { IClickhouseSession } from '../session/session.service';
@@ -76,10 +77,6 @@ const PROFILE_FILTER_TARGET = {
const ARRAY_INDEX_PATH_SEGMENT = /\.([0-9]+)\./g;
const ARRAY_INDEX_PATH_TAIL = /\.([0-9]+)/g;
-function loadFilterCompiler() {
- return import('../chart/src/table-filter-where');
-}
-
export interface IProfileMetrics {
lastSeen: Date | null;
firstSeen: Date | null;
@@ -186,7 +183,6 @@ async function compileProfileFilters(
if (!filters?.length) {
return {};
}
- const { buildFilterWhere } = await loadFilterCompiler();
return buildFilterWhere(filters, projectId, PROFILE_FILTER_TARGET);
}
diff --git a/packages/core/src/modules/realtime/realtime.service.ts b/packages/core/src/modules/realtime/realtime.service.ts
index 4542b8778..a20de0353 100644
--- a/packages/core/src/modules/realtime/realtime.service.ts
+++ b/packages/core/src/modules/realtime/realtime.service.ts
@@ -37,7 +37,10 @@
// `realtime.sql.proof.md` beside this file.
import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';
-import type { IPublishChannels } from '@openpanel/redis';
+import {
+ type IPublishChannels,
+ subscribeToPublishedEvent,
+} from '@openpanel/redis';
import { subMinutes } from 'date-fns';
import { chQuery } from '../../ch-query';
import type { ServiceDeps, Services } from '../../services';
@@ -470,18 +473,6 @@ export function getRealtimeGeo(deps: ServiceDeps, projectId: string) {
// Framework-agnostic: resolve to an unsubscribe function each, exactly
// `subscribeToPublishedEvent`'s own shape. realtime.routes.ts (Elysia/Bun)
// awaits these directly; nothing here is HTTP- or ws-library-specific.
-//
-// `@openpanel/redis` is LAZY here for its own reason: it has no
-// import-time side effect (its
-// clients connect lazily on first use — insight.service.ts already imports
-// `getRedisCache` from it statically), but several modules' tests replace the
-// whole package with `mock.module('@openpanel/redis', () => ({ subset }))`.
-// A new static named import here would demand `subscribeToPublishedEvent` on
-// every one of those subsets the moment this module joins the eager barrel
-// chain (rpc.router.ts), breaking tests this task does not own.
-function loadRedis() {
- return import('@openpanel/redis');
-}
export function getActiveVisitorCount(
deps: ServiceDeps,
@@ -495,7 +486,6 @@ export async function subscribeToVisitorActivity(
projectId: string,
onActivity: () => void
): Promise<() => void> {
- const { subscribeToPublishedEvent } = await loadRedis();
return subscribeToPublishedEvent('events', 'batch', (event) => {
if (event.projectId === projectId) {
onActivity();
@@ -508,7 +498,6 @@ export async function subscribeToProjectEventBatches(
projectId: string,
onBatch: (event: IPublishChannels['events']['batch']) => void
): Promise<() => void> {
- const { subscribeToPublishedEvent } = await loadRedis();
return subscribeToPublishedEvent('events', 'batch', (event) => {
if (event.projectId === projectId) {
onBatch(event);
@@ -523,7 +512,6 @@ export async function subscribeToProjectNotifications(
notification: IPublishChannels['notification']['created']
) => void
): Promise<() => void> {
- const { subscribeToPublishedEvent } = await loadRedis();
return subscribeToPublishedEvent(
'notification',
'created',
@@ -541,7 +529,6 @@ export async function subscribeToOrganizationSubscriptionUpdates(
message: IPublishChannels['organization']['subscription_updated']
) => void
): Promise<() => void> {
- const { subscribeToPublishedEvent } = await loadRedis();
return subscribeToPublishedEvent(
'organization',
'subscription_updated',
diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.ts
index 2f46991fb..3e6d914d2 100644
--- a/packages/core/src/modules/session/session.service.ts
+++ b/packages/core/src/modules/session/session.service.ts
@@ -21,6 +21,7 @@ import { getSafeJson, resolveDateRange } from '@openpanel/shared';
import { cacheablePerDeps } from '../../cacheable-per-deps';
import { chQuery } from '../../ch-query';
import type { ServiceDeps, Services } from '../../services';
+import { buildFilterWhere } from '../chart/src/table-filter-where';
import type { IServiceProfile } from '../profile/profile.service';
import type { IChartEventFilter } from '../report/report.constants';
import { convertClickhouseDateToJs } from './src/dates';
@@ -47,10 +48,6 @@ export {
type SessionDistinctField,
} from './src/sql';
-function loadFilterCompiler() {
- return import('../chart/src/table-filter-where');
-}
-
export interface IClickhouseSession {
id: string;
profile_id: string;
@@ -217,7 +214,6 @@ async function compileSessionFilters(
if (!filters?.length) {
return {};
}
- const { buildFilterWhere } = await loadFilterCompiler();
return buildFilterWhere(filters, projectId, {
...SESSION_FILTER_TABLE,
...range,
@@ -502,5 +498,15 @@ export function createSessionService(
);
}
- return { enqueueSessionEnd };
+ /** `event.service.ts` reaches this through the composition root's thunk
+ * (ADR-022 R3): `session-end.ts` statically imports the event module, so
+ * the two are a real cycle and an import back would be the wrong answer. */
+ function getById(
+ sessionId: string,
+ projectId: string
+ ): ReturnType<typeof getSessionById> {
+ return getSessionById(deps, sessionId, projectId);
+ }
+
+ return { enqueueSessionEnd, getById };
}
diff --git a/packages/core/src/modules/session/src/usage.ts b/packages/core/src/modules/session/src/usage.ts
index bef1aa3a4..733c3f758 100644
--- a/packages/core/src/modules/session/src/usage.ts
+++ b/packages/core/src/modules/session/src/usage.ts
@@ -7,18 +7,8 @@ import type { Organization } from '@openpanel/db/src/prisma-client';
import { cacheablePerDeps } from '../../../cacheable-per-deps';
import { sendEmail } from '../../../clients/email';
import type { ServiceDeps } from '../../../services';
-
-// The two project counters stay a DYNAMIC import: jobs.registry.ts reaches
-// this file (session.jobs.ts -> session-end -> usage), and a static edge to
-// project.service.ts pulls a ClickHouse client into the registry's import
-// graph, which breaks the offline contract
-// verification/golden/queue-keys/check.sh depends on.
-function loadCounters() {
- return Promise.all([
- import('../../project/project.service'),
- import('../../organization/organization.service'),
- ]);
-}
+import { getOrganizationBillingEventsCount } from '../../organization/organization.service';
+import { getProjectEventsCount } from '../../project/project.service';
const INT4_MAX = 2_147_483_647;
const USAGE_WARNING_THRESHOLD = 0.8;
@@ -64,8 +54,6 @@ export const updateEventsCount = cacheablePerDeps(
return;
}
- const [{ getProjectEventsCount }, { getOrganizationBillingEventsCount }] =
- await loadCounters();
const organizationEventsCount = await getOrganizationBillingEventsCount(
deps,
organization
diff --git a/packages/core/src/modules/subscription/subscription.service.ts b/packages/core/src/modules/subscription/subscription.service.ts
index 7575594f0..f804e4771 100644
--- a/packages/core/src/modules/subscription/subscription.service.ts
+++ b/packages/core/src/modules/subscription/subscription.service.ts
@@ -13,10 +13,9 @@
//
// M10-004: every function takes `ServiceDeps` and reaches Postgres as
// `deps.db`; the `loadDb()`/`loadPrisma()` lazy loaders are gone.
-// `Prisma.DbNull` (the JSON-column null sentinel) has no home on `deps` — it
-// is a plain value on the namespace, not the client — so it is reached
-// through `context.ts`'s `prismaSentinels()` instead of importing
-// `@openpanel/db` here.
+// M15-202: `Prisma.DbNull` (the JSON-column null sentinel) arrives as
+// `deps.prisma` — the app shell puts the two sentinels on `AppDeps` — rather
+// than through a lazy import back into `context.ts`.
import {
applySubscriptionDiscount,
@@ -52,13 +51,6 @@ import {
zCancellationReason,
} from './subscription.constants';
-/** Lazy: `context.ts` value-imports `services.ts`, so a static import here
- * would put the whole service graph in this module's import graph — and this
- * module is part of that graph. */
-function loadPrismaSentinels() {
- return import('../../context').then((m) => m.prismaSentinels());
-}
-
const POLAR_PRODUCTS_CACHE_KEY = 'polar:products';
const POLAR_PRODUCTS_CACHE_TTL_SECONDS = 60 * 60 * 24;
const DEFAULT_USAGE_WINDOW_DAYS = 30;
@@ -554,7 +546,7 @@ async function syncSubscriptionToOrg(
);
}
- const { DbNull } = await loadPrismaSentinels();
+ const { DbNull } = deps.prisma;
const updateData = {
subscriptionId: data.id,
diff --git a/packages/core/src/modules/widget/widget.rpc.ts b/packages/core/src/modules/widget/widget.rpc.ts
index 440e59019..de87578d6 100644
--- a/packages/core/src/modules/widget/widget.rpc.ts
+++ b/packages/core/src/modules/widget/widget.rpc.ts
@@ -13,10 +13,9 @@
//
// M10-009: Postgres and ClickHouse come from `ctx` (`ctx.db` / `ctx.ch`), so
// the requestId minted at the edge reaches the query (ADR-018); the `loadDb`/
-// `loadChClient` lazy loaders are gone. Redis's `getCache` stays lazy: this
-// router lands in the eager rpc.router.ts barrel chain nearly every core test
-// file reaches and reaching @openpanel/redis at import time breaks a test that
-// partially mocks that package — see subscription.service.ts's header.
+// `loadChClient` lazy loaders are gone, and M15-202 made `getCache` a plain
+// static import too (ADR-022 R6) — the spelling subscription.service.ts,
+// modules/ingest/src/client-auth.ts and modules/mcp/src/auth.ts already use.
//
// M12-008: the five ClickHouse statements moved off clix onto the ADR-013
// `sql` tag. The conversion changes how values reach the server and nothing
@@ -34,6 +33,7 @@
// holding no client and no request scope (see ch-query.ts).
import { sql } from '@openpanel/db/src/clickhouse/sql';
+import { getCache } from '@openpanel/redis';
import ShortUniqueId from 'short-unique-id';
import { z } from 'zod';
import { chQuery } from '../../ch-query';
@@ -56,10 +56,6 @@ const EVENTS_TABLE = sql.id(TABLE_NAMES.events);
/** `clix.exp('now() - INTERVAL 30 MINUTE')`, parenthesised as clix rendered it. */
const REALTIME_WINDOW = sql`created_at >= (now() - INTERVAL 30 MINUTE)`;
-function loadCache() {
- return import('@openpanel/redis').then((m) => m.getCache);
-}
-
// Helper to find widget by projectId and type
async function findWidgetByType(
db: Ctx['db'],
@@ -221,7 +217,6 @@ export const widgetRouter = createTRPCRouter({
const { projectId } = widget;
const { timezone } = await getSettingsForProject(ctx, projectId);
- const getCache = await loadCache();
// Cache for 5 minutes since this queries 30 days of data
const cacheKey = `widget:badge:${projectId}`;
diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts
index 55e2f0f2b..35b0e3ef1 100644
--- a/packages/core/src/services.ts
+++ b/packages/core/src/services.ts
@@ -43,7 +43,15 @@ import { createUserService } from './modules/user/user.service';
/** What every service factory receives — derived from Ctx, so it cannot drift. */
export type ServiceDeps = Pick<
Ctx,
- 'db' | 'ch' | 'redis' | 'clients' | 'buffers' | 'logger' | 'queues' | 'config'
+ | 'db'
+ | 'prisma'
+ | 'ch'
+ | 'redis'
+ | 'clients'
+ | 'buffers'
+ | 'logger'
+ | 'queues'
+ | 'config'
>;
// Two type rules the compiler enforces but cannot explain:
diff --git a/packages/core/test/http-fixtures.ts b/packages/core/test/http-fixtures.ts
index ed93d4aef..67727b86f 100644
--- a/packages/core/test/http-fixtures.ts
+++ b/packages/core/test/http-fixtures.ts
@@ -40,6 +40,7 @@ export function stubAppDeps(): AppDepsStub {
childCalls: () => childCalls,
deps: {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/test/request-id-end-to-end.test.ts b/packages/core/test/request-id-end-to-end.test.ts
index eb57d12a6..c063fd15d 100644
--- a/packages/core/test/request-id-end-to-end.test.ts
+++ b/packages/core/test/request-id-end-to-end.test.ts
@@ -182,6 +182,7 @@ function stubDeps() {
const deps: AppDeps = {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
@@ -363,6 +364,7 @@ function chartDeps() {
const producers = createRecordingProducers({});
const deps: AppDeps = {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: chartClickHouse(),
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
@@ -545,6 +547,7 @@ function ingestDeps() {
} as unknown as Buffers;
const deps: AppDeps = {
+ prisma: {} as AppDeps['prisma'],
db: {
project: {
// M15-005: the handler reads the project through
@@ -722,3 +725,240 @@ test('a second message is scoped to its own id, and an envelope without one stil
expect(minted).not.toBe(INGEST_REQUEST_ID);
expect(minted).not.toBe(INGEST_OTHER_REQUEST_ID);
});
+
+// ===========================================================================
+// Section 4 — one request, one id, all six hops (ADR-022 A3, M15-202).
+// ===========================================================================
+//
+// Sections 1-3 each prove a segment: 1 the HTTP -> job chain through a
+// MOCKED service, 2 a real converted read path with no job behind it, 3 the
+// Kafka edge. A3 names the property Carl actually asked for — "follow what
+// has happened for a certain request, and see the entire flow" — as one
+// chain, and the hops it lists are:
+//
+// requestId minted at the edge
+// -> ctx
+// -> a service's bound logger
+// -> producers.scope({ requestId })
+// -> the { payload, meta } envelope
+// -> the job's child logger
+//
+// Nothing below is a stand-in for a hop. The read path is
+// `ctx.services.chart.getRetentionSeries`, a REAL converted service reaching
+// ClickHouse through `deps.ch`; the enqueue is
+// `ctx.services.cohort.enqueueCompute`, a REAL service writing onto
+// `ctx.queues`; the envelope is what `wrap` produces from what the recording
+// producer captured; and the job is the REAL `cohortCompute` definition and
+// the REAL handler off `jobs.registry.ts`, which reaches ClickHouse again —
+// so the last hop is a converted read path INSIDE a job, observed on its own
+// `query info` line.
+//
+// Only the two connections are stubs, and both are the seam under test: the
+// ClickHouse client records what it was asked and the Postgres client answers
+// one row. A `load*` loader anywhere on this path, a client that built its
+// own logger, or a handler that reached past `ctx` breaks exactly one of the
+// assertions below and names itself.
+
+const CHAIN_REQUEST_ID = 'adr022-a3-one-request';
+const CHAIN_PROJECT_ID = 'chain-project';
+const CHAIN_COHORT_ID = 'chain-cohort';
+
+function chainDeps() {
+ const lines: CapturedLine[] = [];
+ const queried: string[] = [];
+ const commanded: string[] = [];
+ const inserted: string[] = [];
+ // The real registry, so the enqueue below goes through the real
+ // `cohortCompute` producer and is validated against the real payload schema.
+ const producers = createRecordingProducers(queues);
+
+ const ch = {
+ query: (params: { query: string }) => {
+ queried.push(params.query);
+ return Promise.resolve({
+ json: () => Promise.resolve({ data: [], rows: 0, meta: [] }),
+ });
+ },
+ command: (params: { query: string }) => {
+ commanded.push(params.query);
+ return Promise.resolve({});
+ },
+ insert: (params: { table: string }) => {
+ inserted.push(params.table);
+ return Promise.resolve({});
+ },
+ } as unknown as AppDeps['ch'];
+
+ const deps: AppDeps = {
+ db: {
+ cohort: {
+ findUnique: () =>
+ Promise.resolve({
+ id: CHAIN_COHORT_ID,
+ projectId: CHAIN_PROJECT_ID,
+ definition: {
+ type: 'property',
+ criteria: {
+ operator: 'and',
+ properties: [
+ { name: 'country', operator: 'is', value: ['US'] },
+ ],
+ },
+ },
+ }),
+ update: () => Promise.resolve({}),
+ },
+ } as unknown as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
+ ch,
+ redis: {} as AppDeps['redis'],
+ clients: {} as AppDeps['clients'],
+ buffers: {} as Buffers,
+ producers: producers as unknown as QueueProducerHandle,
+ logger: bindingLogger(lines),
+ config: testCoreConfig(),
+ };
+
+ return {
+ deps,
+ lines,
+ queried,
+ commanded,
+ inserted,
+ recorded: producers.recorded,
+ };
+}
+
+/** The route: a converted read path, then a real service's enqueue. */
+function buildChainApp(deps: AppDeps) {
+ const routes = defineRoutes((app) =>
+ app.post('/proof/chain', async ({ ctx }) => {
+ await ctx.services.chart.getRetentionSeries({
+ projectId: CHAIN_PROJECT_ID,
+ });
+ await ctx.services.cohort.enqueueCompute(CHAIN_COHORT_ID);
+ return { ok: true };
+ })
+ );
+ return new Elysia().use(requestLogging(deps)).use(routes(deps));
+}
+
+/** Every `query info` line, with the requestId its logger was bound to. */
+function queryLineIds(lines: CapturedLine[]): unknown[] {
+ return lines
+ .filter((line) => line.message === 'query info')
+ .map((line) => line.bindings.requestId);
+}
+
+test('one requestId reaches a converted read path, a real enqueue, the envelope and the job that runs it', async () => {
+ const { deps, lines, queried, commanded, inserted, recorded } = chainDeps();
+
+ const response = await buildChainApp(deps).handle(
+ new Request('http://localhost/proof/chain', {
+ method: 'POST',
+ headers: { [REQUEST_ID_HEADER]: CHAIN_REQUEST_ID },
+ })
+ );
+ await settled();
+
+ expect(response.status).toBe(200);
+
+ // Hop 3: a REAL service's ClickHouse call really ran, and its own log line
+ // carries the request's id. A silent miss here would leave every assertion
+ // below trivially true (AGENTS.md).
+ expect(queried).toHaveLength(1);
+ expect(queried[0]).toContain('FROM events');
+ expect(queryLineIds(lines)).toEqual([CHAIN_REQUEST_ID]);
+
+ // Hops 4 and 5: `producers.scope({ requestId })` stamped the envelope the
+ // real `cohort` service enqueued.
+ const enqueued = recorded.find(({ queue }) => queue === 'cohortCompute');
+ if (!enqueued) {
+ throw new Error('the route enqueued no cohortCompute job');
+ }
+ expect(enqueued.job).toBe('cohortCompute');
+ expect(enqueued.payload).toEqual({ cohortId: CHAIN_COHORT_ID });
+ expect(enqueued.meta.requestId).toBe(CHAIN_REQUEST_ID);
+
+ // Hop 6: the REAL job, off the REAL registry definition, reading the REAL
+ // envelope — and the converted read path it makes in turn.
+ const queriesBeforeJob = queried.length;
+ await runJob(
+ queues.cohortCompute,
+ {
+ id: 'job_chain_1',
+ name: enqueued.job,
+ data: wrap(enqueued.payload, enqueued.meta),
+ attemptsMade: 0,
+ },
+ deps
+ );
+
+ // The handler reached ClickHouse through `ctx.ch`, not a client of its own:
+ // one more read, plus the membership DELETE and the metadata write that
+ // `updateCohortMembership` makes on the same handle.
+ expect(queried.length).toBeGreaterThan(queriesBeforeJob);
+ expect(commanded.join('\n')).toContain('DELETE FROM');
+ expect(inserted).toContain('cohort_metadata');
+
+ // Every `query info` line in the process — the route's and the job's — is
+ // the same request. This is the assertion A3 exists for.
+ const allQueryIds = queryLineIds(lines);
+ expect(allQueryIds.length).toBeGreaterThan(1);
+ expect(new Set(allQueryIds)).toEqual(new Set([CHAIN_REQUEST_ID]));
+
+ // And the job's child logger carries the job identity alongside it, so a
+ // log search on the id shows the request AND what it caused.
+ const jobLine = lines.find(
+ (line) => line.message === 'query info' && line.bindings.job !== undefined
+ );
+ expect(jobLine?.bindings).toMatchObject({
+ requestId: CHAIN_REQUEST_ID,
+ queue: 'cohortCompute',
+ job: 'cohortCompute',
+ jobId: 'job_chain_1',
+ attempt: 1,
+ });
+});
+
+test('a job whose envelope carries no requestId is scoped to a fresh one, not to the last request', async () => {
+ const { deps, lines, recorded } = chainDeps();
+
+ await buildChainApp(deps).handle(
+ new Request('http://localhost/proof/chain', {
+ method: 'POST',
+ headers: { [REQUEST_ID_HEADER]: CHAIN_REQUEST_ID },
+ })
+ );
+ await settled();
+
+ const enqueued = recorded.find(({ queue }) => queue === 'cohortCompute');
+ if (!enqueued) {
+ throw new Error('the route enqueued no cohortCompute job');
+ }
+
+ const linesBefore = lines.length;
+ // What a scheduler enqueues: a payload with no originating request
+ // (ADR-018 R2).
+ await runJob(
+ queues.cohortCompute,
+ {
+ id: 'job_chain_2',
+ name: enqueued.job,
+ data: wrap(enqueued.payload, {}),
+ attemptsMade: 0,
+ },
+ deps
+ );
+
+ const jobIds = lines
+ .slice(linesBefore)
+ .filter((line) => line.message === 'query info')
+ .map((line) => line.bindings.requestId);
+
+ expect(jobIds.length).toBeGreaterThan(0);
+ for (const id of jobIds) {
+ expect(id).toBeString();
+ expect(id).not.toBe(CHAIN_REQUEST_ID);
+ }
+});
diff --git a/packages/core/test/rpc-fixtures.ts b/packages/core/test/rpc-fixtures.ts
index 5830dc1a7..cdb50366c 100644
--- a/packages/core/test/rpc-fixtures.ts
+++ b/packages/core/test/rpc-fixtures.ts
@@ -89,6 +89,7 @@ export function stubHttpCtx(
const deps: AppDeps = {
db: {} as AppDeps['db'],
+ prisma: {} as AppDeps['prisma'],
ch: {} as AppDeps['ch'],
redis: {} as AppDeps['redis'],
clients: {} as AppDeps['clients'],
diff --git a/packages/core/test/service-deps.ts b/packages/core/test/service-deps.ts
index 81376674e..d472387f4 100644
--- a/packages/core/test/service-deps.ts
+++ b/packages/core/test/service-deps.ts
@@ -50,13 +50,14 @@ export function testServices(): () => Services {
export async function testServiceDeps(
overrides: Partial<ServiceDeps> = {}
): Promise<ServiceDeps> {
- const [{ db }, { ch }, redis] = await Promise.all([
+ const [{ db, Prisma }, { ch }, redis] = await Promise.all([
import('@openpanel/db/src/prisma-client'),
import('@openpanel/db/src/clickhouse/client'),
import('@openpanel/redis').then((m) => m.getRedisCache()),
]);
return {
db,
+ prisma: { DbNull: Prisma.DbNull, JsonNull: Prisma.JsonNull },
ch,
redis,
logger: recordingLogger(),
diff --git a/tooling/gates/conformance/conformance.constants.ts b/tooling/gates/conformance/conformance.constants.ts
index 93e75c83d..434852abc 100644
--- a/tooling/gates/conformance/conformance.constants.ts
+++ b/tooling/gates/conformance/conformance.constants.ts
@@ -108,6 +108,17 @@ export const RESIDUE_PATTERNS: readonly { label: string; pattern: RegExp }[] = [
* R15 — constructors that open a connection or build a client. A `new` of one
* of these, or a call to one of the factory names, at MODULE scope is the
* violation; inside a factory body it is exactly what core is supposed to do.
+ *
+ * The name matched is the CONSTRUCTED one, however it is spelled: `new
+ * GitHub(...)` and `new Arctic.Google(...)` are the same construction, and a
+ * checker that only looked at bare identifiers could not see the second one at
+ * all (CONFORMANCE_PLAN.md §1l). `checkModuleScopeConstruction` resolves a
+ * qualified `new A.B.C()` down to `C` before looking it up here.
+ *
+ * The OAuth clients (`arctic`) are credential holders rather than sockets, so
+ * nothing about them has to be closed — but they are built from config and
+ * they are exactly what R15 means by "the app constructs": one at module scope
+ * would freeze a deployment's client id and secret into the import graph.
*/
export const CONNECTION_CONSTRUCTOR_NAMES = new Set([
'Redis',
@@ -121,6 +132,10 @@ export const CONNECTION_CONSTRUCTOR_NAMES = new Set([
'Worker',
'QueueEvents',
'WebSocket',
+ // arctic's OAuth clients: modules/auth/src/oauth.ts builds all three per
+ // call, from `config.auth.*`.
+ 'GitHub',
+ 'Google',
]);
export const CONNECTION_FACTORY_NAME_PATTERN =
/^create(?:[A-Z][A-Za-z]*)?(?:Client|Connection|Redis|Db|Pool)$/;
diff --git a/tooling/gates/conformance/rules.test.ts b/tooling/gates/conformance/rules.test.ts
index 00aea9a0a..5a70730ed 100644
--- a/tooling/gates/conformance/rules.test.ts
+++ b/tooling/gates/conformance/rules.test.ts
@@ -22,6 +22,7 @@ import {
checkCreateServicesCallSites,
checkDependencyLoaders,
checkFactorySignatures,
+ checkModuleScopeConstruction,
checkServicesMembers,
collectEnvReads,
} from './rules';
@@ -235,3 +236,54 @@ const c = process.env['BRACKETED'];
expect(grepped).toBe(2);
});
});
+
+describe('R15 — the two constructor spellings modules/auth/src/oauth.ts uses', () => {
+ // Both arctic clients, both correct: built per call, from config. The bug
+ // M15-202 fixed was the checker, not this file — `GitHub` was not in the
+ // constructor set and `Arctic.Google` is a property access an
+ // `ts.isIdentifier` guard cannot see at all (CONFORMANCE_PLAN.md §1l).
+ const oauthShape = `
+import * as Arctic from 'arctic';
+import { GitHub } from 'arctic';
+
+export function githubClient(config: CoreConfig): GitHub {
+ return new GitHub(config.id, config.secret, config.redirect);
+}
+
+export function googleClient(config: CoreConfig): Arctic.Google {
+ return new Arctic.Google(config.id, config.secret, config.redirect);
+}
+`;
+
+ test('inside a factory body, neither is a violation', () => {
+ const source = parseSource(
+ 'packages/core/src/modules/auth/src/oauth.ts',
+ oauthShape
+ );
+ expect(checkModuleScopeConstruction([source]).count).toBe(0);
+ });
+
+ test('a connection nested in another constructor still counts', () => {
+ const source = parseSource(
+ 'packages/core/src/buffers/event-buffer.ts',
+ 'const buffer = new Wrapper(new Redis(url));\n'
+ );
+ expect(checkModuleScopeConstruction([source]).count).toBe(1);
+ });
+
+ test('at module scope, BOTH are — the qualified one included', () => {
+ const source = parseSource(
+ 'packages/core/src/modules/auth/src/oauth.ts',
+ `
+const github = new GitHub(id, secret, redirect);
+const google = new Arctic.Google(id, secret, redirect);
+`
+ );
+ const metric = checkModuleScopeConstruction([source]);
+ expect(metric.count).toBe(2);
+ expect(metric.offenders.map((offender) => offender.detail)).toEqual([
+ 'new GitHub( at module scope',
+ 'new Arctic.Google( at module scope',
+ ]);
+ });
+});
diff --git a/tooling/gates/conformance/rules.ts b/tooling/gates/conformance/rules.ts
index 2e02b70c2..0428f6348 100644
--- a/tooling/gates/conformance/rules.ts
+++ b/tooling/gates/conformance/rules.ts
@@ -543,6 +543,25 @@ export function checkResidue(files: ResidueScanInput[]): Metric[] {
// --- R15 ----------------------------------------------------------------------
+/**
+ * The name a `new` expression actually constructs, however it is qualified.
+ *
+ * `new GitHub(...)` is an identifier; `new Arctic.Google(...)` is a property
+ * access, and an `ts.isIdentifier` guard cannot see it at all — the checker
+ * would walk straight past a namespace-imported client
+ * (CONFORMANCE_PLAN.md §1l). Both spellings construct the same thing, so both
+ * resolve to the rightmost name here.
+ */
+function constructedName(expression: ts.Expression): string | undefined {
+ if (ts.isIdentifier(expression)) {
+ return expression.text;
+ }
+ if (ts.isPropertyAccessExpression(expression)) {
+ return expression.name.text;
+ }
+ return undefined;
+}
+
/**
* R15 — core declares, the app constructs. Nothing in core opens a socket,
* connection or client at import time.
@@ -559,17 +578,18 @@ export function checkModuleScopeConstruction(sources: ParsedSource[]): Metric {
if (!isAtModuleScope(node)) {
return;
}
- if (
- ts.isNewExpression(node) &&
- ts.isIdentifier(node.expression) &&
- CONNECTION_CONSTRUCTOR_NAMES.has(node.expression.text)
- ) {
- offenders.push({
- file: source.path,
- line: lineOf(source, node.getStart(source.sourceFile)),
- detail: `new ${node.expression.text}( at module scope`,
- });
- return;
+ if (ts.isNewExpression(node)) {
+ const constructed = constructedName(node.expression);
+ if (constructed && CONNECTION_CONSTRUCTOR_NAMES.has(constructed)) {
+ offenders.push({
+ file: source.path,
+ line: lineOf(source, node.getStart(source.sourceFile)),
+ detail: `new ${node.expression.getText(source.sourceFile)}( at module scope`,
+ });
+ // Only a MATCH stops the walk: `new Wrapper(new Redis())` must
+ // still reach the inner construction.
+ return;
+ }
}
if (
ts.isCallExpression(node) &&