OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M15-005): R6/R15: v1-compat.ts deleted - 2,104 lines, 331 exports, 71 importers - with the five class-(c) exports rehomed rather than dropped
ralph136cbb49da08
diff --git a/apps/api/e2e/lib.ts b/apps/api/e2e/lib.tsindex d3927321b..78a3f4256 100644--- a/apps/api/e2e/lib.ts+++ b/apps/api/e2e/lib.ts@@ -4,7 +4,7 @@* fixtures, polling, and a tiny check/report framework.*/-import { clearClientByIdCache } from '@openpanel/core';+import { getClientByIdCached } from '@openpanel/core';import { ClientType, chQuery, db } from '@openpanel/db';import { getRedisCache } from '@openpanel/redis';@@ -261,7 +261,7 @@ export async function ensureFixtures() {},update: { ignoreCorsAndSecret: true, projectId: PROJECT_ID },});- await clearClientByIdCache(CLIENT_ID);+ await getClientByIdCached.clear({ db }, CLIENT_ID);check('fixtures ready', true);} catch (error) {check('fixtures ready', false, (error as Error).message);diff --git a/apps/api/src/main.ts b/apps/api/src/main.tsindex d8af2b7e2..0f21de482 100644--- a/apps/api/src/main.ts+++ b/apps/api/src/main.ts@@ -40,7 +40,6 @@ import {bullBoardRoutes,COOKIE_OPTIONS,checkNotificationRulesForEvent,- clearProjectByIdCache,corsDelegator,createBuffers,createClients,@@ -53,7 +52,6 @@ import {debugRoutes,enableEventsHeartbeat,errorHandler,- getProjectByIdCached,type HttpCtx,ingestConsumerMetrics,KAFKA_EVENTS_TOPIC,@@ -79,12 +77,10 @@ import {requestLogging,type SessionMetricsRedis,setShuttingDown,- setV1CompatServices,startKafkaEventsConsumer,startSchedulers,startWorkers,TRPC_ENDPOINT,- V1_COMPAT_REQUEST_ID,type WorkerHandle,} from '@openpanel/core';import { ch } from '@openpanel/db/src/clickhouse/client';@@ -249,26 +245,6 @@ function warnOnUnhandledSchedulers(schedulerIds: string[]): void {}}-/**- * The boot scope as `ServiceDeps`. `AppDeps` carries a `QueueProducerHandle`;- * a service wants an already-scoped `QueueProducers`, and outside a request- * there is nothing to correlate with, so the boot scope stamps- * `V1_COMPAT_REQUEST_ID` (M10-005).- */-function bootServiceDeps(- deps: AppDeps-): Parameters<typeof setV1CompatServices>[0] {- return {- db: deps.db,- ch: deps.ch,- redis: deps.redis,- clients: deps.clients,- buffers: deps.buffers,- logger: deps.logger,- queues: deps.producers.scope({ requestId: V1_COMPAT_REQUEST_ID }),- };-}-/*** The Kafka events consumer. The kafkajs client, the topic, the consumer* group, the DLQ producer and the retry bounds all come from core's own@@ -289,14 +265,11 @@ async function startIngestConsumer(partitionsConsumedConcurrently: KAFKA_PARTITIONS_CONCURRENT,batch: {// One Ctx per message, scoped to the requestId the producer stamped- // into the envelope (M10-006). The two bindings a work scope cannot- // supply are resolved here, once: the notification dispatch has no Ctx- // slot in its signature, and the project cache is the boot-registered- // singleton ingest/http/mcp share.+ // into the envelope (M10-006). The one binding a work scope cannot+ // supply is resolved here, once: the notification dispatch has no Ctx+ // slot in its signature.handleEvent: createIncomingEventHandler(deps, {checkNotificationRulesForEvent,- getCachedProject: getProjectByIdCached,- clearProjectCache: clearProjectByIdCache,}),sendToDeadLetter: produceDeadLetterEvent,logger,@@ -486,13 +459,6 @@ async function main() {const role = config.ROLE;const deps = buildDeps();- // The V1 compat seam (core/src/v1-compat.ts): `packages/trpc`'s routers and- // the mcp/assistant tool runtimes reach core's modules as bare barrel- // exports with no `Ctx`, so the deps built above are registered once here- // for them. Everything with a `Ctx` uses `ctx.services.*`. Deleted with- // `packages/trpc` at P10.- setV1CompatServices(bootServiceDeps(deps));-// HTTP and default metrics register everywhere (TARGET_ARCHITECTURE §18).registerDefaultMetrics();if (roleConsumes) {diff --git a/packages/core/src/buffers/base-buffer.ts b/packages/core/src/buffers/base-buffer.tsindex 3032e04ca..81a490165 100644--- a/packages/core/src/buffers/base-buffer.ts+++ b/packages/core/src/buffers/base-buffer.ts@@ -25,7 +25,7 @@ export interface BufferDeps {* a second client (and a second pino transport) outside any scope. M15-004* made it required: the one caller that had none* (`apps/api/e2e/legacy-job-proof.ts`, a BullMQ-keys-only proof that never- * flushes to ClickHouse) already passes the field, so the v1-compat fallback+ * flushes to ClickHouse) already passes the field, so the unscoped fallback* behind it had no live path left.*/ch: ServiceDeps['ch'];diff --git a/packages/core/src/context.ts b/packages/core/src/context.tsindex 7e464bf4a..e0209440c 100644--- a/packages/core/src/context.ts+++ b/packages/core/src/context.ts@@ -25,6 +25,42 @@ export type RedisClient = ReturnType<>;export type ServiceClients = import('./clients/create-clients').ServiceClients;+// The two `@openpanel/db` VALUES core cannot reach through a scope, and the+// one file allowed to name them: `core-uses-ctx-not-db-internals` exempts+// this module by path, and it is already where core declares its handles.+// Both are LAZY, so importing core still constructs no database and+// `bun test` still runs offline, and neither memoizes its result — the module+// registry already caches the import, and a second memo is exactly what let+// the deleted compat seam hand one suite's mocked Prisma client to every+// later file in the process.++export type PrismaNamespace =+ typeof import('@openpanel/db/src/prisma-client').Prisma;++/**+ * 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.+ */+export function prismaSentinels(): Promise<PrismaNamespace> {+ return import('@openpanel/db/src/prisma-client').then((m) => m.Prisma);+}++/**+ * The process's Postgres client, for the one path that cannot be handed a+ * scope: `shared/access-lookups.ts`. Its lookups are `cacheable` on their+ * ARGUMENTS, so they cannot take a leading `deps`, and their bare signature is+ * pinned by the protected wire contract+ * `verification/contracts/auth/group-b-project-access.mts`, which imports them+ * through `packages/db/src/services/access.service.ts` with no app boot at+ * all. It is the same client `main.ts` puts on `AppDeps.db`. Every other+ * caller in core reaches Postgres as `deps.db`.+ */+export function unscopedDb(): Promise<Db> {+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);+}+// Landed at M8-001: built once by `createBuffers(deps)` in main.ts, never a// module singleton.export type { Buffers } from './buffers/create-buffers';diff --git a/packages/core/src/http/auth.ts b/packages/core/src/http/auth.tsindex d13612ae7..d467eb2dd 100644--- a/packages/core/src/http/auth.ts+++ b/packages/core/src/http/auth.ts@@ -70,7 +70,7 @@ export function authMacros(deps: AppDeps) {clientAuth: (options: ClientAuthOptions) => ({async resolve({ body, ctx, status }) {const result = await authenticateClient(- deps,+ ctx,toIngestHeaders(ctx.headers),options,{ ip: ctx.ip, body }diff --git a/packages/core/src/http/client-auth.ts b/packages/core/src/http/client-auth.tsindex 021641f24..ce9d97deb 100644--- a/packages/core/src/http/client-auth.ts+++ b/packages/core/src/http/client-auth.ts@@ -15,19 +15,13 @@// below. MCP is NOT here — it authenticates its own `token` form inside// `modules/mcp/src/auth.ts`, exactly as V1's mcp router did.-import type { AppDeps } from '../context';+import type { HttpCtx } from '../context';import {type IngestHeaders,validateIngestRequest,} from '../modules/ingest/src/client-auth';import { headerValue } from '../modules/ingest/src/headers';import { verifyPassword } from '../shared/crypto';-// M10-004: `getClientByIdCached`'s L1 LRU now lives inside-// `createClientService(deps)` (see that file's header), reached here through-// the v1-compat singleton, exactly as `modules/ingest/src/client-auth.ts`-// does — no cycle for THIS file (nothing under `modules/*.service.ts`-// imports `http/**`), so the import stays static.-import { getClientByIdCached } from '../v1-compat';/** V1 refuses a client id that is not a UUID before it ever queries* (utils/auth.ts's three validators). Same regex, same order. */@@ -91,17 +85,25 @@ export interface ClientAuthRequest {body: unknown;}+/**+ * M15-005: takes the request's own `Ctx`, not the boot scope. The ingest tier+ * reads only `ctx.db` — `getClientByIdCached`'s L1 is keyed on the Postgres+ * client, so `/track` reaches the one process-lived cache without forcing+ * `ctx.services`. The allow-list tier is not a hot path and goes through+ * `ctx.services.client` like every other handler.+ */export async function authenticateClient(- _deps: AppDeps,+ ctx: HttpCtx,headers: IngestHeaders,options: ClientAuthOptions,request?: ClientAuthRequest): Promise<ClientAuthResult> {if (!options.ingest) {- return await authenticateAllowedClient(headers, options);+ return await authenticateAllowedClient(ctx, headers, options);}const outcome = await validateIngestRequest({+ deps: ctx,headers,clientIp: request?.ip,body: request?.body,@@ -146,6 +148,7 @@ const UNEXPECTED_MESSAGE = 'Unexpected error';* secret, so reaching the return means one was presented and matched.*/async function authenticateAllowedClient(+ ctx: HttpCtx,headers: IngestHeaders,options: ClientAuthOptions): Promise<ClientAuthResult> {@@ -164,7 +167,7 @@ async function authenticateAllowedClient(}try {- const client = await getClientByIdCached(clientId);+ const client = await ctx.services.client.getClientByIdCached(clientId);if (!client) {return refuse(`${label}: Invalid client id`);}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex b3110e71c..19ae4c5a8 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -394,7 +394,11 @@ export type {IServiceClient,IServiceClientWithProject,} from './modules/client/client.service';-export { createClientService } from './modules/client/client.service';+export {+ createClientService,+ // apps/api's session e2e clears one client's cache between runs.+ getClientByIdCached,+} from './modules/client/client.service';// Dissolved from @openpanel/db's services/cohort.service.ts (M5-003) —// packages/trpc's cohort router and apps/worker's cohort job files call// these directly, the same way V1 reaches every other dissolved service@@ -874,9 +878,7 @@ export {// apps/worker/src/jobs/cron.salt.ts (M8-004) — `main.ts` calls// `createInitialSalts(deps)` directly at boot; `salt.jobs.ts`'s cron handler// and everything else reach `rotateSalt`/`getSalts` through-// `ctx.services.salt` / the v1-compat singleton instead (M10-004, see-// salt.service.ts's header — `getSalts` is the one export still bare here,-// for the same reason it's bare on the v1-compat seam).+// `ctx.services.salt`.export type { Salts } from './modules/salt/salt.service';export {createInitialSalts,@@ -1089,137 +1091,3 @@ export {safeFetchStream,} from './shared/safe-fetch';export { assertSafeUrl, createPinnedLookup } from './shared/ssrf';-// What is left of the V1 compat seam (v1-compat.ts). M15-004 deleted its 204-// deps-threading wrappers — every caller passes the `ServiceDeps` it already-// holds now — so what remains here is the sibling-service half, which needs a-// service graph rather than a connection and dies with R3's `services()`-// accessor, plus `compatDb` / `compatPrisma` / `compatChHelpers`. See that-// file's header for why each of the three is still standing.-export {- AggregateChartEngine,- applySaveDiscount,- buildFunnelBase,- ChartEngine,- cancelProjectDeletion,- cancelSubscription,- checkout,- clearClientByIdCache,- clearProjectByIdCache,- compatDb,- createClientForOrganization,- createDashboard,- createProjectForOrganization,- createReference,- createReport,- createShareDashboard,- createShareOverview,- createShareReport,- deleteClientForOrganization,- deleteConversation,- deleteDashboard,- deleteProjectForOrganization,- deleteReference,- deleteReport,- deleteUserAccount,- duplicateReport,- executeAggregateChart,- executeChart,- getChartBucketProfiles,- getChartPropertyValues,- getChartReferences,- getClientById,- getClientByIdCached,- getClientForOrganization,- getClientsByOrganizationId,- getClientsByProjectId,- getConversationById,- getConversion,- getConversionChart,- getDashboardById,- getDashboardByIdOrThrow,- getDashboardsByProjectId,- getEngagementCore,- getFunnel,- getFunnelChart,- getFunnelCore,- getFunnelProfileIds,- getFunnelStepProfiles,- getLastEventPerProject,- getProjectActivationStatus,- getProjectById,- getProjectByIdCached,- getProjectCard,- getProjectEventsCount,- getProjectForOrganization,- getProjects,- getProjectWithClients,- getReferenceById,- getReferenceByIdOrThrow,- getReportById,- getReportByIdOrThrow,- getReportDataCore,- getReportLayouts,- getReportsByDashboardId,- getRetentionChart,- getRetentionCohort,- getRetentionCohortCore,- getRetentionLastSeenSeries,- getRetentionSeries,- getRollingActiveUsers,- getRollingActiveUsersCore,- getSalts,- getSankey,- getSankeyChart,- getShareByProjectId,- getShareDashboard,- getShareDashboardByDashboardId,- getShareDashboardById,- getShareDashboardReports,- getShareDashboardSettings,- getShareOverview,- getShareOverviewById,- getShareOverviewSettings,- getShareReport,- getShareReportById,- getShareReportByReportId,- getShareReportSettings,- getUsage,- getUserAccount,- getUserById,- getUserFlowCore,- getWeeklyRetentionSeriesCore,- listChartEvents,- listChartProperties,- listClientsForOrganization,- listConversations,- listDashboardsCore,- listProducts,- listProjectsCore,- listProjectsForOrganization,- listReferences,- listReportsCore,- listUserDeletionBlockers,- moveReport,- overviewService,- pagesService,- pauseSubscription,- portal,- resetReportLayouts,- resetV1CompatServicesForTests,- resolveClientProjectId,- resumeSubscription,- scheduleProjectDeletion,- setV1CompatServices,- updateClientForOrganization,- updateDashboard,- updateProjectForOrganization,- updateReference,- updateReport,- updateReportLayout,- updateUserProfile,- upsertConversationTitle,- V1_COMPAT_REQUEST_ID,- validateOverviewShareAccess,- validateReportAccess,- validateShareAccess,-} from './v1-compat';diff --git a/packages/core/src/modules/auth/auth.service.access.test.ts b/packages/core/src/modules/auth/auth.service.access.test.tsindex 7bcd00c51..b95f04a12 100644--- a/packages/core/src/modules/auth/auth.service.access.test.ts+++ b/packages/core/src/modules/auth/auth.service.access.test.ts@@ -1,11 +1,10 @@// M10-002 (docs/TECH_DEBT.md §5b): auth.service.ts is now the ONLY place// `shared/access.ts`'s ladder is bound to real lookups, via the lazy,// memoized `getAccessChecks()`. This proves that seam still takes a fake-// `AccessLookups` cleanly — mocking `../../shared/access-lookups` and-// `../project/project.service` (both reached only through dynamic imports by-// auth.service.ts, never statically) instead of a per-module `src/access.ts`-// copy — and that ADR-011's fail-closed ordering, messages and write-level-// gate are unchanged.+// `AccessLookups` cleanly — mocking `../../shared/access-lookups`, which+// auth.service.ts reaches only through a dynamic import and which owns all+// four lookups since M15-005 — and that ADR-011's fail-closed ordering,+// messages and write-level gate are unchanged.import { afterAll, beforeAll, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';@@ -29,19 +28,15 @@ const getProjectById = mock(async () => projectById);// Snapshotted BEFORE `mock.module` below, not after — restoring by// re-`import`ing later would resolve the already-mocked registry entry, not// the real module (bare `bun test` shares one module registry across every-// file, and both of these are reached by plenty of other modules —-// client.rpc.ts, project.rpc.ts, integration.service.ts, ...).+// file, and this one is reached by plenty of other modules — client.rpc.ts,+// project.rpc.ts, integration.service.ts, ...).const realAccessLookups = { ...(await import('../../shared/access-lookups')) };-const realProjectService = { ...(await import('../project/project.service')) };mock.module('../../shared/access-lookups', () => ({...realAccessLookups,getProjectAccess,getOrganizationAccess,canWriteProject,-}));-mock.module('../project/project.service', () => ({- ...realProjectService,getProjectById,}));@@ -55,7 +50,6 @@ beforeAll(async () => {afterAll(() => {mock.module('../../shared/access-lookups', () => realAccessLookups);- mock.module('../project/project.service', () => realProjectService);// `getAccessChecks()` memoizes for the life of the process — clear it so a// later file in this bare run rebuilds against the real lookups just// restored above, not this file's fakes.diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex 411bb50c7..b13898379 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -13,10 +13,7 @@// password-reset/OAuth-callback all take `deps` now and reach Postgres as// `deps.db`; `./src/login-session.ts` and `./src/registration.ts` do the// same and are plain static imports here (neither cycles back to this file).-// `packages/trpc`'s still-live router calls every one of these bare (no-// `ServiceDeps`); those reach `createServices` through the v1-compat-// singleton instead (see v1-compat.ts's header) — `auth.rpc.ts` already-// carries a `Ctx` and passes it straight through.+// `auth.rpc.ts` already carries a `Ctx` and passes it straight through.import { z } from 'zod';import type { ServiceDeps, Services } from '../../services';@@ -101,24 +98,18 @@ let accessChecksPromise: Promise<ProjectAccessChecks> | undefined;* attempt bound this at module scope and hung `bun test` for 30 minutes.** `integration.service.ts` and `subscription.service.ts` import this- * directly instead of going through `ctx.services.auth`: both are invoked by- * `packages/trpc`'s still-live V1 delegate routers with a bare `userId`, no- * `ctx`, so they cannot reach a service. Operator-authorized (docs/TECH_DEBT.md- * §5b); the exemption expires when `packages/trpc` dies at P10.+ * directly instead of going through `ctx.services.auth`: both are called with+ * a bare `userId` and no `ctx`. Operator-authorized (docs/TECH_DEBT.md §5b).*/export function getAccessChecks(): Promise<ProjectAccessChecks> {if (!accessChecksPromise) {- accessChecksPromise = Promise.all([- loadAccessLookups(),- // project.service.ts's own `getProjectById` takes `ServiceDeps` now- // (M10-004) — this singleton has none, so it reaches the bare,- // v1-compat-wrapped spelling instead (see that file's header).- import('../../v1-compat'),- ]).then(- ([- { getProjectAccess, canWriteProject, getOrganizationAccess },- { getProjectById },- ]) =>+ accessChecksPromise = loadAccessLookups().then(+ ({+ getProjectAccess,+ canWriteProject,+ getOrganizationAccess,+ getProjectById,+ }) =>createAccessChecks({getProjectAccess,canWriteProject,diff --git a/packages/core/src/modules/chart/src/chart.sql.test.ts b/packages/core/src/modules/chart/src/chart.sql.test.tsindex bb645cd40..22ea2af44 100644--- a/packages/core/src/modules/chart/src/chart.sql.test.ts+++ b/packages/core/src/modules/chart/src/chart.sql.test.ts@@ -42,13 +42,6 @@ mock.module('@openpanel/db/src/prisma-client', () => ({afterAll(async () => {mock.module('@openpanel/db/src/prisma-client', () => realPrismaClient);- // Restoring the module registry is not enough: `v1-compat.ts` MEMOIZES the- // fallback `ServiceDeps` the first time anything resolves it, so if that- // happened while the mock above was installed, every later FILE in this- // process keeps the mocked client (bare `bun test` shares one registry).- // Drop the memo too — same reason mcp's dashboard-management.test.ts does.- const { resetV1CompatServicesForTests } = await import('../../../v1-compat');- resetV1CompatServicesForTests();});let ch: typeof import('@openpanel/db/src/clickhouse/client').ch;diff --git a/packages/core/src/modules/chart/src/funnel.sql.test.ts b/packages/core/src/modules/chart/src/funnel.sql.test.tsindex db975396b..99b211b40 100644--- a/packages/core/src/modules/chart/src/funnel.sql.test.ts+++ b/packages/core/src/modules/chart/src/funnel.sql.test.ts@@ -42,13 +42,6 @@ mock.module('@openpanel/db/src/prisma-client', () => ({afterAll(async () => {mock.module('@openpanel/db/src/prisma-client', () => realPrismaClient);- // Restoring the module registry is not enough: `v1-compat.ts` MEMOIZES the- // fallback `ServiceDeps` the first time anything resolves it, so if that- // happened while the mock above was installed, every later FILE in this- // process keeps the mocked client (bare `bun test` shares one registry).- // Drop the memo too — same reason mcp's dashboard-management.test.ts does.- const { resetV1CompatServicesForTests } = await import('../../../v1-compat');- resetV1CompatServicesForTests();});let ch: typeof import('@openpanel/db/src/clickhouse/client').ch;diff --git a/packages/core/src/modules/client/client.service.ts b/packages/core/src/modules/client/client.service.tsindex d3ada79d4..456e27b46 100644--- a/packages/core/src/modules/client/client.service.ts+++ b/packages/core/src/modules/client/client.service.ts@@ -16,20 +16,17 @@// invalidation) — project-ownership checks below query `db.project`// directly, matching V1's manage.controller.ts exactly.//-// `getClientByIdCached` lives INSIDE `createClientService(deps)` rather than-// at module scope: its `cacheable(...)` L1 LRU must survive across calls to-// stay useful, which only holds if the closure it is built in is a-// singleton. `ctx.services.client` is one Ctx per request, so this cache is-// only actually a cross-call singleton through the v1-compat seam-// (`registered`, built exactly once at boot) — see v1-compat.ts's header —-// which is what `ingest/src/client-auth.ts`, `http/client-auth.ts` and-// `mcp/src/auth.ts` read through, on the ingest hot path, with no `Ctx` of-// their own to carry `ServiceDeps`.+// M15-005: `getClientByIdCached` is a module-scope `cacheablePerDb`, keyed on+// the Postgres client rather than on the scope. Its L1 LRU has to survive+// across calls to be worth anything, and the ingest hot path+// (`ingest/src/client-auth.ts`, `http/client-auth.ts`) now passes the scope it+// holds instead of reading a boot-scoped singleton through the deleted compat+// seam. One instance per process to read, one to invalidate.import crypto from 'node:crypto';import type { Client, Prisma } from '@openpanel/db/src/prisma-client';-import { cacheable } from '@openpanel/redis';import type { ServiceDeps, Services } from '../../services';+import { cacheablePerDb, type DbScope } from '../../shared/cacheable-per-deps';import { hashPassword } from '../auth/auth.service';export type IServiceClient = Client;@@ -71,7 +68,7 @@ export async function getClientsByProjectId(}export async function getClientById(- deps: ServiceDeps,+ deps: DbScope,id: string): Promise<IServiceClientWithProject | null> {return deps.db.client.findUnique({@@ -82,6 +79,21 @@ export async function getClientById(});}+/**+ * L1 LRU (60s) + L2 Redis, one instance per Postgres client. `clear()`+ * invalidates Redis and that LRU; other nodes may serve stale from theirs for+ * up to 60s.+ *+ * The name is EMPTY on purpose: the in-factory `cacheable(...)` this replaces+ * was handed an anonymous arrow, so `fn.name` was `''` and the Redis key is+ * `cachable::<id>`. Naming it here would orphan every live entry.+ */+export const getClientByIdCached = cacheablePerDb(+ '',+ getClientById,+ FIVE_MINUTES_IN_SECONDS+);+// --- /manage REST CRUD (apps/api/src/controllers/manage.controller.ts) ---export async function listClientsForOrganization(@@ -131,12 +143,6 @@ export function createClientService(deps: ServiceDeps,_services: () => Services) {- /** L1 LRU (60s) + L2 Redis. clear() invalidates Redis + local LRU; other nodes may serve stale from LRU for up to 60s. */- const getClientByIdCached = cacheable(- (id: string) => getClientById(deps, id),- FIVE_MINUTES_IN_SECONDS- );-async function createClientForOrganization(organizationId: string,input: {@@ -165,7 +171,7 @@ export function createClientService(},});- await getClientByIdCached.clear(client.id);+ await getClientByIdCached.clear(deps, client.id);return { client, secret };}@@ -193,7 +199,7 @@ export function createClientService(data: updateData,});- await getClientByIdCached.clear(client.id);+ await getClientByIdCached.clear(deps, client.id);return client;}@@ -211,7 +217,7 @@ export function createClientService(}await deps.db.client.delete({ where: { id } });- await getClientByIdCached.clear(id);+ await getClientByIdCached.clear(deps, id);return true;}@@ -229,13 +235,14 @@ export function createClientService(getClientById(deps, id),getClientByIdCached: (id: string- ): Promise<IServiceClientWithProject | null> => getClientByIdCached(id),+ ): Promise<IServiceClientWithProject | null> =>+ getClientByIdCached(deps, id),/** Invalidates a single id in `getClientByIdCached`'s L1 LRU + Redis. Its- * own create/update/delete already call this; `project.service.ts`- * reaches it too, through the v1-compat singleton, to invalidate a- * project's clients on a project mutation — see that file's header. */+ * own create/update/delete already call this; `project.service.ts` calls+ * the module-scope spelling to invalidate a project's clients on a+ * project mutation. */clearClientByIdCache: (id: string): Promise<number> =>- getClientByIdCached.clear(id),+ getClientByIdCached.clear(deps, id),listClientsForOrganization: (organizationId: string,projectId?: stringdiff --git a/packages/core/src/modules/export/export.routes.ts b/packages/core/src/modules/export/export.routes.tsindex e2255a0c1..572bfdddf 100644--- a/packages/core/src/modules/export/export.routes.ts+++ b/packages/core/src/modules/export/export.routes.ts@@ -353,7 +353,7 @@ const zOverviewGenericQuerystring = zGetTopPagesQuery;type OverviewGenericQuery = z.infer<typeof zOverviewGenericQuerystring>;type InsightsProjectParam = z.infer<typeof projectIdParam>;-type InsightsClient = Parameters<typeof resolveInsightsProjectId>[0];+type InsightsClient = Parameters<typeof resolveInsightsProjectId>[1];/** Shared body of the 18 `overviewColumns` routes below (V1's `getOverviewGeneric(column)`). */async function getOverviewGeneric(@@ -363,7 +363,7 @@ async function getOverviewGeneric(query: OverviewGenericQuery,client: InsightsClient) {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { timezone } = await getSettingsForProject(ctx, projectId);const { startDate, endDate } = getChartStartEndDate(query, timezone);return ctx.services.overview.getTopGeneric({@@ -542,7 +542,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/overview',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -569,7 +569,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/active_users',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return ctx.services.chart.getRollingActiveUsersCore({projectId,days: query.days,@@ -588,7 +588,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/retention',async ({ params, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return ctx.services.chart.getWeeklyRetentionSeriesCore(projectId);},{@@ -603,7 +603,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/retention/cohort',async ({ params, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return ctx.services.chart.getRetentionCohortCore(projectId);},{@@ -618,7 +618,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/pages/top',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -640,7 +640,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/pages/entry_exit',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -666,7 +666,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/pages/performance',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -693,7 +693,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/metrics',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { timezone } = await getSettingsForProject(ctx, projectId);const { startDate, endDate } = getChartStartEndDate(query, timezone);return ctx.services.overview.getMetrics({@@ -719,7 +719,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/live',async ({ params, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return {visitors: await ctx.buffers.event.getActiveVisitorCount(projectId),};@@ -736,7 +736,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/pages',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { timezone } = await getSettingsForProject(ctx, projectId);const { startDate, endDate } = getChartStartEndDate(query, timezone);return ctx.services.overview.getTopPages({@@ -1013,7 +1013,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/funnel',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1041,7 +1041,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/traffic/referrers',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1067,7 +1067,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/traffic/geo',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1094,7 +1094,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/traffic/devices',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1120,7 +1120,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/user_flow',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1147,7 +1147,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/engagement',async ({ params, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return ctx.services.chart.getEngagementCore(projectId);},{@@ -1162,7 +1162,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/events',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return queryEventsCore(ctx, { projectId, ...query });},{@@ -1179,7 +1179,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/events/names',async ({ params, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return listEventNamesCore(ctx, projectId);},{@@ -1194,7 +1194,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/events/properties',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return listEventPropertiesCore(ctx, {projectId,eventName: query.eventName,@@ -1213,7 +1213,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/events/property_values',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return getEventPropertyValuesCore(ctx, { projectId, ...query });},{@@ -1229,7 +1229,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/profiles',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return findProfilesCore(ctx, { projectId, ...query });},{@@ -1245,7 +1245,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/profiles/:profileId',async ({ params, query, client, status, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const result = await getProfileWithEvents(ctx,projectId,@@ -1273,7 +1273,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/profiles/:profileId/sessions',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return getProfileSessionsCore(ctx,projectId,@@ -1294,7 +1294,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/profiles/:profileId/metrics',async ({ params, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return getProfileMetricsCore(ctx, {projectId,profileId: params.profileId,@@ -1312,7 +1312,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/sessions',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return querySessionsCore(ctx, { projectId, ...query });},{@@ -1328,7 +1328,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/groups/types',async ({ params, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return listGroupTypesCore(ctx, projectId);},{@@ -1343,7 +1343,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/groups',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return findGroupsCore(ctx, { projectId, ...query });},{@@ -1359,7 +1359,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/groups/:groupId',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return getGroupCore(ctx, {projectId,groupId: params.groupId,@@ -1379,7 +1379,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/reports/:reportId/data',async ({ params, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);return ctx.services.report.getReportDataCore({projectId,reportId: params.reportId,@@ -1398,7 +1398,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/gsc/overview',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1425,7 +1425,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/gsc/pages',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1451,7 +1451,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/gsc/pages/details',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1477,7 +1477,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/gsc/queries',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1503,7 +1503,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/gsc/queries/details',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1529,7 +1529,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/gsc/queries/opportunities',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,@@ -1556,7 +1556,7 @@ export const insightsRoutes = defineRoutes((app) =>.get('/insights/:projectId/gsc/cannibalization',async ({ params, query, client, ctx }) => {- const projectId = await resolveInsightsProjectId(client, params);+ const projectId = await resolveInsightsProjectId(ctx, client, params);const { startDate, endDate } = await resolveInsightsDateRange(ctx,projectId,diff --git a/packages/core/src/modules/export/export.service.ts b/packages/core/src/modules/export/export.service.tsindex 6fe81ee6b..c1b805488 100644--- a/packages/core/src/modules/export/export.service.ts+++ b/packages/core/src/modules/export/export.service.ts@@ -17,18 +17,9 @@ import type { AuthenticatedClient } from '../../http/client-auth';import type { ServiceDeps, Services } from '../../services';import { getChartStartEndDate, resolveDateRange } from '../../shared/date';import { getSettingsForProject } from '../organization/organization.service';+import { resolveClientProjectId } from '../project/project.service';import type { IChartRange } from '../report/report.constants';-// project.service.ts's `resolveClientProjectId` takes `ServiceDeps` now-// (M10-004); `resolveInsightsProjectId` below is called from ~35 route-// handlers in export.routes.ts with no `deps` in their own signature, so it-// reaches the bare, v1-compat-wrapped spelling instead of threading `deps`-// through every one of them. GENUINE CYCLE, kept lazy: services.ts ->-// export.service.ts (this file) -> v1-compat.ts -> services.ts.-function loadProjectService() {- return import('../../v1-compat');-}-export type ProjectIdResolution =| { ok: true; projectId: string }| { ok: false; status: 400 | 403 | 404; message: string };@@ -85,11 +76,11 @@ export async function resolveExportProjectId(* 12), already what apps/api's insights.controller.ts `getProjectId` calls.*/export async function resolveInsightsProjectId(+ deps: ServiceDeps,client: AuthenticatedClient,params: { projectId?: string }): Promise<string> {- const { resolveClientProjectId } = await loadProjectService();- return resolveClientProjectId({+ return resolveClientProjectId(deps, {clientType: client.type === 'root' ? 'root' : 'read',clientProjectId: client.projectId,organizationId: client.organizationId,diff --git a/packages/core/src/modules/import/import.service.test.ts b/packages/core/src/modules/import/import.service.test.tsindex cb0603991..e11f67e86 100644--- a/packages/core/src/modules/import/import.service.test.ts+++ b/packages/core/src/modules/import/import.service.test.ts@@ -2,8 +2,7 @@// file hands in fakes as `deps.db` / `deps.ch` and mocks NO module at all.// That is the point of the conversion: a module mock of// `@openpanel/db/src/clickhouse/client` replaced that specifier for every-// other FILE in the process (bare `bun test` shares one module registry), and-// the v1-compat seam memoizes whatever it resolved while one was installed.+// other FILE in the process (bare `bun test` shares one module registry).import { beforeAll, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';diff --git a/packages/core/src/modules/ingest/ingest.routes.ts b/packages/core/src/modules/ingest/ingest.routes.tsindex 2959ea68b..3b108c804 100644--- a/packages/core/src/modules/ingest/ingest.routes.ts+++ b/packages/core/src/modules/ingest/ingest.routes.ts@@ -200,6 +200,7 @@ export const ingestRoutes = defineRoutes((app, deps: AppDeps) =>'/track/device-id',async ({ client, ctx, status }) => {const identity = await fetchDeviceIdentity(+ ctx,{projectId: client.projectId,clientIp: ctx.ip,diff --git a/packages/core/src/modules/ingest/ingest.service.test.ts b/packages/core/src/modules/ingest/ingest.service.test.tsindex 12b2f6ecd..62c97d709 100644--- a/packages/core/src/modules/ingest/ingest.service.test.ts+++ b/packages/core/src/modules/ingest/ingest.service.test.ts@@ -42,7 +42,7 @@ const getAsnInfo = mock(async () => ({org: undefined,isHosting: false,}));-const getSalts = mock(async () => ({+const getSalts = mock(async (_deps: unknown) => ({current: 'salt-current',previous: 'salt-previous',}));@@ -62,11 +62,10 @@ let ingestTrack: typeof import('./ingest.service').ingestTrack;// path off Postgres and the profile buffer — profile.service calls its own// local `upsertProfile`, not the exported binding.//-// M10-004: ingest.service.ts reaches `getSalts` through the v1-compat-// singleton (salt.service.ts's own cache now lives inside-// `createSaltService(deps)`, not at module scope — see both files' headers),-// so that's the specifier mocked here, spread-actual like the rest.-let realV1Compat: typeof import('../../v1-compat');+// M15-005: ingest.service.ts calls salt.service.ts's module-scope `getSalts`+// with the scope it holds, so that is the specifier mocked here,+// spread-actual like the rest.+let realSaltService: typeof import('../salt/salt.service');beforeAll(async () => {const profile = await import('../profile/profile.service');mock.module('../profile/profile.service', () => ({@@ -75,15 +74,18 @@ beforeAll(async () => {upsertProfile,getProfileById,}));- realV1Compat = { ...(await import('../../v1-compat')) };- mock.module('../../v1-compat', () => ({ ...realV1Compat, getSalts }));+ realSaltService = { ...(await import('../salt/salt.service')) };+ mock.module('../salt/salt.service', () => ({+ ...realSaltService,+ getSalts,+ }));({ getOverrideDeviceId, handleReplay, ingestTrack } = await import('./ingest.service'));});afterAll(() => {- mock.module('../../v1-compat', () => realV1Compat);+ mock.module('../salt/salt.service', () => realSaltService);});const track = (properties?: Record<string, unknown>): ITrackHandlerPayload =>diff --git a/packages/core/src/modules/ingest/ingest.service.ts b/packages/core/src/modules/ingest/ingest.service.tsindex c7cc879db..2f2ab2cb5 100644--- a/packages/core/src/modules/ingest/ingest.service.ts+++ b/packages/core/src/modules/ingest/ingest.service.ts@@ -25,6 +25,7 @@ import {} from '../../clients/geo';import type { Logger } from '../../logger';import type { ServiceDeps, Services } from '../../services';+import type { DbScope } from '../../shared/cacheable-per-deps';import { generateId } from '../../shared/id';import { parseUserAgent } from '../../shared/parser-user-agent';import { generateDeviceId } from '../../shared/profileId';@@ -35,21 +36,7 @@ import {identifyProfile,upsertProfile,} from '../profile/profile.service';--// M10-004: salt.service.ts's `getSalts` moved inside `createSaltService(deps)`-// so its LRU survives across calls; this hot path has no `Ctx` to reach-// `ctx.services.salt` from, so it reads the v1-compat singleton instead — see-// v1-compat.ts's header and salt.service.ts's. GENUINE CYCLE, kept lazy:-// services.ts -> ingest.service.ts (this file) -> v1-compat.ts -> services.ts;-// the dynamic import is what keeps it a cycle ESM can evaluate, same as-// auth.service.ts's `loadShare()`.-function loadSalt() {- return import('../../v1-compat');-}-function getSalts() {- return loadSalt().then((m) => m.getSalts());-}-+import { getSalts } from '../salt/salt.service';import { convertClickhouseDateToJs } from '../session/src/dates';import type {DeprecatedPostEventPayload,@@ -241,6 +228,7 @@ export type TrackOutcome =| { status: 'profile-property-not-a-number' };async function buildContext(+ deps: DbScope,request: TrackRequest,buffers: IngestBuffers): Promise<TrackContext> {@@ -268,7 +256,7 @@ async function buildContext(const [geo, asnInfo, salts] = await Promise.all([getGeoLocation(ip),getAsnInfo(ip),- getSalts(),+ getSalts(deps),]);const deviceIdResult = await getDeviceId({@@ -478,7 +466,11 @@ export async function ingestTrack(return { status: 'missing-project-id' };}- const context = await buildContext(request, transport.buffers);+ const context = await buildContext(+ transport.deps,+ request,+ transport.buffers+ );switch (body.type) {case 'track':@@ -656,7 +648,7 @@ export async function ingestLegacyEvent(const headers = getStringHeaders(request.headers);const [salts, geo, asnInfo] = await Promise.all([- getSalts(),+ getSalts(transport.deps),getGeoLocation(ip),getAsnInfo(ip),]);@@ -714,6 +706,7 @@ export type DeviceIdentity =/** `GET /track/device-id`. */export async function fetchDeviceIdentity(+ deps: DbScope,request: {projectId: string | null | undefined;clientIp: string | undefined;@@ -722,7 +715,7 @@ export async function fetchDeviceIdentity(buffers: Pick<IngestBuffers, 'session'>,logger: Logger): Promise<DeviceIdentity> {- const salts = await getSalts();+ const salts = await getSalts(deps);const projectId = request.projectId;if (!projectId) {return { status: 'missing-project-id' };diff --git a/packages/core/src/modules/ingest/legacy-event.test.ts b/packages/core/src/modules/ingest/legacy-event.test.tsindex 96b30aa66..054f3ee3d 100644--- a/packages/core/src/modules/ingest/legacy-event.test.ts+++ b/packages/core/src/modules/ingest/legacy-event.test.ts@@ -52,7 +52,7 @@ const getAsnInfo = mock(async () => ({org: 'Example ISP',isHosting: false,}));-const getSalts = mock(async () => ({+const getSalts = mock(async (_deps: unknown) => ({current: 'salt-current',previous: 'salt-previous',}));@@ -61,20 +61,21 @@ mock.module('../../clients/geo', () => ({ getGeoLocation, getAsnInfo }));let ingestLegacyEvent: typeof import('./ingest.service').ingestLegacyEvent;-// M10-004: ingest.service.ts reaches `getSalts` through the v1-compat-// singleton now (salt.service.ts's own cache moved inside-// `createSaltService(deps)` — see both files' headers), so that's the-// specifier mocked here, spread-actual like everywhere else this seam is-// overridden.-let realV1Compat: typeof import('../../v1-compat');+// M15-005: ingest.service.ts calls salt.service.ts's module-scope `getSalts`+// with the scope it holds, so that is the specifier mocked here —+// spread-actual like everywhere else this module is overridden.+let realSaltService: typeof import('../salt/salt.service');beforeAll(async () => {- realV1Compat = { ...(await import('../../v1-compat')) };- mock.module('../../v1-compat', () => ({ ...realV1Compat, getSalts }));+ realSaltService = { ...(await import('../salt/salt.service')) };+ mock.module('../salt/salt.service', () => ({+ ...realSaltService,+ getSalts,+ }));({ ingestLegacyEvent } = await import('./ingest.service'));});afterAll(() => {- mock.module('../../v1-compat', () => realV1Compat);+ mock.module('../salt/salt.service', () => realSaltService);});const produced: { payload: IncomingEventPayload; partitionKey: string }[] = [];diff --git a/packages/core/src/modules/ingest/src/client-auth.test.ts b/packages/core/src/modules/ingest/src/client-auth.test.tsindex a8a498018..b92ad65af 100644--- a/packages/core/src/modules/ingest/src/client-auth.test.ts+++ b/packages/core/src/modules/ingest/src/client-auth.test.ts@@ -38,23 +38,25 @@ const client = {},};-const getClientByIdCached = mock(async (_id: string) => client);--// M10-004: client-auth.ts reaches `getClientByIdCached` through the-// v1-compat singleton now (its own header explains why) — mocked at that-// specifier, spread-actual so the rest of the seam (`createServices` et al.,-// which `services.ts`'s own import of `client.service.ts` still needs) stays-// intact.-const realV1Compat = { ...(await import('../../../v1-compat')) };-mock.module('../../../v1-compat', () => ({- ...realV1Compat,+const getClientByIdCached = mock(async (_deps: unknown, _id: string) => client);++// M15-005: client-auth.ts takes the caller's scope and reads+// `client.service.ts`'s module-scope `cacheablePerDb` — mocked at that+// specifier, spread-actual so the rest of the module (which `services.ts`'s+// own import of it still needs) stays intact.+const realClientService = { ...(await import('../../client/client.service')) };+mock.module('../../client/client.service', () => ({+ ...realClientService,getClientByIdCached,}));afterAll(() => {- mock.module('../../../v1-compat', () => realV1Compat);+ mock.module('../../client/client.service', () => realClientService);});+/** Only `db` is read on this path, and only as the cache's identity. */+const deps = { db: {} } as unknown as import('../../../services').ServiceDeps;+let validateIngestRequest: typeof import('./client-auth').validateIngestRequest;beforeAll(async () => {@@ -70,6 +72,7 @@ const body = { name: 'legacy_event', properties: { foo: 'bar' } };describe('validateIngestRequest', () => {it('authenticates a client sent as mixan-client-id (ADR-015 entry 5 deferred)', async () => {const result = await validateIngestRequest({+ deps,headers: {'mixan-client-id': CLIENT_ID,'mixan-client-secret': 'legacy-secret',@@ -78,13 +81,14 @@ describe('validateIngestRequest', () => {body,});- expect(getClientByIdCached).toHaveBeenCalledWith(CLIENT_ID);+ expect(getClientByIdCached).toHaveBeenCalledWith(deps, CLIENT_ID);expect(result.ok && result.client.id).toBe(CLIENT_ID);expect(result.secretPresented).toBe(true);});it('accepts the openpanel-* headers and reports no secret when none was sent', async () => {const result = await validateIngestRequest({+ deps,headers: { 'openpanel-client-id': CLIENT_ID },clientIp: '203.0.113.10',body,@@ -96,6 +100,7 @@ describe('validateIngestRequest', () => {it('falls back to the credentials carried in the body', async () => {const result = await validateIngestRequest({+ deps,headers: {},clientIp: '203.0.113.10',body: { ...body, clientId: CLIENT_ID, clientSecret: 'from-body' },@@ -109,6 +114,7 @@ describe('validateIngestRequest', () => {// stack is captured outside core's bundle chunk (see client-auth.ts).it('refuses a missing client id without throwing', async () => {const result = await validateIngestRequest({+ deps,headers: {},clientIp: '1.2.3.4',body,@@ -123,6 +129,7 @@ describe('validateIngestRequest', () => {it('refuses a client id that is not a UUIDv4', async () => {const result = await validateIngestRequest({+ deps,headers: { 'openpanel-client-id': 'not-a-uuid' },clientIp: '1.2.3.4',body,@@ -136,6 +143,7 @@ describe('validateIngestRequest', () => {it('redacts the presented secret in the refusal payload', async () => {const result = await validateIngestRequest({+ deps,headers: {'openpanel-client-id': 'not-a-uuid','openpanel-client-secret': 'abcdefghijklmnop',@@ -153,6 +161,7 @@ describe('validateIngestRequest', () => {it('refuses revenue tracking without a client secret', async () => {const result = await validateIngestRequest({+ deps,headers: { 'openpanel-client-id': CLIENT_ID },clientIp: '1.2.3.4',body: { ...body, properties: { __revenue: 100 } },@@ -175,6 +184,7 @@ describe('validateIngestRequest', () => {} as unknown as typeof client);const result = await validateIngestRequest({+ deps,headers: { 'openpanel-client-id': CLIENT_ID },clientIp: '203.0.113.10',body,diff --git a/packages/core/src/modules/ingest/src/client-auth.ts b/packages/core/src/modules/ingest/src/client-auth.tsindex 236d05821..fa0fabffb 100644--- a/packages/core/src/modules/ingest/src/client-auth.ts+++ b/packages/core/src/modules/ingest/src/client-auth.ts@@ -14,8 +14,12 @@import { getCache } from '@openpanel/redis';import { path } from 'ramda';+import type { DbScope } from '../../../shared/cacheable-per-deps';import { verifyPassword } from '../../../shared/crypto';-import type { IServiceClientWithProject } from '../../client/client.service';+import {+ getClientByIdCached,+ type IServiceClientWithProject,+} from '../../client/client.service';import type {IProjectFilterIp,IProjectFilterProfileId,@@ -24,16 +28,6 @@ import { headerValue, type IngestHeaders } from './headers';export type { IngestHeaders } from './headers';-// M10-004: `getClientByIdCached`'s L1 LRU now lives inside-// `createClientService(deps)` (see that file's header), reached here through-// the v1-compat singleton — this ingest hot path has no `Ctx` of its own.-// GENUINE CYCLE, kept lazy: services.ts -> ingest.service.ts -> this file ->-// v1-compat.ts -> services.ts; the dynamic import is what keeps it a cycle-// ESM can evaluate.-function loadClientService() {- return import('../../../v1-compat');-}-const CLIENT_ID_UUID_REGEX =/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;const VERIFY_CACHE_SECONDS = 60 * 5;@@ -108,10 +102,14 @@ function isOriginAllowed(cors: string[], origin: string | undefined): boolean {}export async function validateIngestRequest({+ deps,headers,clientIp,body,}: {+ /** The scope the caller already holds — `getClientByIdCached`'s L1 is keyed+ * on `deps.db`, so every ingest caller reads the one process instance. */+ deps: DbScope;headers: IngestHeaders;clientIp: string | undefined;body: unknown;@@ -150,9 +148,7 @@ export async function validateIngestRequest({return refuse('Ingestion: Client ID must be a valid UUIDv4');}- const client = await (await loadClientService()).getClientByIdCached(- clientId- );+ const client = await getClientByIdCached(deps, clientId);if (!client) {return refuse('Ingestion: Invalid client id');diff --git a/packages/core/src/modules/ingest/src/incoming-event-handler.ts b/packages/core/src/modules/ingest/src/incoming-event-handler.tsindex b1e5a0323..12362cc3a 100644--- a/packages/core/src/modules/ingest/src/incoming-event-handler.ts+++ b/packages/core/src/modules/ingest/src/incoming-event-handler.ts@@ -29,6 +29,7 @@ import {} from '../../event/event.service';import { matchEvent } from '../../notification/notification.service';import type { IProjectFilters } from '../../project/project.constants';+import { getProjectByIdCached } from '../../project/project.service';import type { IClickhouseSession } from '../../session/session.service';import { sessionEndsEnqueued } from '../../session/src/session.metrics';import type { EnqueueSessionEndInput } from '../../session/src/session-end';@@ -97,8 +98,12 @@ export interface IncomingEventDeps {}/**- * The two lookups a work scope cannot supply. Both are resolved once at the- * composition root (`apps/api`'s main.ts) rather than per message.+ * The one lookup a work scope cannot supply, resolved once at the composition+ * root (`apps/api`'s main.ts) rather than per message.+ *+ * M15-005 removed the other two: `getProjectByIdCached` is now a module-scope+ * `cacheablePerDb` keyed on the Postgres client, so the message's own scope+ * reaches the same process-lived cache ingest, http and mcp read.*/export interface IncomingEventBindings {/**@@ -111,13 +116,6 @@ export interface IncomingEventBindings {deps: Ctx,payload: IServiceCreateEventPayload): Promise<unknown>;- /**- * `getProjectByIdCached`'s L1 LRU lives inside `createProjectService(deps)`,- * so `ctx.services.project` would hand every message a fresh, empty cache;- * ingest, http and mcp read the one instance registered at boot.- */- getCachedProject(projectId: string): Promise<IncomingEventProject | null>;- clearProjectCache(projectId: string): Promise<unknown>;}/**@@ -135,13 +133,13 @@ export function createIncomingEventDeps(checkNotificationRulesForEvent: (payload) =>bindings.checkNotificationRulesForEvent(ctx, payload),projects: {- getCached: bindings.getCachedProject,+ getCached: (projectId) => getProjectByIdCached(ctx, projectId),markFirstEvent: async (projectId) => {await ctx.db.project.updateMany({where: { id: projectId, firstEventAt: null },data: { firstEventAt: new Date() },});- await bindings.clearProjectCache(projectId);+ await getProjectByIdCached.clear(ctx, projectId);},},enqueueSessionEnd: (input) => ctx.services.session.enqueueSessionEnd(input),diff --git a/packages/core/src/modules/insight/src/referrer-spikes.ts b/packages/core/src/modules/insight/src/referrer-spikes.tsindex d71e1df8c..d88b22fa1 100644--- a/packages/core/src/modules/insight/src/referrer-spikes.ts+++ b/packages/core/src/modules/insight/src/referrer-spikes.ts@@ -12,7 +12,7 @@ import type { ServiceDeps } from '../../../services';import { convertClickhouseDateToJs } from '../../../shared/ch-dates';import { chQuery } from '../../../shared/ch-query';import { TABLE_NAMES } from '../../../shared/ch-tables';-import { overviewService } from '../../../v1-compat';+import { getRawWhereClause } from '../../overview/overview.service';import type {IChartEventFilter,IInterval,@@ -118,9 +118,7 @@ export async function getReferrerSpikes(input: GetReferrerSpikesInput): Promise<ReferrerSpikeCluster[]> {const { projectId, filters, startDate, endDate, interval, timezone } = input;- const filtersWhere = andFilters(- overviewService.getRawWhereClause('sessions', filters)- );+ const filtersWhere = andFilters(getRawWhereClause('sessions', filters));const window = sessionWindow(projectId, startDate, endDate);const bucket = bucketStart(interval);const sessionsTable = sql.id(TABLE_NAMES.sessions);diff --git a/packages/core/src/modules/insight/src/store.ts b/packages/core/src/modules/insight/src/store.tsindex ee7ea9feb..32815ed4b 100644--- a/packages/core/src/modules/insight/src/store.ts+++ b/packages/core/src/modules/insight/src/store.ts@@ -1,9 +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 two-// JSON sentinels (`DbNull`), which live in the same module as the constructed-// client and are reached through the declared v1-compat seam-// (`compatPrisma()`) rather than by importing `@openpanel/db` from core.+// 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.import type { Prisma } from '@openpanel/db/src/prisma-client';import type { ServiceDeps } from '../../../services';@@ -15,10 +14,11 @@ import type {} from './types';/** `Prisma.DbNull` is a plain sentinel value that lives in the same module as- * the constructed client — reached through the v1-compat seam so this file- * value-imports nothing from `@openpanel/db`. */-function loadCompatPrisma() {- return import('../../../v1-compat').then((m) => m.compatPrisma());+ * 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 {@@ -206,7 +206,7 @@ export function createInsightStore(deps: ServiceDeps): InsightStore {changeTo,now,}): Promise<void> {- const { DbNull } = await loadCompatPrisma();+ const { DbNull } = await loadPrismaSentinels();await db.insightEvent.create({data: {insightId,diff --git a/packages/core/src/modules/integration/integration.service.ts b/packages/core/src/modules/integration/integration.service.tsindex 67bd719c7..f6ea35ac2 100644--- a/packages/core/src/modules/integration/integration.service.ts+++ b/packages/core/src/modules/integration/integration.service.ts@@ -19,8 +19,7 @@//// M10-009: every exported function takes `ServiceDeps` and reaches Postgres// as `deps.db`; the `loadDb()` lazy loader is gone, so a requestId minted at-// the edge reaches the query (ADR-018, docs/TECH_DEBT.md §4). V1's still-live-// trpc router keeps calling the deps-free spellings v1-compat.ts re-exports.+// the edge reaches the query (ADR-018, docs/TECH_DEBT.md §4).import { z } from 'zod';import {diff --git a/packages/core/src/modules/mcp/mcp.service.ts b/packages/core/src/modules/mcp/mcp.service.tsindex 4971ea4af..650e6e630 100644--- a/packages/core/src/modules/mcp/mcp.service.ts+++ b/packages/core/src/modules/mcp/mcp.service.ts@@ -21,7 +21,6 @@import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';import type { ServiceDeps, Services } from '../../services';-import { compatPrisma } from '../../v1-compat';import {authenticateToken,extractToken,@@ -48,18 +47,17 @@ export interface McpHttpResult {* a service graph: nothing about it is per-request, and resolving it opens no* connection.*- * It comes off `v1-compat.ts` because that is the ONLY file in this package- * `core-uses-ctx-not-db-internals` lets import `@openpanel/db`'s Prisma+ * 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. This is the module's one- * remaining edge to that file: the tool tree itself reaches Postgres and- * ClickHouse through `deps`.+ * `insight/src/store.ts` use for the same sentinel. The tool tree itself+ * reaches Postgres and ClickHouse through `deps`.*/-let jsonNullSentinel: Promise<unknown> | undefined;function dbJsonNull(): Promise<unknown> {- jsonNullSentinel ??= compatPrisma().then((prisma) => prisma.DbNull);- return jsonNullSentinel;+ return import('../../context').then((m) =>+ m.prismaSentinels().then((prisma) => prisma.DbNull)+ );}/**diff --git a/packages/core/src/modules/misc/misc.service.ts b/packages/core/src/modules/misc/misc.service.tsindex b6eb63f24..100050cea 100644--- a/packages/core/src/modules/misc/misc.service.ts+++ b/packages/core/src/modules/misc/misc.service.ts@@ -9,11 +9,12 @@//// M10-005: the ClickHouse CLIENT is `deps.ch` — reads through// shared/ch-query.ts, the one write through `deps.ch.insert` — so the-// `loadCh()` lazy import of `@openpanel/db` is gone. What is left is-// `loadChHelpers()`, the same v1-compat hop project.service.ts uses: these-// three statements are raw strings, not `sql` fragments, so they still need-// `TABLE_NAMES` / `formatClickhouseDate`, which are pure helpers living beside-// the client. Converting the statements is ADR-013's P7 work, not this wave's.+// `loadCh()` lazy import of `@openpanel/db` is gone. M15-005 dropped the last+// hop too: these three statements are raw strings, not `sql` fragments, so+// they still need `TABLE_NAMES` / `formatClickhouseDate`, and core owns its+// own parity-tested copies of both (shared/ch-tables.ts, shared/ch-dates.ts,+// 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@@ -26,7 +27,9 @@ import { getRedisCache } from '@openpanel/redis';import { type GeoLocation, getGeoLocation } from '../../clients/geo';import type { Logger } from '../../logger';import type { ServiceDeps, Services } from '../../services';+import { formatClickhouseDate } from '../../shared/ch-dates';import { chQuery } from '../../shared/ch-query';+import { TABLE_NAMES } from '../../shared/ch-tables';import {DEFAULT_IP_HEADER_ORDER,getClientIpFromHeaders,@@ -44,10 +47,6 @@ import {} from './src/image-proxy';import { parseUrlMeta } from './src/parse-url-meta';-function loadChHelpers() {- return import('../../v1-compat').then((m) => m.compatChHelpers());-}-function loadCache() {return import('@openpanel/redis').then((m) => m.getCache);}@@ -364,7 +363,6 @@ export interface StatsResult {}export async function getStats(deps: ServiceDeps): Promise<StatsResult> {- const { TABLE_NAMES } = await loadChHelpers();const getCache = await loadCache();const res = await getCache(STATS_CACHE_KEY,@@ -399,7 +397,6 @@ export async function insertPingRecord(deps: ServiceDeps,record: PingRecord): Promise<void> {- const { TABLE_NAMES, formatClickhouseDate } = await loadChHelpers();await deps.ch.insert({table: TABLE_NAMES.self_hosting,values: [@@ -466,7 +463,6 @@ export async function runPingCron(deps: ServiceDeps): Promise<unknown> {return;}- const { TABLE_NAMES } = await loadChHelpers();const [res] = await chQuery<{ count: number }>(deps,`SELECT COUNT(*) as count FROM ${TABLE_NAMES.events}`diff --git a/packages/core/src/modules/notification/notification.service.test.ts b/packages/core/src/modules/notification/notification.service.test.tsindex b90082843..aa56b3a0e 100644--- a/packages/core/src/modules/notification/notification.service.test.ts+++ b/packages/core/src/modules/notification/notification.service.test.ts@@ -67,13 +67,6 @@ const realPrismaClient = {afterAll(async () => {mock.module('@openpanel/redis', () => realRedis);mock.module('@openpanel/db/src/prisma-client', () => realPrismaClient);- // Restoring the module registry is not enough: `v1-compat.ts` MEMOIZES the- // fallback `ServiceDeps` the first time anything resolves it, so if that- // happened while the mock above was installed, every later FILE in this- // process keeps the mocked client (bare `bun test` shares one registry).- // Drop the memo too — same reason mcp's dashboard-management.test.ts does.- const { resetV1CompatServicesForTests } = await import('../../v1-compat');- resetV1CompatServicesForTests();});const notificationRule = {@@ -132,10 +125,9 @@ const project = {};// M10-009: every function under test takes `ServiceDeps`, so `deps.db` IS the-// fake below. The `@openpanel/db/src/prisma-client` mock stays only for the-// cacheable `getNotificationRulesByProjectId`, which reaches Postgres through-// the v1-compat seam (see the service's header) — and for `Prisma.JsonNull` /-// `Prisma.DbNull`, which `compatPrisma()` reads from the same module.+// fake below. The `@openpanel/db/src/prisma-client` mock stays for+// `Prisma.JsonNull` / `Prisma.DbNull`, which `prismaSentinels()` reads from+// that module.const actualPrismaClient = await import('@openpanel/db/src/prisma-client');mock.module('@openpanel/db/src/prisma-client', () => ({...actualPrismaClient,diff --git a/packages/core/src/modules/notification/notification.service.ts b/packages/core/src/modules/notification/notification.service.tsindex 0eaab7a5e..81332de39 100644--- a/packages/core/src/modules/notification/notification.service.ts+++ b/packages/core/src/modules/notification/notification.service.ts@@ -36,6 +36,14 @@ import type {IChartEvent,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';@@ -73,9 +81,6 @@ export type INotificationPayload =// keys on the call's ARGUMENTS (packages/redis/cachable.ts), so the caller's// deps travel beside the key rather than inside it and the Redis key stays// byte-identical. Every function in this file now reads `deps.db`.-function loadPrisma() {- return import('../../v1-compat').then((m) => m.compatPrisma());-}// -- Rule cache --------------------------------------------------------@@ -326,7 +331,7 @@ export async function deliverNotification(});const payload = notification.payload;- const PrismaRuntime = await loadPrisma();+ const PrismaRuntime = await loadPrismaSentinels();if (!isValidPayload<INotificationPayload>(payload,diff --git a/packages/core/src/modules/notification/src/notification-dispatch.ts b/packages/core/src/modules/notification/src/notification-dispatch.tsindex c0c6110eb..9a87ad5e0 100644Binary files a/packages/core/src/modules/notification/src/notification-dispatch.ts and b/packages/core/src/modules/notification/src/notification-dispatch.ts differdiff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.tsindex 65909ab1c..3c5678351 100644--- a/packages/core/src/modules/onboarding/onboarding.service.ts+++ b/packages/core/src/modules/onboarding/onboarding.service.ts@@ -8,9 +8,7 @@//// M10-009: every exported function takes `ServiceDeps` and reaches Postgres// as `deps.db`; the `loadDb()` lazy loader is gone, so the requestId minted at-// the edge reaches the query (ADR-018, docs/TECH_DEBT.md §4). V1's still-live-// trpc router and cron job keep calling the deps-free spellings v1-compat.ts-// re-exports.+// the edge reaches the query (ADR-018, docs/TECH_DEBT.md §4).import crypto from 'node:crypto';import { getRecommendedPlan } from '@openpanel/payments';@@ -29,17 +27,9 @@ import {getOrganizationById,getOrganizationEventsCount,} from '../organization/organization.service';+import { getUserById } from '../user/user.service';import type { IOnboardingProject } from './onboarding.constants';-// user.service.ts's `getUserById` now takes `ServiceDeps` (M10-004), which-// this file's own still-lazy `loadDb()` functions don't carry — reached-// through v1-compat.ts's bare re-export instead. GENUINE CYCLE, kept lazy:-// services.ts -> onboarding.service.ts (this file) -> v1-compat.ts ->-// services.ts; the dynamic import is what keeps it a cycle ESM can evaluate.-function loadUserService() {- return import('../../v1-compat');-}-const TRIAL_DURATION_IN_DAYS = 30;// Generous trial allowance so trialing orgs never get flagged as// "limit exceeded" (the limit defaults to 0, which trips on the first event).@@ -106,7 +96,7 @@ async function createOrGetOnboardingOrganization(}),db.member.create({data: {- email: (await (await loadUserService()).getUserById(userId)).email,+ email: (await getUserById(deps, userId)).email,organizationId,role: 'org:admin',userId,diff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.tsindex 3daac2294..5c767b18d 100644--- a/packages/core/src/modules/organization/organization.service.test.ts+++ b/packages/core/src/modules/organization/organization.service.test.ts@@ -397,7 +397,7 @@ const $transaction = mock(async (ops: Promise<unknown>[]) => Promise.all(ops));// `deps.ch` ARE the fakes below — the two `@openpanel/db` module mocks this// file used to install are gone, and with them the process-wide leak they had// to be restored from. `connectUserToOrganization` reaches-// `shared/access-lookups.ts` (cacheable, via the v1-compat seam), which is why+// `shared/access-lookups.ts` (cacheable, on the unscoped db), which is why// the `@openpanel/redis` stand-in below stays.const chCommand = mock(async () => undefined);const deps = {diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.tsindex d5a1119a6..747eb6c58 100644--- a/packages/core/src/modules/organization/organization.service.ts+++ b/packages/core/src/modules/organization/organization.service.ts@@ -20,9 +20,8 @@//// M12-006 also made `shared/access-lookups.ts` a static import: that file// value-imports only zod-free leaves (`@openpanel/redis`, a Prisma TYPE) and-// reaches Postgres through the lazy v1-compat seam itself (the one seam-// M15-004 could not close — its bare signature is pinned by a protected wire-// contract), so it has no static edge back here.+// reaches Postgres through `context.ts`'s `unscopedDb()` (its bare signature+// is pinned by a protected wire contract), so it has no static edge back here.//// M12-006 converted all five ClickHouse statements here onto the ADR-013 `sql`// tag: the four billing counters and `deleteFromClickhouse`'s project filterdiff --git a/packages/core/src/modules/project/project.service.test.ts b/packages/core/src/modules/project/project.service.test.tsindex e09ecf210..718ea0031 100644--- a/packages/core/src/modules/project/project.service.test.ts+++ b/packages/core/src/modules/project/project.service.test.ts@@ -5,10 +5,10 @@// port with unchanged SQL (ADR-013 converts them in P7) — executed against// local ClickHouse for this task's verification, not re-tested here.//-// `../../v1-compat` is still mocked: `createProjectForOrganization`/-// `updateProjectForOrganization` invalidate a project's clients through the-// v1-compat singleton (see project.service.ts's header), which this test-// has no real `AppDeps` to build.+// M15-005: `createProjectForOrganization`/`updateProjectForOrganization`+// invalidate a project's clients through `client.service.ts`'s module-scope+// `getClientByIdCached`, which is built from the `cacheable` stub below — so+// there is no seam left to mock here.import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testServices } from '../../../test/service-deps';@@ -165,10 +165,8 @@ function cacheableStub(}// M10-009: each factory spreads a plain-object SNAPSHOT of the real module and// is restored in afterAll. `mock.module` has no per-file scope under bare-// `bun test` (AGENTS.md), and a partial factory for `@openpanel/redis` or-// `../../v1-compat` deletes every export it does not name for whichever file-// runs next — which, now that cross-module callers reach the v1-compat seam-// directly rather than through the package barrel, is a live hazard.+// `bun test` (AGENTS.md), and a partial factory for `@openpanel/redis` deletes+// every export it does not name for whichever file runs next.const realRedis = { ...(await import('@openpanel/redis')) };mock.module('@openpanel/redis', () => ({...realRedis,@@ -186,17 +184,9 @@ mock.module('../../shared/slug-id', () => ({getId: async (_deps: unknown, _table: string, name: string) => `${name}-slug`,}));-const clearClientByIdCache = mock(async () => 0);-const realV1Compat = { ...(await import('../../v1-compat')) };-mock.module('../../v1-compat', () => ({- ...realV1Compat,- clearClientByIdCache,-}));-afterAll(() => {mock.module('@openpanel/redis', () => realRedis);mock.module('../../shared/slug-id', () => realSlugId);- mock.module('../../v1-compat', () => realV1Compat);});let subject: ReturnType<diff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.tsindex 6f983eb1c..6cc7a7a14 100644--- a/packages/core/src/modules/project/project.service.ts+++ b/packages/core/src/modules/project/project.service.ts@@ -3,15 +3,14 @@// access.service.ts and notification.service.ts still reach `getProjectById`// / `getProjectByIdCached` through the same relative path, and// apps/api/src/utils/auth.ts reaches them through @openpanel/db's barrel;-// auth.service.ts's permission ladder (M10-002) reaches `getProjectById`-// through `shared/access-lookups.ts`, which — with no `ServiceDeps` of its-// own to carry — reaches it through the v1-compat singleton instead-// (M10-004, see v1-compat.ts's header).+// auth.service.ts's permission ladder (M10-002) reaches a project through+// `shared/access-lookups.ts`, which has no `ServiceDeps` of its own to carry+// (M15-005: it reads Postgres from `context.ts`'s `unscopedDb()` instead).//// M10-004: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; the `loadDb()` lazy loader is gone. `getProjectByIdCached` lives-// INSIDE `createProjectService(deps)` for the same reason-// `getClientByIdCached` does in client.service.ts — see that file's header.+// `deps.db`; the `loadDb()` lazy loader is gone. M15-005: `getProjectByIdCached`+// is a module-scope `cacheablePerDb` for the same reason `getClientByIdCached`+// is in client.service.ts — see that file's header.//// M12-006 converted this module's two ClickHouse statements// (`getProjectEventsCount` / `getLastEventPerProject`) onto the ADR-013 `sql`@@ -28,15 +27,16 @@ import type {Project,ProjectType,} from '@openpanel/db/src/prisma-client';-import { cacheable } from '@openpanel/redis';import { TRPCBadRequestError } from '../../rpc/errors';import type { ServiceDeps, Services } from '../../services';+import { cacheablePerDb, type DbScope } from '../../shared/cacheable-per-deps';import { convertClickhouseDateToJs } from '../../shared/ch-dates';import { chQuery } from '../../shared/ch-query';import { TABLE_NAMES } from '../../shared/ch-tables';import { getId } from '../../shared/slug-id';import { stripTrailingSlash } from '../../shared/string';import { hashPassword } from '../auth/auth.service';+import { getClientByIdCached } from '../client/client.service';// The `sql` tag is a value import of `@openpanel/db` and stays one: it is a// compile-time template tag holding no client (see shared/ch-query.ts).@@ -53,18 +53,6 @@ const CLIX_SESSION_TIMEZONE = { session_timezone: 'UTC' } as const;// session_end after tracking already stopped) — only real tracking activity// counts. V1 wrote this list inline in both statements.const NON_TRACKING_EVENT_NAMES = ['session_start', 'session_end'];-// GENUINE CYCLE, kept lazy: `createClientForOrganization`/-// `updateClientForOrganization` invalidate a project's clients' cache-// entries, and that cache now lives inside `createClientService(deps)` (see-// that file's header) — reached here through the v1-compat singleton so-// every caller invalidates the SAME cache instance, the one `ingest`/`http`/-// `mcp` actually read. services.ts -> project.service.ts (this file) ->-// v1-compat.ts -> services.ts; the dynamic import is what keeps it a cycle-// ESM can evaluate.-function loadClientService() {- return import('../../v1-compat');-}-export type IServiceProject = Project;export type IServiceProjectWithClients = Prisma.ProjectGetPayload<{include: {@@ -74,7 +62,7 @@ export type IServiceProjectWithClients = Prisma.ProjectGetPayload<{const DAY_IN_SECONDS = 60 * 60 * 24;-export async function getProjectById(deps: ServiceDeps, id: string) {+export async function getProjectById(deps: DbScope, id: string) {const res = await deps.db.project.findUnique({where: {id,@@ -88,6 +76,19 @@ export async function getProjectById(deps: ServiceDeps, id: string) {return res;}+/**+ * L1 LRU (60s) + L2 Redis, one instance per Postgres client — the ingest+ * consumer, `/track` and mcp all read and invalidate the same one. The name is+ * EMPTY for the same reason `getClientByIdCached`'s is: the in-factory+ * `cacheable(...)` this replaces took an anonymous arrow, so the Redis key is+ * `cachable::<id>`.+ */+export const getProjectByIdCached = cacheablePerDb(+ '',+ getProjectById,+ DAY_IN_SECONDS+);+export async function getProjectWithClients(deps: ServiceDeps, id: string) {const res = await deps.db.project.findUnique({where: {@@ -391,12 +392,6 @@ export function createProjectService(deps: ServiceDeps,_services: () => Services) {- /** L1 LRU (60s) + L2 Redis. clear() invalidates Redis + local LRU; other nodes may serve stale from LRU for up to 60s. */- const getProjectByIdCached = cacheable(- (id: string) => getProjectById(deps, id),- DAY_IN_SECONDS- );-async function createProjectForOrganization(organizationId: string,input: {@@ -440,11 +435,10 @@ export function createProjectService(},});- const clientService = await loadClientService();await Promise.all([- getProjectByIdCached.clear(project.id),+ getProjectByIdCached.clear(deps, project.id),...project.clients.map((client) =>- clientService.clearClientByIdCache(client.id)+ getClientByIdCached.clear(deps, client.id)),]);@@ -498,11 +492,10 @@ export function createProjectService(data: updateData,});- const clientService = await loadClientService();await Promise.all([- getProjectByIdCached.clear(project.id),+ getProjectByIdCached.clear(deps, project.id),...existing.clients.map((client) =>- clientService.clearClientByIdCache(client.id)+ getClientByIdCached.clear(deps, client.id)),]);@@ -528,7 +521,7 @@ export function createProjectService(},});- await getProjectByIdCached.clear(id);+ await getProjectByIdCached.clear(deps, id);return true;}@@ -574,12 +567,12 @@ export function createProjectService(getProjectById: (id: string): ReturnType<typeof getProjectById> =>getProjectById(deps, id),getProjectByIdCached: (id: string): ReturnType<typeof getProjectById> =>- getProjectByIdCached(id),+ getProjectByIdCached(deps, id),/** Invalidates a single id in `getProjectByIdCached`'s L1 LRU + Redis —- * `ingest/src/incoming-event-handler.ts` reaches it, through the- * v1-compat singleton, right after marking a project's first event. */+ * `ingest/src/incoming-event-handler.ts` calls the module-scope spelling+ * right after marking a project's first event. */clearProjectByIdCache: (id: string): Promise<number> =>- getProjectByIdCached.clear(id),+ getProjectByIdCached.clear(deps, id),getProjectWithClients: (id: string): ReturnType<typeof getProjectWithClients> =>diff --git a/packages/core/src/modules/salt/salt.service.ts b/packages/core/src/modules/salt/salt.service.tsindex c2bd481a3..f66e9a9c3 100644--- a/packages/core/src/modules/salt/salt.service.ts+++ b/packages/core/src/modules/salt/salt.service.ts@@ -8,17 +8,14 @@// `salt.jobs.ts`'s handler passes its `JobCtx` (a `ServiceDeps` by// construction) to `rotateSalt`.//-// `getSalts` is built ONCE per `createSaltService(deps)` call — its-// `cacheable(...)` L1 LRU must survive across calls to stay useful. That-// holds for the two places that matter: `ctx.services.salt` (one Ctx per-// request, but nothing hot-path reads it that way yet) and the v1-compat-// singleton (`registered`, built exactly once at boot by-// `setV1CompatServices`) that `ingest.service.ts`'s `/track` hot path reads-// through — see v1-compat.ts's header. `generateNewSalt` clears the SAME-// closure's cache, which is why it lives inside the factory too.--import { cacheable } from '@openpanel/redis';+// M15-005: `getSalts` is a module-scope `cacheablePerDb`, keyed on the+// Postgres client rather than on the scope — its L1 LRU has to survive across+// calls to be worth anything, and `ingest.service.ts`'s `/track` hot path now+// passes the scope it holds instead of reading a boot-scoped singleton through+// the deleted compat seam. `generateNewSalt` clears the same instance.+import type { ServiceDeps, Services } from '../../services';+import { cacheablePerDb } from '../../shared/cacheable-per-deps';import { generateSalt } from '../../shared/crypto';const SALT_CACHE_NAME = 'op:salt';@@ -60,6 +57,15 @@ export async function fetchSalts(deps: SaltDeps): Promise<Salts> {return { current: curr.salt, previous: prev?.salt ?? curr.salt };}+/** L1 LRU (60s) + L2 Redis, one instance per Postgres client. No arguments, so+ * the Redis key stays the single `cachable:op:salt:[]` the in-factory+ * `cacheable(SALT_CACHE_NAME, () => fetchSalts(deps), ...)` produced. */+export const getSalts = cacheablePerDb(+ SALT_CACHE_NAME,+ fetchSalts,+ SALT_CACHE_TTL_SECONDS+);+/** Boot bootstrap: creates the first two salts the first time this ever runs. */export async function createInitialSalts(deps: SaltDeps,@@ -92,12 +98,6 @@ export function createSaltService(deps: ServiceDeps,_services: () => Services) {- const getSalts = cacheable(- SALT_CACHE_NAME,- () => fetchSalts(deps),- SALT_CACHE_TTL_SECONDS- );-async function generateNewSalt() {const created = await deps.db.$transaction(async (tx) => {const existingSalts = await tx.salt.findMany({@@ -118,7 +118,7 @@ export function createSaltService(return newSalt;});- await getSalts.clear();+ await getSalts.clear(deps);return created;}@@ -139,7 +139,7 @@ export function createSaltService(}return {- getSalts: (): Promise<Salts> => getSalts(),+ getSalts: (): Promise<Salts> => getSalts(deps),createInitialSalts: (): Promise<void> => createInitialSalts(deps),rotateSalt: (): Promise<{ salt: string; createdAt: Date }> => rotateSalt(),};diff --git a/packages/core/src/modules/subscription/subscription.service.ts b/packages/core/src/modules/subscription/subscription.service.tsindex eb22b7339..160150948 100644--- a/packages/core/src/modules/subscription/subscription.service.ts+++ b/packages/core/src/modules/subscription/subscription.service.ts@@ -16,11 +16,8 @@// `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 v1-compat.ts's `compatPrisma()` instead of importing-// `@openpanel/db` here. `packages/trpc`'s still-live router calls every-// function here bare (no `ServiceDeps`); those reach `createServices` through-// the v1-compat singleton too — `subscription.routes.ts`'s own-// `/webhook/polar` route already carries a `Ctx`.+// through `context.ts`'s `prismaSentinels()` instead of importing+// `@openpanel/db` here.import {applySubscriptionDiscount,@@ -56,12 +53,11 @@ import {zCancellationReason,} from './subscription.constants';-// GENUINE CYCLE, kept lazy: `services.ts` statically imports this file for-// `createSubscriptionService`, and `v1-compat.ts` statically imports-// `services.ts` for `createServices` — so `loadCompatPrisma` reaches-// `v1-compat.ts` through a dynamic `import()`, not a static one.-function loadCompatPrisma() {- return import('../../v1-compat').then((m) => m.compatPrisma());+/** 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';@@ -566,7 +562,7 @@ async function syncSubscriptionToOrg();}- const { DbNull } = await loadCompatPrisma();+ const { DbNull } = await loadPrismaSentinels();const updateData = {subscriptionId: data.id,diff --git a/packages/core/src/modules/user/user.service.ts b/packages/core/src/modules/user/user.service.tsindex 5a0d58b2d..ce57b0a5c 100644--- a/packages/core/src/modules/user/user.service.ts+++ b/packages/core/src/modules/user/user.service.ts@@ -4,11 +4,8 @@// @openpanel/db's barrel, same shape as packages/db/src/gsc.ts since M5-002.//// M10-004: every function takes `ServiceDeps` and reaches Postgres as-// `deps.db`; the `loadDb()` lazy loader is gone. `onboarding.service.ts`'s-// own `getUserById` call and `packages/trpc`'s bare calls have no `deps` to-// hand it, so they reach these through v1-compat.ts's bare re-exports-// instead (see v1-compat.ts's header) — `auth.service.ts` calls-// `getUserAccount` directly since it already carries `deps` itself.+// `deps.db`; the `loadDb()` lazy loader is gone. Every caller — including+// `onboarding.service.ts` and `auth.service.ts` — passes the `deps` it holds.import type { User } from '@openpanel/db/src/prisma-client';import { TRPCBadRequestError } from '../../rpc/errors';@@ -18,9 +15,8 @@ export type IServiceUser = Awaited<ReturnType<typeof getUserById>>;// Explicit `Promise<User>` return type, not inferred: Prisma's// `findUniqueOrThrow` returns a chainable "fluent" client (PromiseLike, plus-// relation-loading methods), which trips up `Services['user']['getUserById']`-// in v1-compat.ts — a `.then(...)` wrapping a bare fluent type there can't-// unify with the plain `Promise<User>` the service member declares.+// relation-loading methods), which does not unify with the plain+// `Promise<User>` a `.then(...)` wrapper would declare.export function getUserById(deps: ServiceDeps, id: string): Promise<User> {return deps.db.user.findUniqueOrThrow({where: {diff --git a/packages/core/src/services.ts b/packages/core/src/services.tsindex 61efe3f4d..f8df6bcfc 100644--- a/packages/core/src/services.ts+++ b/packages/core/src/services.ts@@ -99,11 +99,10 @@ export interface Services {mcp: ReturnType<typeof createMcpService>;}-// MUST stay a hoisted `function` declaration, not a `const` arrow: one static-// ESM cycle runs through it (subscription.service.ts -> v1-compat.ts ->-// services.ts -> subscription.service.ts) and hoisting is the only reason it-// evaluates. A `const` would put it in a temporal dead zone that no typecheck-// reports and that fails at process boot.+// Stays a hoisted `function` declaration, not a `const` arrow: the one static+// ESM cycle that ran through it died with the compat seam at M15-005, but a+// `const` here would still put any future cycle in a temporal dead zone that+// no typecheck reports and that fails at process boot.export function createServices(deps: ServiceDeps): Services {// The thunk is captured, not copied, so two services may call each other// without a cycle: `container` is assigned before any thunk body can run,diff --git a/packages/core/src/shared/access-lookups.ts b/packages/core/src/shared/access-lookups.tsindex 3e61cd94d..ff2318a1b 100644--- a/packages/core/src/shared/access-lookups.ts+++ b/packages/core/src/shared/access-lookups.ts@@ -5,32 +5,40 @@// the real `@openpanel/db` binding ~28 modules' `src/access.ts` files supply// to it. Same shape as packages/trpc/src/access.ts's binding.//-// M10-004: `project.service.ts`'s `getProjectById` now takes `ServiceDeps`,-// which this file has none of — reached through the v1-compat singleton-// instead (see v1-compat.ts's header). GENUINE CYCLE, kept lazy: auth.service.ts-// -> this file (via `access-lookups`) is already lazy on the OTHER side;-// v1-compat.ts -> services.ts -> project.service.ts has no edge back to this-// file, but `getAccessChecks()` in auth.service.ts reaches both this file and-// project.service.ts, so a static import here risks the same evaluation-order-// hazard `getAccessChecks()`'s own header warns about.+// M15-005: Postgres comes from `context.ts`'s `unscopedDb()`. Two of the three+// lookups here are `cacheable`, whose key is derived from the call's ARGUMENTS+// (packages/redis/cachable.ts), so they cannot take a `ServiceDeps` leading+// parameter at all; the third (`getClientAccess`) delegates to them and stays+// symmetric. Their bare signature is also a protected wire contract —+// `verification/contracts/auth/group-b-project-access.mts` imports them through+// `packages/db/src/services/access.service.ts` with no app boot at all, so the+// handle has to be one this file can resolve on its own. It is the same client+// `ctx.db` is, not a second one.//-// M10-009: Postgres comes through that same seam (`compatDb()`), not a direct-// `import('@openpanel/db/...')`. Two of the three lookups here are `cacheable`,-// whose key is derived from the call's ARGUMENTS (packages/redis/cachable.ts),-// so they cannot take a `ServiceDeps` leading parameter at all; the third-// (`getClientAccess`) delegates to them and stays symmetric. What they get is-// the boot scope's `AppDeps.db` — the same client `ctx.db` is — rather than a-// second module-level singleton.+// `getProjectById` is spelled here rather than imported from+// `project.service.ts`: `shared/` sits below `modules/` (ADR-022 R22) and the+// ladder reads one field off the row.import type { AccessLevel } from '@openpanel/db/src/prisma-client';import { cacheable } from '@openpanel/redis';-function loadDb() {- return import('../v1-compat').then((m) => m.compatDb());+// Lazy, as the seam this replaces was: `context.ts` value-imports+// `services.ts`, so a static import here would drag the whole 36-service graph+// into the import graph of everything that reaches this file.+function unscopedDb() {+ return import('../context').then((m) => m.unscopedDb());}-function loadProjectService() {- return import('../v1-compat');+/**+ * The project row the ladder reads (`shared/access.ts`'s `AccessLookups`).+ * Same query as `project.service.ts`'s `getProjectById`, without the scope+ * that file's callers have and this one does not.+ */+export async function getProjectById(+ projectId: string+): Promise<{ organizationId: string | null } | null> {+ const db = await unscopedDb();+ return db.project.findUnique({ where: { id: projectId } });}export interface IProjectAccess {@@ -71,14 +79,12 @@ export const getProjectAccess = cacheable(}): Promise<IProjectAccess | null> => {try {// Check if user has access to the project- const project = await (await loadProjectService()).getProjectById(- projectId- );+ const project = await getProjectById(projectId);if (!project?.organizationId) {return null;}- const db = await loadDb();+ const db = await unscopedDb();const [projectAccess, member] = await Promise.all([db.projectAccess.findMany({where: {@@ -123,7 +129,7 @@ export const getOrganizationAccess = cacheable(userId: string;organizationId: string;}) => {- const db = await loadDb();+ const db = await unscopedDb();return db.member.findFirst({where: {userId,@@ -141,7 +147,7 @@ export async function getClientAccess({userId: string;clientId: string;}) {- const db = await loadDb();+ const db = await unscopedDb();const client = await db.client.findFirst({where: {id: clientId,diff --git a/packages/core/src/shared/cacheable-per-deps.ts b/packages/core/src/shared/cacheable-per-deps.tsindex 7f0aed625..0ef11538c 100644--- a/packages/core/src/shared/cacheable-per-deps.ts+++ b/packages/core/src/shared/cacheable-per-deps.ts@@ -19,8 +19,8 @@// (context.ts's `installLazyServices`), so the L1 LRU inside `cacheable` is// per scope rather than per process. The L2 Redis cache — the shared one, the// one that actually saves the query — is unchanged, so a repeat call costs one-// Redis GET where it used to cost none. Boot-scoped callers (the v1-compat-// seam, job handlers) keep a process-lived L1.+// Redis GET where it used to cost none. A cache that must be process-lived+// takes `cacheablePerDb` below instead.import { type CacheableOptions, cacheable } from '@openpanel/redis';import type { ServiceDeps } from '../services';@@ -70,3 +70,62 @@ export function cacheablePerDeps<A extends unknown[], R>(return run;}++/** What a cache keyed on the Postgres client needs from a scope. `AppDeps`,+ * `Ctx` and `ServiceDeps` all satisfy it. */+export type DbScope = Pick<ServiceDeps, 'db'>;++export type CacheablePerDb<A extends unknown[], R> = ((+ deps: DbScope,+ ...args: A+) => Promise<R>) & {+ getKey: (deps: DbScope, ...args: A) => string;+ clear: (deps: DbScope, ...args: A) => Promise<number>;+};++/**+ * `cacheablePerDeps` for a cache that must be PROCESS-lived, not scope-lived.+ *+ * The three ingest-path caches (`getClientByIdCached`, `getProjectByIdCached`,+ * `getSalts`) used to live inside a factory that was only ever built once, in+ * the deleted V1 compat seam. Keying them on the scope like `cacheablePerDeps`+ * does would hand every request a fresh, empty L1 LRU and split `.clear()`+ * across as many instances as there are requests. Keying on `deps.db` — one+ * Postgres client per process — keeps one instance to read and one to+ * invalidate under any scope.+ *+ * Safe precisely because `fn` can see nothing but `db`: the closure captures+ * the first caller's scope, and `db` is the key, so there is nothing else in+ * it that could differ between sharers.+ */+export function cacheablePerDb<A extends unknown[], R>(+ name: string,+ fn: (deps: DbScope, ...args: A) => Promise<R>,+ expireInSec: number,+ options?: CacheableOptions+): CacheablePerDb<A, R> {+ const byDb = new WeakMap<DbScope['db'], Cacheable<A, R>>();++ const forDeps = (deps: DbScope): Cacheable<A, R> => {+ const existing = byDb.get(deps.db);+ if (existing) {+ return existing;+ }+ const built = cacheable(+ name,+ (...args: A) => fn(deps, ...args),+ expireInSec,+ options+ ) as unknown as Cacheable<A, R>;+ byDb.set(deps.db, built);+ return built;+ };++ const run = (deps: DbScope, ...args: A): Promise<R> => forDeps(deps)(...args);+ run.getKey = (deps: DbScope, ...args: A): string =>+ forDeps(deps).getKey(...args);+ run.clear = (deps: DbScope, ...args: A): Promise<number> =>+ forDeps(deps).clear(...args);++ return run;+}diff --git a/packages/core/src/shared/slug-id.ts b/packages/core/src/shared/slug-id.tsindex f599a13c3..282dd8a4b 100644--- a/packages/core/src/shared/slug-id.ts+++ b/packages/core/src/shared/slug-id.ts@@ -7,8 +7,8 @@// `import('@openpanel/db/...')` — so the requestId minted at the edge reaches// the uniqueness probe (ADR-018, docs/TECH_DEBT.md §4). `deps` is narrowed to// `Pick<ServiceDeps, 'db'>` because mcp's tool handlers have a fixed-// `@modelcontextprotocol/sdk` signature and only ever hold the db they got-// from the v1-compat seam.+// `@modelcontextprotocol/sdk` signature and only ever hold the db the route+// closed over.import type { ServiceDeps } from '../services';import { slug } from './slug';diff --git a/packages/core/src/v1-compat.ts b/packages/core/src/v1-compat.tsdeleted file mode 100644index 505cbc7dc..000000000--- a/packages/core/src/v1-compat.ts+++ /dev/null@@ -1,738 +0,0 @@-// V1 COMPAT SEAM — what is left of it.-//-// M15-004 removed class (b): the 204 deps-threading wrappers that reached-// Postgres/ClickHouse through this file's boot-scoped `ServiceDeps` on behalf-// of a caller that already held one. Every one of those callers now passes the-// `deps` it was handed, so a converted read path carries the requestId minted-// at the edge all the way to the query (ADR-018, ADR-022 amendment A3) instead-// of losing it here.-//-// What remains is class (a) — the sibling-service wrappers, which need a-// service graph rather than a connection and die with R3's `services()`-// accessor (M15-005) — plus three seams that belong to neither:-// `compatPrisma` (the `Prisma` namespace, a sentinel value, not a client),-// `compatChHelpers` (ADR-013's still-unconverted query helpers) and-// `compatDb`, kept for `shared/access-lookups.ts` alone: its three lookups are-// `cacheable`, keyed on their ARGUMENTS, and their bare signature is pinned by-// the protected wire contract `verification/contracts/auth/-// group-b-project-access.mts` through `packages/db`'s re-export shim.-//-// Nothing that has a `Ctx` comes through here. HTTP routes, core's own-// procedures and job handlers all use `ctx.services.*`, built from the-// request-scoped ctx.-//-// A process that never builds `AppDeps` — this package's own unit suites,-// which exercise a service directly — falls back to the singletons the deleted-// module-level `loadDb()` / `loadChClient()` loaders reached. The fallback is-// LAZY: importing `@openpanel/core` still constructs no database, which is-// what keeps `bun test` runnable offline.--import {- getRawWhereClause,- isPageFilter,-} from './modules/overview/overview.service';-import { createServices, type ServiceDeps, type Services } from './services';--let registered: Services | undefined;-let registeredDeps: ServiceDeps | undefined;--/** Called once from `main.ts`, right after `AppDeps` is built. */-export function setV1CompatServices(deps: ServiceDeps): void {- registeredDeps = deps;- registered = createServices(deps);-}--/** Test-only: drop the registration so one suite cannot answer the next. */-export function resetV1CompatServicesForTests(): void {- registered = undefined;- registeredDeps = undefined;- fallback = undefined;-}--/** What the boot scope stamps on jobs enqueued through this seam — there is- * no request to correlate with, and saying so beats a random id. */-export const V1_COMPAT_REQUEST_ID = 'v1-compat';--function unbuilt(field: string): never {- throw new Error(- `ServiceDeps.${field} is only available once main.ts has called setV1CompatServices(deps)`- );-}--let fallback: Promise<ServiceDeps> | undefined;--function fallbackServiceDeps(): Promise<ServiceDeps> {- fallback ??= (async () => {- // `createLogger` is packages/db's own pino factory — the one that already- // writes `chQuery`'s `query info` line today — so a caller that reaches- // this fallback logs exactly what it logged before M10-003.- const [{ db }, { ch }, { getRedisCache }, { createLogger }] =- await Promise.all([- import('@openpanel/db/src/prisma-client'),- import('@openpanel/db/src/clickhouse/client'),- import('@openpanel/redis'),- import('@openpanel/db/src/logger'),- ]);- return {- db,- ch,- redis: getRedisCache(),- logger: createLogger({ name: 'v1-compat' }),- get clients(): never {- return unbuilt('clients');- },- get buffers(): never {- return unbuilt('buffers');- },- get queues(): never {- return unbuilt('queues');- },- };- })();- return fallback;-}--function compatServiceDeps(): Promise<ServiceDeps> {- return registeredDeps- ? Promise.resolve(registeredDeps)- : fallbackServiceDeps();-}--function services(): Promise<Services> {- return registered- ? Promise.resolve(registered)- : fallbackServiceDeps().then(createServices);-}--/**- * The one deps-free Postgres handle left (M15-004). `shared/access-lookups.ts`- * keeps it because its three lookups are `cacheable` on their ARGUMENTS and- * their bare signature is a protected wire contract- * (`verification/contracts/auth/group-b-project-access.mts` imports them- * through `packages/db/src/services/access.service.ts`). Every other caller of- * this seam now passes the `deps` it holds.- */-export async function compatDb(): Promise<ServiceDeps['db']> {- return (await compatServiceDeps()).db;-}-/**- * `subscription.service.ts` (has `deps`, but `deps.db`'s type is the client- * instance, not the namespace) and `mcp`'s `dashboard-management.ts` (no- * `deps` at all) both need `Prisma.DbNull` — a plain sentinel value, not a- * client — to write an explicit SQL NULL onto a nullable Json column. The- * namespace lives in the same module as the constructed `db` singleton, so- * this seam is the only way to reach it without either module importing- * `@openpanel/db` itself.- */-export async function compatPrisma(): Promise<- typeof import('@openpanel/db/src/prisma-client').Prisma-> {- return (await import('@openpanel/db/src/prisma-client')).Prisma;-}--/**- * ADR-013 keeps `chQuery`/`TABLE_NAMES` alive until the analytics read path's- * conversion (one query per task, old-vs-new result sets diffed) —- * `misc.service.ts`'s still-unconverted queries reach the query-building- * helpers here instead of importing `@openpanel/db` themselves. The CLIENT- * itself is still `deps.ch` (M15-004 deleted `compatCh`); this is only the- * pure helpers that live beside it. (M12-006 converted the other two callers,- * `project.service.ts` and mcp's `analytics/property-values.ts`.)- *- * M12-008 dropped the `clix` member: `legacy-scan.ts` and `widget.rpc.ts` were- * its last consumers in core, and nothing destructured it from here any more.- * Core no longer reaches the builder at all, which is what lets M12-009 delete- * `query-builder.ts`.- */-export async function compatChHelpers(): Promise<{- TABLE_NAMES: typeof import('@openpanel/db/src/clickhouse/client').TABLE_NAMES;- chQuery: typeof import('@openpanel/db/src/clickhouse/client').chQuery;- convertClickhouseDateToJs: typeof import('@openpanel/db/src/clickhouse/client').convertClickhouseDateToJs;- formatClickhouseDate: typeof import('@openpanel/db/src/clickhouse/client').formatClickhouseDate;- toNullIfDefaultMinDate: typeof import('@openpanel/db/src/clickhouse/client').toNullIfDefaultMinDate;-}> {- const client = await import('@openpanel/db/src/clickhouse/client');- return {- TABLE_NAMES: client.TABLE_NAMES,- chQuery: client.chQuery,- convertClickhouseDateToJs: client.convertClickhouseDateToJs,- formatClickhouseDate: client.formatClickhouseDate,- toNullIfDefaultMinDate: client.toNullIfDefaultMinDate,- };-}--// --- chart -------------------------------------------------------------------export const getProjectCard: Services['chart']['getProjectCard'] = (...args) =>- services().then((container) => container.chart.getProjectCard(...args));-export const listChartEvents: Services['chart']['listChartEvents'] = (- ...args-) => services().then((container) => container.chart.listChartEvents(...args));-export const listChartProperties: Services['chart']['listChartProperties'] = (- ...args-) =>- services().then((container) => container.chart.listChartProperties(...args));-export const getChartPropertyValues: Services['chart']['getChartPropertyValues'] =- (...args) =>- services().then((container) =>- container.chart.getChartPropertyValues(...args)- );-export const getChartBucketProfiles: Services['chart']['bucketProfiles'] = (- ...args-) => services().then((container) => container.chart.bucketProfiles(...args));-export const getFunnelStepProfiles: Services['chart']['funnelStepProfiles'] = (- ...args-) =>- services().then((container) => container.chart.funnelStepProfiles(...args));-export const executeChart: Services['chart']['execute'] = (...args) =>- services().then((container) => container.chart.execute(...args));-export const executeAggregateChart: Services['chart']['executeAggregate'] = (- ...args-) => services().then((container) => container.chart.executeAggregate(...args));-export const ChartEngine = { execute: executeChart };-export const AggregateChartEngine = { execute: executeAggregateChart };--// --- funnel / conversion / sankey / retention --------------------------------export const getFunnelChart: Services['chart']['getFunnelChart'] = (...args) =>- services().then((container) => container.chart.getFunnelChart(...args));-export const getFunnel: Services['chart']['getFunnel'] = (...args) =>- services().then((container) => container.chart.getFunnel(...args));-export const getFunnelCore: Services['chart']['getFunnelCore'] = (...args) =>- services().then((container) => container.chart.getFunnelCore(...args));-export const buildFunnelBase: Services['chart']['buildFunnelBase'] = (- ...args-) => services().then((container) => container.chart.buildFunnelBase(...args));-export const getFunnelProfileIds: Services['chart']['getFunnelProfileIds'] = (- ...args-) =>- services().then((container) => container.chart.getFunnelProfileIds(...args));-export const getConversionChart: Services['chart']['getConversionChart'] = (- ...args-) =>- services().then((container) => container.chart.getConversionChart(...args));-export const getConversion: Services['chart']['getConversion'] = (...args) =>- services().then((container) => container.chart.getConversion(...args));-export const getSankeyChart: Services['chart']['getSankeyChart'] = (...args) =>- services().then((container) => container.chart.getSankeyChart(...args));-export const getSankey: Services['chart']['getSankey'] = (...args) =>- services().then((container) => container.chart.getSankey(...args));-export const getUserFlowCore: Services['chart']['getUserFlowCore'] = (- ...args-) => services().then((container) => container.chart.getUserFlowCore(...args));-export const getRetentionChart: Services['chart']['getRetentionChart'] = (- ...args-) => services().then((container) => container.chart.getRetentionChart(...args));-export const getRetentionCohort: Services['chart']['getRetentionCohort'] = (- ...args-) =>- services().then((container) => container.chart.getRetentionCohort(...args));-export const getRetentionCohortCore: Services['chart']['getRetentionCohortCore'] =- (...args) =>- services().then((container) =>- container.chart.getRetentionCohortCore(...args)- );-export const getRetentionSeries: Services['chart']['getRetentionSeries'] = (- ...args-) =>- services().then((container) => container.chart.getRetentionSeries(...args));-export const getRetentionLastSeenSeries: Services['chart']['getRetentionLastSeenSeries'] =- (...args) =>- services().then((container) =>- container.chart.getRetentionLastSeenSeries(...args)- );-export const getRollingActiveUsers: Services['chart']['getRollingActiveUsers'] =- (...args) =>- services().then((container) =>- container.chart.getRollingActiveUsers(...args)- );-export const getRollingActiveUsersCore: Services['chart']['getRollingActiveUsersCore'] =- (...args) =>- services().then((container) =>- container.chart.getRollingActiveUsersCore(...args)- );-export const getWeeklyRetentionSeriesCore: Services['chart']['getWeeklyRetentionSeriesCore'] =- (...args) =>- services().then((container) =>- container.chart.getWeeklyRetentionSeriesCore(...args)- );-export const getEngagementCore: Services['chart']['getEngagementCore'] = (- ...args-) => services().then((container) => container.chart.getEngagementCore(...args));--// --- report ------------------------------------------------------------------export const getReportsByDashboardId: Services['report']['getReportsByDashboardId'] =- (...args) =>- services().then((container) =>- container.report.getReportsByDashboardId(...args)- );-export const getReportById: Services['report']['getReportById'] = (...args) =>- services().then((container) => container.report.getReportById(...args));-export const getReportByIdOrThrow: Services['report']['getReportByIdOrThrow'] =- (...args) =>- services().then((container) =>- container.report.getReportByIdOrThrow(...args)- );-export const listReportsCore: Services['report']['listReportsCore'] = (- ...args-) => services().then((container) => container.report.listReportsCore(...args));-export const getReportDataCore: Services['report']['getReportDataCore'] = (- ...args-) =>- services().then((container) => container.report.getReportDataCore(...args));-export const createReport: Services['report']['createReport'] = (...args) =>- services().then((container) => container.report.createReport(...args));-export const updateReport: Services['report']['updateReport'] = (...args) =>- services().then((container) => container.report.updateReport(...args));-export const moveReport: Services['report']['moveReport'] = (...args) =>- services().then((container) => container.report.moveReport(...args));-export const deleteReport: Services['report']['deleteReport'] = (...args) =>- services().then((container) => container.report.deleteReport(...args));-export const duplicateReport: Services['report']['duplicateReport'] = (- ...args-) => services().then((container) => container.report.duplicateReport(...args));-export const updateReportLayout: Services['report']['updateReportLayout'] = (- ...args-) =>- services().then((container) => container.report.updateReportLayout(...args));-export const getReportLayouts: Services['report']['getReportLayouts'] = (- ...args-) => services().then((container) => container.report.getReportLayouts(...args));-export const resetReportLayouts: Services['report']['resetReportLayouts'] = (- ...args-) =>- services().then((container) => container.report.resetReportLayouts(...args));--// --- dashboard ---------------------------------------------------------------export const getDashboardById: Services['dashboard']['getDashboardById'] = (- ...args-) =>- services().then((container) => container.dashboard.getDashboardById(...args));-export const getDashboardByIdOrThrow: Services['dashboard']['getDashboardByIdOrThrow'] =- (...args) =>- services().then((container) =>- container.dashboard.getDashboardByIdOrThrow(...args)- );-export const getDashboardsByProjectId: Services['dashboard']['getDashboardsByProjectId'] =- (...args) =>- services().then((container) =>- container.dashboard.getDashboardsByProjectId(...args)- );-export const listDashboardsCore: Services['dashboard']['listDashboardsCore'] = (- ...args-) =>- services().then((container) =>- container.dashboard.listDashboardsCore(...args)- );-export const createDashboard: Services['dashboard']['createDashboard'] = (- ...args-) =>- services().then((container) => container.dashboard.createDashboard(...args));-export const updateDashboard: Services['dashboard']['updateDashboard'] = (- ...args-) =>- services().then((container) => container.dashboard.updateDashboard(...args));-export const deleteDashboard: Services['dashboard']['deleteDashboard'] = (- ...args-) =>- services().then((container) => container.dashboard.deleteDashboard(...args));--// --- share -------------------------------------------------------------------export const getShareOverviewById: Services['share']['getShareOverviewById'] = (- ...args-) =>- services().then((container) => container.share.getShareOverviewById(...args));-export const getShareByProjectId: Services['share']['getShareByProjectId'] = (- ...args-) =>- services().then((container) => container.share.getShareByProjectId(...args));-export const getShareDashboardById: Services['share']['getShareDashboardById'] =- (...args) =>- services().then((container) =>- container.share.getShareDashboardById(...args)- );-export const getShareDashboardByDashboardId: Services['share']['getShareDashboardByDashboardId'] =- (...args) =>- services().then((container) =>- container.share.getShareDashboardByDashboardId(...args)- );-export const getShareReportById: Services['share']['getShareReportById'] = (- ...args-) =>- services().then((container) => container.share.getShareReportById(...args));-export const getShareReportByReportId: Services['share']['getShareReportByReportId'] =- (...args) =>- services().then((container) =>- container.share.getShareReportByReportId(...args)- );-export const validateReportAccess: Services['share']['validateReportAccess'] = (- ...args-) =>- services().then((container) => container.share.validateReportAccess(...args));-export const validateShareAccess: Services['share']['validateShareAccess'] = (- ...args-) =>- services().then((container) => container.share.validateShareAccess(...args));-export const validateOverviewShareAccess: Services['share']['validateOverviewShareAccess'] =- (...args) =>- services().then((container) =>- container.share.validateOverviewShareAccess(...args)- );-export const getShareOverview: Services['share']['getShareOverview'] = (- ...args-) => services().then((container) => container.share.getShareOverview(...args));-export const getShareOverviewSettings: Services['share']['getShareOverviewSettings'] =- (...args) =>- services().then((container) =>- container.share.getShareOverviewSettings(...args)- );-export const createShareOverview: Services['share']['createShareOverview'] = (- ...args-) =>- services().then((container) => container.share.createShareOverview(...args));-export const getShareDashboard: Services['share']['getShareDashboard'] = (- ...args-) => services().then((container) => container.share.getShareDashboard(...args));-export const getShareDashboardSettings: Services['share']['getShareDashboardSettings'] =- (...args) =>- services().then((container) =>- container.share.getShareDashboardSettings(...args)- );-export const createShareDashboard: Services['share']['createShareDashboard'] = (- ...args-) =>- services().then((container) => container.share.createShareDashboard(...args));-export const getShareDashboardReports: Services['share']['getShareDashboardReports'] =- (...args) =>- services().then((container) =>- container.share.getShareDashboardReports(...args)- );-export const getShareReport: Services['share']['getShareReport'] = (...args) =>- services().then((container) => container.share.getShareReport(...args));-export const getShareReportSettings: Services['share']['getShareReportSettings'] =- (...args) =>- services().then((container) =>- container.share.getShareReportSettings(...args)- );-export const createShareReport: Services['share']['createShareReport'] = (- ...args-) => services().then((container) => container.share.createShareReport(...args));--// --- reference ---------------------------------------------------------------export const getReferenceById: Services['reference']['getReferenceById'] = (- ...args-) =>- services().then((container) => container.reference.getReferenceById(...args));-export const getReferenceByIdOrThrow: Services['reference']['getReferenceByIdOrThrow'] =- (...args) =>- services().then((container) =>- container.reference.getReferenceByIdOrThrow(...args)- );-export const listReferences: Services['reference']['listReferences'] = (- ...args-) =>- services().then((container) => container.reference.listReferences(...args));-export const createReference: Services['reference']['createReference'] = (- ...args-) =>- services().then((container) => container.reference.createReference(...args));-export const updateReference: Services['reference']['updateReference'] = (- ...args-) =>- services().then((container) => container.reference.updateReference(...args));-export const deleteReference: Services['reference']['deleteReference'] = (- ...args-) =>- services().then((container) => container.reference.deleteReference(...args));-export const getChartReferences: Services['reference']['getChartReferences'] = (- ...args-) =>- services().then((container) =>- container.reference.getChartReferences(...args)- );--// --- client --------------------------------------------------------------export const getClientById: Services['client']['getClientById'] = (...args) =>- services().then((container) => container.client.getClientById(...args));-export const getClientByIdCached: Services['client']['getClientByIdCached'] = (- ...args-) =>- services().then((container) => container.client.getClientByIdCached(...args));-export const clearClientByIdCache: Services['client']['clearClientByIdCache'] =- (...args) =>- services().then((container) =>- container.client.clearClientByIdCache(...args)- );-export const getClientsByOrganizationId: Services['client']['getClientsByOrganizationId'] =- (...args) =>- services().then((container) =>- container.client.getClientsByOrganizationId(...args)- );-export const getClientsByProjectId: Services['client']['getClientsByProjectId'] =- (...args) =>- services().then((container) =>- container.client.getClientsByProjectId(...args)- );-export const listClientsForOrganization: Services['client']['listClientsForOrganization'] =- (...args) =>- services().then((container) =>- container.client.listClientsForOrganization(...args)- );-export const getClientForOrganization: Services['client']['getClientForOrganization'] =- (...args) =>- services().then((container) =>- container.client.getClientForOrganization(...args)- );-export const createClientForOrganization: Services['client']['createClientForOrganization'] =- (...args) =>- services().then((container) =>- container.client.createClientForOrganization(...args)- );-export const updateClientForOrganization: Services['client']['updateClientForOrganization'] =- (...args) =>- services().then((container) =>- container.client.updateClientForOrganization(...args)- );-export const deleteClientForOrganization: Services['client']['deleteClientForOrganization'] =- (...args) =>- services().then((container) =>- container.client.deleteClientForOrganization(...args)- );--// --- project ---------------------------------------------------------------export const getProjectById: Services['project']['getProjectById'] = (- ...args-) => services().then((container) => container.project.getProjectById(...args));-export const getProjectByIdCached: Services['project']['getProjectByIdCached'] =- (...args) =>- services().then((container) =>- container.project.getProjectByIdCached(...args)- );-export const clearProjectByIdCache: Services['project']['clearProjectByIdCache'] =- (...args) =>- services().then((container) =>- container.project.clearProjectByIdCache(...args)- );-export const getProjectWithClients: Services['project']['getProjectWithClients'] =- (...args) =>- services().then((container) =>- container.project.getProjectWithClients(...args)- );-export const getProjects: Services['project']['getProjects'] = (...args) =>- services().then((container) => container.project.getProjects(...args));-export const getProjectEventsCount: Services['project']['getProjectEventsCount'] =- (...args) =>- services().then((container) =>- container.project.getProjectEventsCount(...args)- );-export const getLastEventPerProject: Services['project']['getLastEventPerProject'] =- (...args) =>- services().then((container) =>- container.project.getLastEventPerProject(...args)- );-export const resolveClientProjectId: Services['project']['resolveClientProjectId'] =- (...args) =>- services().then((container) =>- container.project.resolveClientProjectId(...args)- );-export const getProjectActivationStatus: Services['project']['getProjectActivationStatus'] =- (...args) =>- services().then((container) =>- container.project.getProjectActivationStatus(...args)- );-export const listProjectsCore: Services['project']['listProjectsCore'] = (- ...args-) =>- services().then((container) => container.project.listProjectsCore(...args));-export const listProjectsForOrganization: Services['project']['listProjectsForOrganization'] =- (...args) =>- services().then((container) =>- container.project.listProjectsForOrganization(...args)- );-export const getProjectForOrganization: Services['project']['getProjectForOrganization'] =- (...args) =>- services().then((container) =>- container.project.getProjectForOrganization(...args)- );-export const createProjectForOrganization: Services['project']['createProjectForOrganization'] =- (...args) =>- services().then((container) =>- container.project.createProjectForOrganization(...args)- );-export const updateProjectForOrganization: Services['project']['updateProjectForOrganization'] =- (...args) =>- services().then((container) =>- container.project.updateProjectForOrganization(...args)- );-export const deleteProjectForOrganization: Services['project']['deleteProjectForOrganization'] =- (...args) =>- services().then((container) =>- container.project.deleteProjectForOrganization(...args)- );-export const scheduleProjectDeletion: Services['project']['scheduleProjectDeletion'] =- (...args) =>- services().then((container) =>- container.project.scheduleProjectDeletion(...args)- );-export const cancelProjectDeletion: Services['project']['cancelProjectDeletion'] =- (...args) =>- services().then((container) =>- container.project.cancelProjectDeletion(...args)- );--// --- user --------------------------------------------------------------------export const getUserById: Services['user']['getUserById'] = (...args) =>- services().then((container) => container.user.getUserById(...args));-export const getUserAccount: Services['user']['getUserAccount'] = (...args) =>- services().then((container) => container.user.getUserAccount(...args));-export const listUserDeletionBlockers: Services['user']['listUserDeletionBlockers'] =- (...args) =>- services().then((container) =>- container.user.listUserDeletionBlockers(...args)- );-export const deleteUserAccount: Services['user']['deleteUserAccount'] = (- ...args-) => services().then((container) => container.user.deleteUserAccount(...args));-export const updateUserProfile: Services['user']['updateUserProfile'] = (- ...args-) => services().then((container) => container.user.updateUserProfile(...args));--// --- subscription --------------------------------------------------------// `getCurrentSubscriptionProduct` never touched Postgres directly, so it-// kept its bare signature straight through — no wrapper needed, exported-// directly from subscription.service.ts on the barrel.-export const checkout: Services['subscription']['checkout'] = (...args) =>- services().then((container) => container.subscription.checkout(...args));-export const listProducts: Services['subscription']['listProducts'] = (- ...args-) =>- services().then((container) => container.subscription.listProducts(...args));-export const getUsage: Services['subscription']['getUsage'] = (...args) =>- services().then((container) => container.subscription.getUsage(...args));-export const cancelSubscription: Services['subscription']['cancelSubscription'] =- (...args) =>- services().then((container) =>- container.subscription.cancelSubscription(...args)- );-export const pauseSubscription: Services['subscription']['pauseSubscription'] =- (...args) =>- services().then((container) =>- container.subscription.pauseSubscription(...args)- );-export const resumeSubscription: Services['subscription']['resumeSubscription'] =- (...args) =>- services().then((container) =>- container.subscription.resumeSubscription(...args)- );-export const applySaveDiscount: Services['subscription']['applySaveDiscount'] =- (...args) =>- services().then((container) =>- container.subscription.applySaveDiscount(...args)- );-export const portal: Services['subscription']['portal'] = (...args) =>- services().then((container) => container.subscription.portal(...args));--// --- salt --------------------------------------------------------------------// `ingest.service.ts`'s `/track` hot path has no `Ctx` to reach-// `ctx.services.salt` from — see salt.service.ts's header for why `getSalts`-// stays bare here instead of gaining a `deps` parameter like every other-// function in this file.-export const getSalts: Services['salt']['getSalts'] = () =>- services().then((container) => container.salt.getSalts());--// --- conversation --------------------------------------------------------export const getConversationById: Services['conversation']['getConversationById'] =- (...args) =>- services().then((container) =>- container.conversation.getConversationById(...args)- );-export const listConversations: Services['conversation']['listConversations'] =- (...args) =>- services().then((container) =>- container.conversation.listConversations(...args)- );-export const upsertConversationTitle: Services['conversation']['upsertConversationTitle'] =- (...args) =>- services().then((container) =>- container.conversation.upsertConversationTitle(...args)- );-export const deleteConversation: Services['conversation']['deleteConversation'] =- (...args) =>- services().then((container) =>- container.conversation.deleteConversation(...args)- );--// V1's (now-deleted) `@openpanel/trpc` overview and event routers called-// these as OBJECTS (`overviewService.getMetrics(...)`,-// `pagesService.getTopPages(...)`), and one of them still did-// `.bind(overviewService)`. Both were module-singleton class instances-// before M10-005; here they are plain objects of bare wrappers, so those-// call sites read identically and `bind` stayed a no-op.-export const overviewService = {- isPageFilter: (...args: Parameters<Services['overview']['isPageFilter']>) =>- isPageFilter(...args),- getRawWhereClause: (- ...args: Parameters<Services['overview']['getRawWhereClause']>- ) => getRawWhereClause(...args),- getMetrics: ((...args) =>- services().then((container) =>- container.overview.getMetrics(...args)- )) as Services['overview']['getMetrics'],- getTopPages: ((...args) =>- services().then((container) =>- container.overview.getTopPages(...args)- )) as Services['overview']['getTopPages'],- getTopEntryExit: ((...args) =>- services().then((container) =>- container.overview.getTopEntryExit(...args)- )) as Services['overview']['getTopEntryExit'],- getTopGeneric: ((...args) =>- services().then((container) =>- container.overview.getTopGeneric(...args)- )) as Services['overview']['getTopGeneric'],- getTopGenericSeries: ((...args) =>- services().then((container) =>- container.overview.getTopGenericSeries(...args)- )) as Services['overview']['getTopGenericSeries'],- getUserJourney: ((...args) =>- services().then((container) =>- container.overview.getUserJourney(...args)- )) as Services['overview']['getUserJourney'],- getTopEvents: ((...args) =>- services().then((container) =>- container.overview.getTopEvents(...args)- )) as Services['overview']['getTopEvents'],- getTopLinkOut: ((...args) =>- services().then((container) =>- container.overview.getTopLinkOut(...args)- )) as Services['overview']['getTopLinkOut'],- getMapData: ((...args) =>- services().then((container) =>- container.overview.getMapData(...args)- )) as Services['overview']['getMapData'],- getLiveData: ((...args) =>- services().then((container) =>- container.overview.getLiveData(...args)- )) as Services['overview']['getLiveData'],-};--export const pagesService = {- getTopPages: ((...args) =>- services().then((container) =>- container.pages.getTopPages(...args)- )) as Services['pages']['getTopPages'],- getPageTimeseries: ((...args) =>- services().then((container) =>- container.pages.getPageTimeseries(...args)- )) as Services['pages']['getPageTimeseries'],-};diff --git a/packages/core/test/request-id-end-to-end.test.ts b/packages/core/test/request-id-end-to-end.test.tsindex 12aa55e9e..7d405ebf1 100644--- a/packages/core/test/request-id-end-to-end.test.ts+++ b/packages/core/test/request-id-end-to-end.test.ts@@ -545,7 +545,14 @@ function ingestDeps() {const deps: AppDeps = {db: {- project: { updateMany: () => Promise.resolve({ count: 0 }) },+ project: {+ // M15-005: the handler reads the project through+ // `project.service.ts`'s module-scope `getProjectByIdCached`, off the+ // message's own scope, instead of a binding resolved at boot.+ findUnique: () =>+ Promise.resolve({ firstEventAt: new Date(), filters: [] }),+ updateMany: () => Promise.resolve({ count: 0 }),+ },} as unknown as AppDeps['db'],ch: {} as AppDeps['ch'],redis: {} as AppDeps['redis'],@@ -561,9 +568,6 @@ function ingestDeps() {const ingestBindings: IncomingEventBindings = {checkNotificationRulesForEvent: () => Promise.resolve(null),- getCachedProject: () =>- Promise.resolve({ firstEventAt: new Date(), filters: [] }),- clearProjectCache: () => Promise.resolve(0),};function ingestEnvelope(requestId?: string): IncomingEventPayload {@@ -637,7 +641,7 @@ test("the envelope's requestId reaches the handler's logger, its buffer write anexpect(ingestHarness.eventsBuffered).toHaveLength(2);// Hop 3: the boundary's session_end job, enqueued through `ctx.services`.- // Before M10-006 this carried the boot scope's `v1-compat` id.+ // Before M10-006 this carried the boot scope's compat id.expect(ingestHarness.recorded.map(({ queue, job, meta }) => ({queue,@@ -654,8 +658,9 @@ test("the envelope's requestId reaches the handler's logger, its buffer write an});// M15-004: the notification dispatch used to reach Postgres and the-// `notification` producer through v1-compat's BOOT scope, so every job it-// enqueued was stamped `v1-compat` no matter which message triggered it. It+// `notification` producer through the deleted compat seam's BOOT scope, so+// every job it enqueued was stamped with that scope's id no matter which+// message triggered it. It// takes the caller's scope now, and this is the hop that proves it: the// binding enqueues exactly what `triggerNotification` enqueues, off the deps// it was handed, and the envelope must carry the message's own id.