@open-mercato/core 0.11.1-develop.8517.1.f52e23452d → 0.11.1-develop.8523.1.c6b0fd2058

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/query_index/lib/reindexer.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport { resolveQueryIndexSourceTableMetadata } from './subscriber-scope'\nimport { resolveTenantEncryptionService } from '@open-mercato/shared/lib/encryption/customFieldValues'\nimport { decryptIndexDocForSearch, encryptIndexDocForStorage } from '@open-mercato/shared/lib/encryption/indexDoc'\nimport {\n upsertIndexBatch,\n assertIndexBatchWritesLanded,\n createEmptyUpsertIndexBatchResult,\n mergeUpsertIndexBatchResults,\n QueryIndexBatchWriteError,\n type AnyRow,\n} from './batch'\nimport { createSearchTokenGateQueryEngine } from './search-entity-policy'\nimport {\n refreshCoverageSnapshot,\n writeCoverageCounts,\n applyCoverageAdjustments,\n deleteScopedCoverageForEntity,\n} from './coverage'\nimport { prepareJob, updateJobProgress, finalizeJob, type JobScope } from './jobs'\nimport { purgeOrphans, retireScopedCatalogueRows } from './stale'\nimport type { VectorIndexService } from '@open-mercato/search/vector'\nimport { isSearchDebugEnabled } from './search-tokens'\nimport { isTenantGlobalEntityType } from './tenant-global'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('query_index').child({ component: 'reindexer' })\n\nexport type ReindexJobOptions = {\n entityType: string\n tenantId?: string | null\n organizationId?: string | null\n force?: boolean\n batchSize?: number\n emitVectorizeEvents?: boolean\n eventBus?: {\n emitEvent(event: string, payload: any, options?: any): Promise<void>\n }\n partitionCount?: number\n partitionIndex?: number\n resetCoverage?: boolean\n onProgress?: (info: { processed: number; total: number; chunkSize: number }) => void\n vectorService?: VectorIndexService | null\n}\n\n/**\n * Why a sweep did no work, when it did none on purpose.\n *\n * A refused run is otherwise byte-identical to a successful sweep that found zero rows,\n * and the surfaces an operator reads - `indexer_status_logs`, the indexer status page,\n * the CLI's `0 / 0 (0.00%)` - report the second. The allowlist's safety argument is that\n * a missing `registerTenantGlobalEntityTypes()` declaration \"shows up in the log\", so the\n * log the product surfaces has to be able to say it.\n */\nexport type ReindexRefusalReason =\n /** The source table has no `tenant_id` column and the type is not a declared catalogue. */\n | 'no-tenant-column'\n /** `information_schema` could not be read, so no column could be proven to exist. */\n | 'column-probe-failed'\n /**\n * The type IS declared tenant-global, but its table carries `organization_id` while\n * lacking `tenant_id`. A global projection means both scope columns absent - the same\n * definition `loadQueryIndexRowScope()` uses - so the declaration cannot be honoured.\n */\n | 'declared-global-but-org-scoped'\n\nexport type ReindexJobResult = {\n processed: number\n total: number\n tenantScopes: Array<string | null>\n scopes: Array<{ tenantId: string | null; organizationId: string | null }>\n /** Absent on a sweep that ran. Present, with the reason, on one that deliberately did not. */\n refused?: ReindexRefusalReason\n}\n\nexport const DEFAULT_REINDEX_PARTITIONS = 5\nconst DEFAULT_BATCH_SIZE = 500\n/**\n * Above this many failed records the purge exclusion list stops being a sane query, so\n * the purge is skipped entirely instead. Failing closed keeps stale rows; the alternative\n * deletes index entries the run failed to rebuild.\n */\nconst MAX_PURGE_EXCLUSIONS = 1000\nconst deriveOrgFromId = new Set<string>(['directory:organization'])\nconst COVERAGE_REFRESH_THROTTLE_MS = 5 * 60 * 1000\nconst lastCoverageReset = new Map<string, number>()\n\nconst REINDEX_DECRYPT_DEBUG_KEYS = ['display_name', 'first_name', 'last_name', 'brand_name', 'legal_name', 'primary_email', 'primary_phone'] as const\n\nexport type ReindexDecryptDebugPayload = {\n entityType: string\n tenantId: string | null\n organizationId: string | null\n keys: string[]\n}\n\nexport function buildReindexDecryptDebugPayload(\n entityType: string,\n doc: Record<string, unknown>,\n scope: { organizationId: string | null; tenantId: string | null },\n): ReindexDecryptDebugPayload {\n const presentKeys: string[] = []\n for (const key of REINDEX_DECRYPT_DEBUG_KEYS) {\n const value = doc[key]\n if (key in doc && value != null && value !== '') presentKeys.push(key)\n }\n return {\n entityType,\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId ?? null,\n keys: presentKeys,\n }\n}\n\nasync function cleanupLegacyJobScopes(\n db: Kysely<any>,\n options: {\n entityType: string\n organizationId: string | null\n tenantId: string | null\n activePartitionCount: number | null\n },\n): Promise<void> {\n await db\n .deleteFrom('entity_index_jobs' as any)\n .where('entity_type' as any, '=', options.entityType)\n .where(sql<boolean>`organization_id is not distinct from ${options.organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${options.tenantId}`)\n .where(sql<boolean>`partition_count is distinct from ${options.activePartitionCount}`)\n .execute()\n}\n\nfunction toNumber(value: unknown): number {\n if (typeof value === 'number') return Number.isFinite(value) ? value : 0\n if (typeof value === 'string') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : 0\n }\n return 0\n}\n\n/**\n * Returns `null` - never an empty set - when the probe itself fails.\n *\n * An empty set is indistinguishable from \"this table has no columns we care about\", so a\n * transient failure (an aborted transaction on the same connection, a statement timeout, a\n * blip during a partition-parallel sweep) would make every entity type look tenant-less and\n * refuse every tenant-scoped reindex, reported as a successful zero-row run. Failing closed\n * is right; failing closed silently and globally is the hardest state to diagnose.\n */\nasync function getColumnSet(db: Kysely<any>, tableName: string, schema?: string): Promise<Set<string> | null> {\n try {\n const rows = await db\n .selectFrom('information_schema.columns' as any)\n .select(['column_name' as any])\n .where(schema ? sql<boolean>`table_schema = ${schema}` : sql<boolean>`table_schema = current_schema()`)\n .where('table_name' as any, '=', tableName)\n .execute() as Array<{ column_name: string }>\n return new Set(rows.map((row) => String(row.column_name).toLowerCase()))\n } catch (error) {\n logger.warn('Failed to read information_schema.columns for a reindex target', {\n table: tableName,\n error: error instanceof Error ? error.message : String(error),\n })\n reportColumnProbeFailure(error, tableName)\n return null\n }\n}\n\n/**\n * The probe's caller refuses the sweep whatever happens here, so a telemetry backend that\n * throws must not turn that refusal into a failed job.\n */\nfunction reportColumnProbeFailure(error: unknown, tableName: string): void {\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'query_index',\n code: 'query_index.column_probe_failed',\n attributes: { table: tableName },\n })\n } catch (telemetryError) {\n logger.warn('Failed to report a column probe failure', {\n table: tableName,\n error: telemetryError instanceof Error ? telemetryError.message : String(telemetryError),\n })\n }\n}\n\ntype ReindexSourceMetadata = ReturnType<typeof resolveQueryIndexSourceTableMetadata>\n\nfunction writesGlobalReindexProjection(\n entityType: string,\n columns: Set<string>,\n source: ReindexSourceMetadata,\n): boolean {\n return columns.has('id')\n && !columns.has('tenant_id')\n && !columns.has('organization_id')\n && !source?.tenantColumn\n && !source?.organizationColumn\n && isTenantGlobalEntityType(entityType)\n}\n\nfunction resolveTenantlessRefusal(\n entityType: string,\n columns: Set<string>,\n source: ReindexSourceMetadata,\n): Exclude<ReindexRefusalReason, 'column-probe-failed'> | null {\n if (columns.has('tenant_id')) return null\n if (writesGlobalReindexProjection(entityType, columns, source)) return null\n return isTenantGlobalEntityType(entityType) ? 'declared-global-but-org-scoped' : 'no-tenant-column'\n}\n\n/**\n * Answers, without logging, whether a tenant-scoped sweep of `entityType` would be refused\n * because its source table has no `tenant_id` column and the type is not a declared\n * tenant-global catalogue. Callers that enumerate every registered entity type for one\n * tenant (e.g. `mercato query_index reindex --tenant <id>` during `mercato init`) use it to\n * leave such types out up front, so the guard inside `reindexEntity()` keeps warning only\n * for callers that genuinely aimed a tenant-scoped sweep at a tenant-less table.\n *\n * Deliberately narrow: an unregistered type, a failed column probe, or a tenant-global\n * declaration that cannot be honoured all return `false`, so those still reach the guard\n * and surface their own diagnostics.\n */\nexport async function isTenantlessReindexTarget(\n em: EntityManager,\n entityType: string,\n): Promise<boolean> {\n if (!entityType) return false\n const source = resolveQueryIndexSourceTableMetadata(em, entityType)\n if (!source?.table) return false\n const db = em.getKysely<Record<string, Record<string, unknown>>>()\n const columns = await getColumnSet(db, source.tableName ?? source.table, source.schema)\n if (columns === null) return false\n return resolveTenantlessRefusal(entityType, columns, source) === 'no-tenant-column'\n}\n\nexport async function reindexEntity(\n em: EntityManager,\n options: ReindexJobOptions,\n): Promise<ReindexJobResult> {\n const entityType = String(options?.entityType || '')\n if (!entityType) {\n return {\n processed: 0,\n total: 0,\n tenantScopes: [],\n scopes: [],\n }\n }\n const tenantIdInput = options?.tenantId\n const tenantId = tenantIdInput === 'undefined' ? undefined : tenantIdInput\n const organizationIdInput = options?.organizationId\n const organizationId = organizationIdInput === 'undefined' ? undefined : organizationIdInput\n const force = options?.force === true\n const batchSize = Number.isFinite(options?.batchSize) && options!.batchSize! > 0\n ? Math.max(1, Math.trunc(options!.batchSize!))\n : DEFAULT_BATCH_SIZE\n const emitVectorize = options?.emitVectorizeEvents === true\n const eventBus = options?.eventBus\n const vectorService = options?.vectorService ?? null\n const partitionCountRaw = Number.isFinite(options?.partitionCount)\n ? Math.max(1, Math.trunc(options!.partitionCount!))\n : 1\n const usingPartitions = partitionCountRaw > 1\n const partitionIndexRaw = Number.isFinite(options?.partitionIndex)\n ? Math.max(0, Math.trunc(options!.partitionIndex!))\n : 0\n const partitionIndex = usingPartitions\n ? Math.min(partitionIndexRaw, partitionCountRaw - 1)\n : null\n const resetCoverage = options?.resetCoverage ?? (!usingPartitions || partitionIndex === 0)\n\n const db = (em as any).getKysely() as Kysely<any>\n // Resolve the source table strictly via registered MikroORM metadata. We must\n // never fall back to a pluralized guess derived from the caller-supplied id\n // here: doing so would let a principal with `query_index.reindex` point the\n // reindexer at arbitrary tables (e.g. `auth_users`, `users`) and read their\n // rows into the index, bypassing tenant scoping and entity-level encryption.\n const source = resolveQueryIndexSourceTableMetadata(em, entityType)\n const table = source?.table\n if (!table || entityType === 'query_index:search_token' || table === 'search_tokens') {\n if (!table) {\n logger.warn('Refusing to reindex unregistered entity type', {\n entityType,\n })\n }\n return {\n processed: 0,\n total: 0,\n tenantScopes: [],\n scopes: [],\n }\n }\n const columns = await getColumnSet(db, source?.tableName ?? table, source?.schema)\n // A probe failure proves nothing about the table, so it cannot be read as \"no tenant\n // column\". Refuse with its own reason rather than letting a database blip masquerade as\n // a permanent classification - and refuse rather than proceed, because proceeding would\n // drop the tenant predicate and stamp the caller's tenant, which is the defect this guard\n // exists for.\n if (columns === null) {\n logger.warn(\"Refusing reindex: could not read the source table's columns\", {\n entityType,\n table,\n tenantId,\n })\n return { processed: 0, total: 0, tenantScopes: [], scopes: [], refused: 'column-probe-failed' }\n }\n const hasOrgCol = columns.has('organization_id')\n const hasTenantCol = columns.has('tenant_id')\n const hasDeletedCol = columns.has('deleted_at')\n\n // `applyBaseWhere()` below can only apply the tenant predicate when the source\n // table HAS a `tenant_id` column; when it does not, it silently drops the\n // predicate the caller asked for. `scopeOverrides.tenantId` further down then\n // stamps every swept row with the caller's tenant anyway. A tenant-scoped\n // reindex of a tenant-less table therefore does two wrong things at once: it\n // reads every tenant's rows, and it files them under whichever tenant happened\n // to run it. Nothing downstream corrects that, because both readers ask for an\n // exact tenant match with no NULL branch, so the rows become searchable and\n // readable as that tenant's own.\n //\n // The condition is derived, not enumerated: it is exactly the set of inputs\n // where a predicate is dropped AND an override is stamped. A `tenantId` of\n // `undefined` or `null` sets no override, so those rows land under\n // `tenant_id = NULL` \u2014 invisible to both readers, but filed under nobody \u2014 and\n // are deliberately left alone here.\n //\n // Indexing every tenant-less table under NULL was considered as the general fix\n // and rejected: an unqualified NULL branch in the readers overloads a value that\n // also means \"written by an unscoped reindex\", so every mis-scoped row would\n // become globally visible \u2014 fail-open, in a fix whose whole value is failing\n // closed. `isTenantGlobalEntityType` is the narrow allowlist for the catalogue\n // case instead; see its comment in ./tenant-global. The readers widen for exactly\n // that declared set and for nothing else, and the projection of a declared type is\n // written under the null tenant just below.\n // A declared platform-wide catalogue has one row per record for every tenant to\n // share, so its projection belongs to no tenant and no organization in particular and\n // is written under `tenant_id = NULL, organization_id = NULL`. That is already where\n // the incremental path files these rows: `resolveQueryIndexRecordScope()` resolves a\n // source table with NEITHER scope column to `kind: 'global'` and requires an explicitly\n // null tenant AND organization. Before this, the sweep disagreed with it and stamped the\n // caller's scope, and since `entity_indexes` is unique on\n // (entity_type, entity_id, organization_id_coalesced) the last caller to reindex simply\n // took the catalogue from the previous one. Both readers in `@open-mercato/search` now\n // carry the matching NULL branch for declared types.\n //\n // The condition matches `loadQueryIndexRowScope()`'s definition of global exactly -\n // NEITHER column, not just no tenant column. Keying on the tenant column alone would let\n // a third-party declaration of a table that HAS `organization_id` take the global branch\n // for a record the event path never classifies as global, so the two writers would\n // disagree again on a different axis.\n //\n // Only the PROJECTION scope moves. `jobScope` keeps the caller's tenant and organization:\n // it records who ran the sweep, so two tenants reindexing the catalogue remain two jobs\n // rather than one that blocks the other behind the active-job guard.\n const writesGlobalProjection = writesGlobalReindexProjection(entityType, columns, source)\n const projectionTenantId = writesGlobalProjection ? null : tenantId\n const projectionOrganizationId = writesGlobalProjection ? null : organizationId\n // Vector work keeps the caller's scope even where the projection moves. Its consumers -\n // the `query_index.vectorize_one` and `query_index.vectorize_purge` subscribers and\n // `removeOrphans` - need a real tenant, and nothing defines a shared vector across\n // dispatch, storage and reads, so a declared catalogue's vectors stay filed per tenant\n // exactly as they were before its projection moved to the null scope.\n const vectorTenantId = writesGlobalProjection ? tenantId : projectionTenantId\n const vectorOrganizationId = writesGlobalProjection ? organizationId : projectionOrganizationId\n\n // Refuse anything tenant-less that is not writing a global projection. That is the\n // no-tenant-column case, and also a declaration this module cannot honour: a declared\n // type whose table carries `organization_id` but no `tenant_id`. Letting the second\n // through would silently drop the tenant predicate and stamp the caller's tenant - the\n // exact defect the guard exists for - while the author believes the declaration took\n // effect. Fail closed and name it, in the spirit of the allowlist itself.\n const tenantlessRefusal = tenantId != null ? resolveTenantlessRefusal(entityType, columns, source) : null\n if (tenantlessRefusal) {\n logger.warn(\n tenantlessRefusal === 'declared-global-but-org-scoped'\n ? 'Refusing tenant-scoped reindex: entity type is declared tenant-global but its table has an organization_id column'\n : 'Refusing tenant-scoped reindex of a table with no tenant_id column',\n { entityType, table, tenantId },\n )\n return {\n processed: 0,\n total: 0,\n tenantScopes: [],\n scopes: [],\n refused: tenantlessRefusal,\n }\n }\n\n const jobScope: JobScope = {\n entityType,\n organizationId: organizationId ?? null,\n tenantId: tenantId ?? null,\n partitionIndex,\n partitionCount: usingPartitions ? partitionCountRaw : null,\n }\n\n if (!force) {\n const activeJob = await db\n .selectFrom('entity_index_jobs' as any)\n .select(['id' as any])\n .where('entity_type' as any, '=', entityType)\n .where('finished_at' as any, 'is', null as any)\n .where(sql<boolean>`organization_id is not distinct from ${null}`)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantId ?? null}`)\n .where(sql<boolean>`partition_index is not distinct from ${partitionIndex}`)\n .where(sql<boolean>`partition_count is not distinct from ${usingPartitions ? partitionCountRaw : null}`)\n .executeTakeFirst()\n if (activeJob) {\n return {\n processed: 0,\n total: 0,\n tenantScopes: [],\n scopes: [],\n }\n }\n }\n\n if (resetCoverage) {\n await cleanupLegacyJobScopes(db, {\n entityType,\n organizationId: jobScope.organizationId ?? null,\n tenantId: jobScope.tenantId ?? null,\n activePartitionCount: jobScope.partitionCount ?? null,\n })\n }\n\n const scopeKey = (tenantValue: string | null, orgValue: string | null) => `${tenantValue ?? '__null__'}|${orgValue ?? '__null__'}`\n\n const applyBaseWhere = <QB extends { where: (...args: any[]) => QB }>(q: QB): QB => {\n let chain = q\n if (hasDeletedCol) chain = chain.where('b.deleted_at' as any, 'is', null as any)\n if (tenantId !== undefined && hasTenantCol) {\n chain = tenantId === null\n ? chain.where('b.tenant_id' as any, 'is', null as any)\n : chain.where('b.tenant_id' as any, '=', tenantId)\n }\n if (organizationId !== undefined && hasOrgCol) {\n chain = organizationId === null\n ? chain.where('b.organization_id' as any, 'is', null as any)\n : chain.where('b.organization_id' as any, '=', organizationId)\n }\n if (usingPartitions && partitionIndex !== null) {\n chain = chain.where(sql<boolean>`mod(abs(hashtext(b.id::text)), ${partitionCountRaw}) = ${partitionIndex}`)\n }\n return chain\n }\n\n type ScopeStats = { tenantId: string | null; organizationId: string | null; count: number }\n const baseCounts = new Map<string, ScopeStats>()\n const registerBaseCount = (tenantValue: string | null, orgValue: string | null, count: number) => {\n const key = scopeKey(tenantValue, orgValue)\n baseCounts.set(key, { tenantId: tenantValue, organizationId: orgValue, count })\n }\n\n const groupByTenant = hasTenantCol && tenantId === undefined\n const groupByOrg = hasOrgCol && organizationId === undefined\n\n if (groupByTenant || groupByOrg) {\n let groupQuery = applyBaseWhere(\n db.selectFrom(`${table} as b` as any).select(sql<number>`count(*)`.as('count')),\n )\n if (groupByTenant) {\n groupQuery = groupQuery.select('b.tenant_id as tenant_id' as any).groupBy('b.tenant_id' as any)\n }\n if (groupByOrg) {\n groupQuery = groupQuery.select('b.organization_id as organization_id' as any).groupBy('b.organization_id' as any)\n }\n const rows = await groupQuery.execute() as Array<Record<string, unknown>>\n for (const row of rows) {\n const bucketTenant = groupByTenant\n ? ((row as any)?.tenant_id ?? null)\n : (projectionTenantId === undefined ? null : projectionTenantId ?? null)\n const bucketOrg = groupByOrg\n ? ((row as any)?.organization_id ?? null)\n : (projectionOrganizationId === undefined ? null : projectionOrganizationId ?? null)\n registerBaseCount(bucketTenant, bucketOrg, toNumber((row as any)?.count))\n }\n } else {\n const row = await applyBaseWhere(\n db.selectFrom(`${table} as b` as any).select(sql<number>`count(*)`.as('count')),\n ).executeTakeFirst() as { count: unknown } | undefined\n const bucketTenant = projectionTenantId === undefined ? null : projectionTenantId ?? null\n const bucketOrg = projectionOrganizationId === undefined ? null : projectionOrganizationId ?? null\n registerBaseCount(bucketTenant, bucketOrg, toNumber(row?.count))\n }\n\n const total = Array.from(baseCounts.values()).reduce((acc, value) => acc + (Number.isFinite(value.count) ? value.count : 0), 0)\n await prepareJob(db, jobScope, 'reindexing', { totalCount: total })\n const jobRow = await db\n .selectFrom('entity_index_jobs' as any)\n .select(['started_at' as any])\n .where('entity_type' as any, '=', entityType)\n .where('organization_id' as any, 'is', null as any)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantId ?? null}`)\n .where(sql<boolean>`partition_index is not distinct from ${partitionIndex}`)\n .where(sql<boolean>`partition_count is not distinct from ${usingPartitions ? partitionCountRaw : null}`)\n .orderBy('started_at' as any, 'desc')\n .executeTakeFirst() as { started_at: Date | string } | undefined\n const jobStartedAt = jobRow?.started_at ? new Date(jobRow.started_at) : new Date()\n const deriveOrg = deriveOrgFromId.has(entityType)\n ? (row: AnyRow) => String(row.id)\n : undefined\n\n const scopeOverrides: { tenantId?: string; orgId?: string } = {}\n if (projectionTenantId !== undefined && projectionTenantId !== null) {\n scopeOverrides.tenantId = String(projectionTenantId)\n }\n if (projectionOrganizationId !== undefined && projectionOrganizationId !== null) {\n scopeOverrides.orgId = String(projectionOrganizationId)\n }\n\n const scopeEntries = Array.from(baseCounts.values()).map((entry) => ({\n tenantId: entry.tenantId,\n organizationId: entry.organizationId,\n }))\n const tenantScopes = Array.from(\n new Set(scopeEntries.map((entry) => entry.tenantId ?? null)),\n )\n\n let processed = 0\n let lastId: string | null = null\n let jobFailed = false\n const writeTotals = createEmptyUpsertIndexBatchResult()\n\n options?.onProgress?.({ processed, total, chunkSize: 0 })\n\n // Partitions run concurrently, so a scope-wide purge here would delete rows a sibling\n // partition has already written and never rebuild them (the run still reports success\n // because progress counts attempted writes). Each partition therefore purges only the\n // slice it is about to rebuild, and every partition purges \u2014 restricting the purge to\n // the coverage-resetting partition would otherwise leave the other slices' stale rows\n // behind on a forced rebuild.\n if (force && (resetCoverage || usingPartitions)) {\n try {\n let purgeQuery = db\n .deleteFrom('entity_indexes' as any)\n .where('entity_type' as any, '=', entityType)\n if (projectionTenantId !== undefined) {\n purgeQuery = purgeQuery.where(sql<boolean>`tenant_id is not distinct from ${projectionTenantId ?? null}`)\n }\n if (projectionOrganizationId !== undefined) {\n purgeQuery = purgeQuery.where(sql<boolean>`organization_id is not distinct from ${projectionOrganizationId ?? null}`)\n }\n if (usingPartitions && partitionIndex !== null) {\n purgeQuery = purgeQuery.where(\n sql<boolean>`mod(abs(hashtext(entity_id::text)), ${partitionCountRaw}) = ${partitionIndex}`,\n )\n }\n await purgeQuery.execute()\n } catch (error) {\n logger.warn('Failed to purge index rows before force reindex', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n partitionIndex: usingPartitions ? partitionIndex : null,\n error: error instanceof Error ? error.message : error,\n })\n }\n }\n\n // The vector purge is scope-wide and cannot be partitioned \u2014 the queued job deletes every\n // vector for the scope. Emitting it from one partition while siblings are already queueing\n // per-record vectorize jobs is the same race the row purge just had, so a partitioned run\n // leaves it to the caller that owns the fan-out (`api/reindex.ts` queues it once, before\n // dispatching any partition).\n if (force && resetCoverage && !usingPartitions && emitVectorize && eventBus) {\n if (vectorTenantId !== undefined) {\n const payload: Record<string, unknown> = {\n entityType,\n tenantId: vectorTenantId ?? null,\n }\n if (vectorOrganizationId !== undefined) payload.organizationId = vectorOrganizationId ?? null\n try {\n await eventBus.emitEvent('query_index.vectorize_purge', payload)\n } catch (err) {\n logger.warn('Failed to queue vector purge before force reindex', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n error: err instanceof Error ? err.message : err,\n })\n }\n } else {\n logger.warn('Skipping vector purge for force reindex without tenant scope', {\n entityType,\n })\n }\n }\n\n if (resetCoverage) {\n // Only meaningful for an unpartitioned run: `baseCounts` holds this partition's slice,\n // so writing it as the scope's base count under-reports by the partition factor, and\n // zeroing indexed_count scope-wide discards deltas siblings have already applied. The\n // authoritative `refreshCoverageSnapshot` at the end of every partition owns the counts\n // for partitioned runs.\n const nowTs = Date.now()\n for (const scope of usingPartitions ? [] : baseCounts.values()) {\n const key = `${entityType}|${scopeKey(scope.tenantId, scope.organizationId)}`\n const last = lastCoverageReset.get(key) ?? 0\n if (force || nowTs - last >= COVERAGE_REFRESH_THROTTLE_MS) {\n await writeCoverageCounts(em, {\n entityType,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n withDeleted: false,\n }, {\n baseCount: scope.count,\n indexedCount: 0,\n vectorCount: emitVectorize ? 0 : undefined,\n })\n lastCoverageReset.set(key, nowTs)\n }\n }\n }\n\n try {\n while (true) {\n let query = applyBaseWhere(\n db\n .selectFrom(`${table} as b` as any)\n .selectAll('b' as any)\n .orderBy('b.id' as any, 'asc')\n .limit(batchSize),\n )\n if (lastId !== null) {\n query = query.where('b.id' as any, '>', lastId)\n }\n const rows = await query.execute() as AnyRow[]\n if (!rows.length) break\n\n const encryption = resolveTenantEncryptionService(em as any)\n const searchTokenGateQueryEngine = createSearchTokenGateQueryEngine(em)\n const dekKeyCache = new Map<string | null, string | null>()\n const encryptDoc = async (\n targetEntity: string,\n doc: Record<string, unknown>,\n scope: { organizationId: string | null; tenantId: string | null },\n ) => {\n return await encryptIndexDocForStorage(\n targetEntity,\n doc,\n { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId ?? null },\n encryption,\n )\n }\n const decryptDoc = async (\n targetEntity: string,\n doc: Record<string, unknown>,\n scope: { organizationId: string | null; tenantId: string | null },\n ) => {\n const result = await decryptIndexDocForSearch(\n targetEntity,\n doc,\n { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId ?? null },\n encryption,\n dekKeyCache,\n )\n if (isSearchDebugEnabled()) {\n logger.debug('Reindex decrypt', buildReindexDecryptDebugPayload(targetEntity, result as Record<string, unknown>, scope))\n }\n return result\n }\n\n const batchResult = await upsertIndexBatch(db, entityType, rows, scopeOverrides, {\n deriveOrganizationId: deriveOrg,\n encryptDoc,\n decryptDoc,\n searchTokenGateQueryEngine,\n })\n mergeUpsertIndexBatchResults(writeTotals, batchResult)\n\n // A whole batch failing is infrastructural (pool exhausted, disk full, KMS down),\n // not a poison record. Abort now instead of grinding through the rest of the table.\n if (batchResult.written === 0 && batchResult.attempted > 0) {\n throw new QueryIndexBatchWriteError(entityType, writeTotals)\n }\n\n const failedInBatch = new Set(batchResult.failedRecordIds)\n const writtenRows = failedInBatch.size ? rows.filter((row) => !failedInBatch.has(String(row.id))) : rows\n\n const coverageDeltas = new Map<string, { tenantId: string | null; organizationId: string | null; delta: number }>()\n for (const row of writtenRows) {\n const scopeTenant = projectionTenantId !== undefined\n ? projectionTenantId ?? null\n : (hasTenantCol ? ((row as AnyRow).tenant_id ?? null) : null)\n const scopeOrg = projectionOrganizationId !== undefined\n ? projectionOrganizationId ?? null\n : (hasOrgCol ? ((row as AnyRow).organization_id ?? null) : (deriveOrg ? deriveOrg(row) ?? null : null))\n const key = scopeKey(scopeTenant ?? null, scopeOrg ?? null)\n const existingDelta = coverageDeltas.get(key)\n if (existingDelta) existingDelta.delta += 1\n else coverageDeltas.set(key, {\n tenantId: scopeTenant ?? null,\n organizationId: scopeOrg ?? null,\n delta: 1,\n })\n }\n if (coverageDeltas.size > 0) {\n await applyCoverageAdjustments(\n em,\n Array.from(coverageDeltas.values()).map((entry) => ({\n entityType,\n tenantId: entry.tenantId,\n organizationId: entry.organizationId,\n withDeleted: false,\n deltaBase: 0,\n deltaIndex: entry.delta,\n })),\n )\n }\n\n if (emitVectorize && eventBus) {\n await Promise.all(\n writtenRows.map((row) => {\n const scopeOrg = vectorOrganizationId !== undefined\n ? vectorOrganizationId ?? null\n : hasOrgCol\n ? ((row as AnyRow).organization_id ?? null)\n : (deriveOrg ? deriveOrg(row) ?? null : null)\n const scopeTenant = vectorTenantId !== undefined\n ? vectorTenantId ?? null\n : (hasTenantCol ? ((row as AnyRow).tenant_id ?? null) : null)\n return eventBus\n .emitEvent('query_index.vectorize_one', {\n entityType,\n recordId: String(row.id),\n organizationId: scopeOrg,\n tenantId: scopeTenant,\n })\n .catch(() => undefined)\n }),\n )\n }\n\n processed += batchResult.written\n lastId = String(rows[rows.length - 1]!.id)\n options?.onProgress?.({ processed, total, chunkSize: batchResult.written })\n await updateJobProgress(db, jobScope, batchResult.written)\n }\n\n // Records this run failed to write still look untouched to the purge predicate, so\n // without the exclusion the purge would delete the index rows it just failed to\n // rebuild \u2014 turning a stale entry into a missing one.\n const purgeExclusions = writeTotals.failedRecordIds\n if (purgeExclusions.length > MAX_PURGE_EXCLUSIONS) {\n logger.warn('Skipping orphan purge after widespread write failures', {\n entityType,\n failedRecords: purgeExclusions.length,\n })\n } else {\n await purgeOrphans(db, {\n entityType,\n tenantId: projectionTenantId,\n organizationId: projectionOrganizationId,\n partitionIndex: usingPartitions ? partitionIndex : null,\n partitionCount: usingPartitions ? partitionCountRaw : null,\n startedAt: jobStartedAt,\n excludeRecordIds: purgeExclusions,\n })\n // The purge above only sees the canonical null scope. Rows earlier sweeps stamped with\n // a caller's tenant and organization are other keys of the same records, so a sweep of\n // a declared catalogue also retires them - after the canonical rows are written, so the\n // catalogue never goes unserved in between.\n if (writesGlobalProjection) {\n await retireScopedCatalogueRows(db, {\n entityType,\n partitionIndex: usingPartitions ? partitionIndex : null,\n partitionCount: usingPartitions ? partitionCountRaw : null,\n excludeRecordIds: purgeExclusions,\n })\n if (resetCoverage) await deleteScopedCoverageForEntity(db, entityType)\n }\n }\n\n if (force && vectorService && (!usingPartitions || partitionIndex === null)) {\n try {\n await vectorService.removeOrphans({\n entityId: entityType,\n tenantId: vectorTenantId,\n organizationId: vectorOrganizationId,\n olderThan: jobStartedAt,\n })\n } catch (error) {\n logger.warn('Failed to prune vector orphans after reindex', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n error: error instanceof Error ? error.message : error,\n })\n }\n }\n\n for (const scope of scopeEntries) {\n await refreshCoverageSnapshot(\n em,\n {\n entityType,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n withDeleted: false,\n },\n )\n }\n\n // Deliberately after the coverage refresh: the authoritative recount is what keeps\n // indexed_count truthful, and it is most worth having when a run has just failed.\n // Throwing here fails the queue job so the loss is visible instead of silent.\n if (writeTotals.searchTokenFailures > 0) {\n logger.warn('Search token writes failed during reindex', {\n entityType,\n batches: writeTotals.searchTokenFailures,\n })\n }\n assertIndexBatchWritesLanded(entityType, writeTotals)\n } catch (error) {\n jobFailed = true\n throw error\n } finally {\n // Still finalized on failure: the scope stays wedged behind the active-job guard\n // while finished_at is null. The status carries the outcome instead.\n await finalizeJob(db, jobScope, jobFailed ? { status: 'failed' } : {})\n }\n\n return {\n processed,\n total,\n scopes: scopeEntries,\n tenantScopes,\n }\n}\n"],
5
- "mappings": "AACA,SAAsB,WAAW;AACjC,SAAS,4CAA4C;AACrD,SAAS,sCAAsC;AAC/C,SAAS,0BAA0B,iCAAiC;AACpE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,wCAAwC;AACjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,mBAAmB,mBAAkC;AAC1E,SAAS,cAAc,iCAAiC;AAExD,SAAS,4BAA4B;AACrC,SAAS,gCAAgC;AACzC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,YAAY,CAAC;AAiDpE,MAAM,6BAA6B;AAC1C,MAAM,qBAAqB;AAM3B,MAAM,uBAAuB;AAC7B,MAAM,kBAAkB,oBAAI,IAAY,CAAC,wBAAwB,CAAC;AAClE,MAAM,+BAA+B,IAAI,KAAK;AAC9C,MAAM,oBAAoB,oBAAI,IAAoB;AAElD,MAAM,6BAA6B,CAAC,gBAAgB,cAAc,aAAa,cAAc,cAAc,iBAAiB,eAAe;AASpI,SAAS,gCACd,YACA,KACA,OAC4B;AAC5B,QAAM,cAAwB,CAAC;AAC/B,aAAW,OAAO,4BAA4B;AAC5C,UAAM,QAAQ,IAAI,GAAG;AACrB,QAAI,OAAO,OAAO,SAAS,QAAQ,UAAU,GAAI,aAAY,KAAK,GAAG;AAAA,EACvE;AACA,SAAO;AAAA,IACL;AAAA,IACA,UAAU,MAAM,YAAY;AAAA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AAAA,IACF;AAEA,eAAW,SAAS,cAAc;AAChC,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,UACE;AAAA,UACA,UAAU,MAAM;AAAA,UAChB,gBAAgB,MAAM;AAAA,UACtB,aAAa;AAAA,QACf;AAAA,MACF;AAAA,IACF;AAKA,QAAI,YAAY,sBAAsB,GAAG;AACvC,aAAO,KAAK,6CAA6C;AAAA,QACvD;AAAA,QACA,SAAS,YAAY;AAAA,MACvB,CAAC;AAAA,IACH;AACA,iCAA6B,YAAY,WAAW;AAAA,EACtD,SAAS,OAAO;AACd,gBAAY;AACZ,UAAM;AAAA,EACR,UAAE;AAGA,UAAM,YAAY,IAAI,UAAU,YAAY,EAAE,QAAQ,SAAS,IAAI,CAAC,CAAC;AAAA,EACvE;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,EACF;AACF;",
6
- "names": []
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport { resolveQueryIndexSourceTableMetadata } from './subscriber-scope'\nimport { resolveTenantEncryptionService } from '@open-mercato/shared/lib/encryption/customFieldValues'\nimport { decryptIndexDocForSearch, encryptIndexDocForStorage } from '@open-mercato/shared/lib/encryption/indexDoc'\nimport {\n upsertIndexBatch,\n assertIndexBatchWritesLanded,\n createEmptyUpsertIndexBatchResult,\n mergeUpsertIndexBatchResults,\n QueryIndexBatchWriteError,\n type AnyRow,\n} from './batch'\nimport { createSearchTokenGateQueryEngine } from './search-entity-policy'\nimport {\n refreshCoverageSnapshot,\n writeCoverageCounts,\n applyCoverageAdjustments,\n deleteScopedCoverageForEntity,\n} from './coverage'\nimport { prepareJob, updateJobProgress, finalizeJob, type JobScope } from './jobs'\nimport { purgeOrphans, retireScopedCatalogueRows } from './stale'\nimport type { VectorIndexService } from '@open-mercato/search/vector'\nimport { isSearchDebugEnabled, resolveCiphertextGuard } from './search-tokens'\nimport { isTenantGlobalEntityType } from './tenant-global'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('query_index').child({ component: 'reindexer' })\n\nexport type ReindexJobOptions = {\n entityType: string\n tenantId?: string | null\n organizationId?: string | null\n force?: boolean\n batchSize?: number\n emitVectorizeEvents?: boolean\n eventBus?: {\n emitEvent(event: string, payload: any, options?: any): Promise<void>\n }\n partitionCount?: number\n partitionIndex?: number\n resetCoverage?: boolean\n onProgress?: (info: { processed: number; total: number; chunkSize: number }) => void\n vectorService?: VectorIndexService | null\n}\n\n/**\n * Why a sweep did no work, when it did none on purpose.\n *\n * A refused run is otherwise byte-identical to a successful sweep that found zero rows,\n * and the surfaces an operator reads - `indexer_status_logs`, the indexer status page,\n * the CLI's `0 / 0 (0.00%)` - report the second. The allowlist's safety argument is that\n * a missing `registerTenantGlobalEntityTypes()` declaration \"shows up in the log\", so the\n * log the product surfaces has to be able to say it.\n */\nexport type ReindexRefusalReason =\n /** The source table has no `tenant_id` column and the type is not a declared catalogue. */\n | 'no-tenant-column'\n /** `information_schema` could not be read, so no column could be proven to exist. */\n | 'column-probe-failed'\n /**\n * The type IS declared tenant-global, but its table carries `organization_id` while\n * lacking `tenant_id`. A global projection means both scope columns absent - the same\n * definition `loadQueryIndexRowScope()` uses - so the declaration cannot be honoured.\n */\n | 'declared-global-but-org-scoped'\n\nexport type ReindexJobResult = {\n processed: number\n total: number\n tenantScopes: Array<string | null>\n scopes: Array<{ tenantId: string | null; organizationId: string | null }>\n /** Absent on a sweep that ran. Present, with the reason, on one that deliberately did not. */\n refused?: ReindexRefusalReason\n}\n\nexport const DEFAULT_REINDEX_PARTITIONS = 5\nconst DEFAULT_BATCH_SIZE = 500\n/**\n * Above this many failed records the purge exclusion list stops being a sane query, so\n * the purge is skipped entirely instead. Failing closed keeps stale rows; the alternative\n * deletes index entries the run failed to rebuild.\n */\nconst MAX_PURGE_EXCLUSIONS = 1000\nconst deriveOrgFromId = new Set<string>(['directory:organization'])\nconst COVERAGE_REFRESH_THROTTLE_MS = 5 * 60 * 1000\nconst lastCoverageReset = new Map<string, number>()\n\nconst REINDEX_DECRYPT_DEBUG_KEYS = ['display_name', 'first_name', 'last_name', 'brand_name', 'legal_name', 'primary_email', 'primary_phone'] as const\n\nexport type ReindexDecryptDebugPayload = {\n entityType: string\n tenantId: string | null\n organizationId: string | null\n keys: string[]\n}\n\nexport function buildReindexDecryptDebugPayload(\n entityType: string,\n doc: Record<string, unknown>,\n scope: { organizationId: string | null; tenantId: string | null },\n): ReindexDecryptDebugPayload {\n const presentKeys: string[] = []\n for (const key of REINDEX_DECRYPT_DEBUG_KEYS) {\n const value = doc[key]\n if (key in doc && value != null && value !== '') presentKeys.push(key)\n }\n return {\n entityType,\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId ?? null,\n keys: presentKeys,\n }\n}\n\nasync function cleanupLegacyJobScopes(\n db: Kysely<any>,\n options: {\n entityType: string\n organizationId: string | null\n tenantId: string | null\n activePartitionCount: number | null\n },\n): Promise<void> {\n await db\n .deleteFrom('entity_index_jobs' as any)\n .where('entity_type' as any, '=', options.entityType)\n .where(sql<boolean>`organization_id is not distinct from ${options.organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${options.tenantId}`)\n .where(sql<boolean>`partition_count is distinct from ${options.activePartitionCount}`)\n .execute()\n}\n\nfunction toNumber(value: unknown): number {\n if (typeof value === 'number') return Number.isFinite(value) ? value : 0\n if (typeof value === 'string') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : 0\n }\n return 0\n}\n\n/**\n * Returns `null` - never an empty set - when the probe itself fails.\n *\n * An empty set is indistinguishable from \"this table has no columns we care about\", so a\n * transient failure (an aborted transaction on the same connection, a statement timeout, a\n * blip during a partition-parallel sweep) would make every entity type look tenant-less and\n * refuse every tenant-scoped reindex, reported as a successful zero-row run. Failing closed\n * is right; failing closed silently and globally is the hardest state to diagnose.\n */\nasync function getColumnSet(db: Kysely<any>, tableName: string, schema?: string): Promise<Set<string> | null> {\n try {\n const rows = await db\n .selectFrom('information_schema.columns' as any)\n .select(['column_name' as any])\n .where(schema ? sql<boolean>`table_schema = ${schema}` : sql<boolean>`table_schema = current_schema()`)\n .where('table_name' as any, '=', tableName)\n .execute() as Array<{ column_name: string }>\n return new Set(rows.map((row) => String(row.column_name).toLowerCase()))\n } catch (error) {\n logger.warn('Failed to read information_schema.columns for a reindex target', {\n table: tableName,\n error: error instanceof Error ? error.message : String(error),\n })\n reportColumnProbeFailure(error, tableName)\n return null\n }\n}\n\n/**\n * The probe's caller refuses the sweep whatever happens here, so a telemetry backend that\n * throws must not turn that refusal into a failed job.\n */\nfunction reportColumnProbeFailure(error: unknown, tableName: string): void {\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'query_index',\n code: 'query_index.column_probe_failed',\n attributes: { table: tableName },\n })\n } catch (telemetryError) {\n logger.warn('Failed to report a column probe failure', {\n table: tableName,\n error: telemetryError instanceof Error ? telemetryError.message : String(telemetryError),\n })\n }\n}\n\ntype ReindexSourceMetadata = ReturnType<typeof resolveQueryIndexSourceTableMetadata>\n\nfunction writesGlobalReindexProjection(\n entityType: string,\n columns: Set<string>,\n source: ReindexSourceMetadata,\n): boolean {\n return columns.has('id')\n && !columns.has('tenant_id')\n && !columns.has('organization_id')\n && !source?.tenantColumn\n && !source?.organizationColumn\n && isTenantGlobalEntityType(entityType)\n}\n\nfunction resolveTenantlessRefusal(\n entityType: string,\n columns: Set<string>,\n source: ReindexSourceMetadata,\n): Exclude<ReindexRefusalReason, 'column-probe-failed'> | null {\n if (columns.has('tenant_id')) return null\n if (writesGlobalReindexProjection(entityType, columns, source)) return null\n return isTenantGlobalEntityType(entityType) ? 'declared-global-but-org-scoped' : 'no-tenant-column'\n}\n\n/**\n * Answers, without logging, whether a tenant-scoped sweep of `entityType` would be refused\n * because its source table has no `tenant_id` column and the type is not a declared\n * tenant-global catalogue. Callers that enumerate every registered entity type for one\n * tenant (e.g. `mercato query_index reindex --tenant <id>` during `mercato init`) use it to\n * leave such types out up front, so the guard inside `reindexEntity()` keeps warning only\n * for callers that genuinely aimed a tenant-scoped sweep at a tenant-less table.\n *\n * Deliberately narrow: an unregistered type, a failed column probe, or a tenant-global\n * declaration that cannot be honoured all return `false`, so those still reach the guard\n * and surface their own diagnostics.\n */\nexport async function isTenantlessReindexTarget(\n em: EntityManager,\n entityType: string,\n): Promise<boolean> {\n if (!entityType) return false\n const source = resolveQueryIndexSourceTableMetadata(em, entityType)\n if (!source?.table) return false\n const db = em.getKysely<Record<string, Record<string, unknown>>>()\n const columns = await getColumnSet(db, source.tableName ?? source.table, source.schema)\n if (columns === null) return false\n return resolveTenantlessRefusal(entityType, columns, source) === 'no-tenant-column'\n}\n\nexport async function reindexEntity(\n em: EntityManager,\n options: ReindexJobOptions,\n): Promise<ReindexJobResult> {\n const entityType = String(options?.entityType || '')\n if (!entityType) {\n return {\n processed: 0,\n total: 0,\n tenantScopes: [],\n scopes: [],\n }\n }\n const tenantIdInput = options?.tenantId\n const tenantId = tenantIdInput === 'undefined' ? undefined : tenantIdInput\n const organizationIdInput = options?.organizationId\n const organizationId = organizationIdInput === 'undefined' ? undefined : organizationIdInput\n const force = options?.force === true\n const batchSize = Number.isFinite(options?.batchSize) && options!.batchSize! > 0\n ? Math.max(1, Math.trunc(options!.batchSize!))\n : DEFAULT_BATCH_SIZE\n const emitVectorize = options?.emitVectorizeEvents === true\n const eventBus = options?.eventBus\n const vectorService = options?.vectorService ?? null\n const partitionCountRaw = Number.isFinite(options?.partitionCount)\n ? Math.max(1, Math.trunc(options!.partitionCount!))\n : 1\n const usingPartitions = partitionCountRaw > 1\n const partitionIndexRaw = Number.isFinite(options?.partitionIndex)\n ? Math.max(0, Math.trunc(options!.partitionIndex!))\n : 0\n const partitionIndex = usingPartitions\n ? Math.min(partitionIndexRaw, partitionCountRaw - 1)\n : null\n const resetCoverage = options?.resetCoverage ?? (!usingPartitions || partitionIndex === 0)\n\n const db = (em as any).getKysely() as Kysely<any>\n // Resolve the source table strictly via registered MikroORM metadata. We must\n // never fall back to a pluralized guess derived from the caller-supplied id\n // here: doing so would let a principal with `query_index.reindex` point the\n // reindexer at arbitrary tables (e.g. `auth_users`, `users`) and read their\n // rows into the index, bypassing tenant scoping and entity-level encryption.\n const source = resolveQueryIndexSourceTableMetadata(em, entityType)\n const table = source?.table\n if (!table || entityType === 'query_index:search_token' || table === 'search_tokens') {\n if (!table) {\n logger.warn('Refusing to reindex unregistered entity type', {\n entityType,\n })\n }\n return {\n processed: 0,\n total: 0,\n tenantScopes: [],\n scopes: [],\n }\n }\n const columns = await getColumnSet(db, source?.tableName ?? table, source?.schema)\n // A probe failure proves nothing about the table, so it cannot be read as \"no tenant\n // column\". Refuse with its own reason rather than letting a database blip masquerade as\n // a permanent classification - and refuse rather than proceed, because proceeding would\n // drop the tenant predicate and stamp the caller's tenant, which is the defect this guard\n // exists for.\n if (columns === null) {\n logger.warn(\"Refusing reindex: could not read the source table's columns\", {\n entityType,\n table,\n tenantId,\n })\n return { processed: 0, total: 0, tenantScopes: [], scopes: [], refused: 'column-probe-failed' }\n }\n const hasOrgCol = columns.has('organization_id')\n const hasTenantCol = columns.has('tenant_id')\n const hasDeletedCol = columns.has('deleted_at')\n\n // `applyBaseWhere()` below can only apply the tenant predicate when the source\n // table HAS a `tenant_id` column; when it does not, it silently drops the\n // predicate the caller asked for. `scopeOverrides.tenantId` further down then\n // stamps every swept row with the caller's tenant anyway. A tenant-scoped\n // reindex of a tenant-less table therefore does two wrong things at once: it\n // reads every tenant's rows, and it files them under whichever tenant happened\n // to run it. Nothing downstream corrects that, because both readers ask for an\n // exact tenant match with no NULL branch, so the rows become searchable and\n // readable as that tenant's own.\n //\n // The condition is derived, not enumerated: it is exactly the set of inputs\n // where a predicate is dropped AND an override is stamped. A `tenantId` of\n // `undefined` or `null` sets no override, so those rows land under\n // `tenant_id = NULL` \u2014 invisible to both readers, but filed under nobody \u2014 and\n // are deliberately left alone here.\n //\n // Indexing every tenant-less table under NULL was considered as the general fix\n // and rejected: an unqualified NULL branch in the readers overloads a value that\n // also means \"written by an unscoped reindex\", so every mis-scoped row would\n // become globally visible \u2014 fail-open, in a fix whose whole value is failing\n // closed. `isTenantGlobalEntityType` is the narrow allowlist for the catalogue\n // case instead; see its comment in ./tenant-global. The readers widen for exactly\n // that declared set and for nothing else, and the projection of a declared type is\n // written under the null tenant just below.\n // A declared platform-wide catalogue has one row per record for every tenant to\n // share, so its projection belongs to no tenant and no organization in particular and\n // is written under `tenant_id = NULL, organization_id = NULL`. That is already where\n // the incremental path files these rows: `resolveQueryIndexRecordScope()` resolves a\n // source table with NEITHER scope column to `kind: 'global'` and requires an explicitly\n // null tenant AND organization. Before this, the sweep disagreed with it and stamped the\n // caller's scope, and since `entity_indexes` is unique on\n // (entity_type, entity_id, organization_id_coalesced) the last caller to reindex simply\n // took the catalogue from the previous one. Both readers in `@open-mercato/search` now\n // carry the matching NULL branch for declared types.\n //\n // The condition matches `loadQueryIndexRowScope()`'s definition of global exactly -\n // NEITHER column, not just no tenant column. Keying on the tenant column alone would let\n // a third-party declaration of a table that HAS `organization_id` take the global branch\n // for a record the event path never classifies as global, so the two writers would\n // disagree again on a different axis.\n //\n // Only the PROJECTION scope moves. `jobScope` keeps the caller's tenant and organization:\n // it records who ran the sweep, so two tenants reindexing the catalogue remain two jobs\n // rather than one that blocks the other behind the active-job guard.\n const writesGlobalProjection = writesGlobalReindexProjection(entityType, columns, source)\n const projectionTenantId = writesGlobalProjection ? null : tenantId\n const projectionOrganizationId = writesGlobalProjection ? null : organizationId\n // Vector work keeps the caller's scope even where the projection moves. Its consumers -\n // the `query_index.vectorize_one` and `query_index.vectorize_purge` subscribers and\n // `removeOrphans` - need a real tenant, and nothing defines a shared vector across\n // dispatch, storage and reads, so a declared catalogue's vectors stay filed per tenant\n // exactly as they were before its projection moved to the null scope.\n const vectorTenantId = writesGlobalProjection ? tenantId : projectionTenantId\n const vectorOrganizationId = writesGlobalProjection ? organizationId : projectionOrganizationId\n\n // Refuse anything tenant-less that is not writing a global projection. That is the\n // no-tenant-column case, and also a declaration this module cannot honour: a declared\n // type whose table carries `organization_id` but no `tenant_id`. Letting the second\n // through would silently drop the tenant predicate and stamp the caller's tenant - the\n // exact defect the guard exists for - while the author believes the declaration took\n // effect. Fail closed and name it, in the spirit of the allowlist itself.\n const tenantlessRefusal = tenantId != null ? resolveTenantlessRefusal(entityType, columns, source) : null\n if (tenantlessRefusal) {\n logger.warn(\n tenantlessRefusal === 'declared-global-but-org-scoped'\n ? 'Refusing tenant-scoped reindex: entity type is declared tenant-global but its table has an organization_id column'\n : 'Refusing tenant-scoped reindex of a table with no tenant_id column',\n { entityType, table, tenantId },\n )\n return {\n processed: 0,\n total: 0,\n tenantScopes: [],\n scopes: [],\n refused: tenantlessRefusal,\n }\n }\n\n const jobScope: JobScope = {\n entityType,\n organizationId: organizationId ?? null,\n tenantId: tenantId ?? null,\n partitionIndex,\n partitionCount: usingPartitions ? partitionCountRaw : null,\n }\n\n if (!force) {\n const activeJob = await db\n .selectFrom('entity_index_jobs' as any)\n .select(['id' as any])\n .where('entity_type' as any, '=', entityType)\n .where('finished_at' as any, 'is', null as any)\n .where(sql<boolean>`organization_id is not distinct from ${null}`)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantId ?? null}`)\n .where(sql<boolean>`partition_index is not distinct from ${partitionIndex}`)\n .where(sql<boolean>`partition_count is not distinct from ${usingPartitions ? partitionCountRaw : null}`)\n .executeTakeFirst()\n if (activeJob) {\n return {\n processed: 0,\n total: 0,\n tenantScopes: [],\n scopes: [],\n }\n }\n }\n\n if (resetCoverage) {\n await cleanupLegacyJobScopes(db, {\n entityType,\n organizationId: jobScope.organizationId ?? null,\n tenantId: jobScope.tenantId ?? null,\n activePartitionCount: jobScope.partitionCount ?? null,\n })\n }\n\n const scopeKey = (tenantValue: string | null, orgValue: string | null) => `${tenantValue ?? '__null__'}|${orgValue ?? '__null__'}`\n\n const applyBaseWhere = <QB extends { where: (...args: any[]) => QB }>(q: QB): QB => {\n let chain = q\n if (hasDeletedCol) chain = chain.where('b.deleted_at' as any, 'is', null as any)\n if (tenantId !== undefined && hasTenantCol) {\n chain = tenantId === null\n ? chain.where('b.tenant_id' as any, 'is', null as any)\n : chain.where('b.tenant_id' as any, '=', tenantId)\n }\n if (organizationId !== undefined && hasOrgCol) {\n chain = organizationId === null\n ? chain.where('b.organization_id' as any, 'is', null as any)\n : chain.where('b.organization_id' as any, '=', organizationId)\n }\n if (usingPartitions && partitionIndex !== null) {\n chain = chain.where(sql<boolean>`mod(abs(hashtext(b.id::text)), ${partitionCountRaw}) = ${partitionIndex}`)\n }\n return chain\n }\n\n type ScopeStats = { tenantId: string | null; organizationId: string | null; count: number }\n const baseCounts = new Map<string, ScopeStats>()\n const registerBaseCount = (tenantValue: string | null, orgValue: string | null, count: number) => {\n const key = scopeKey(tenantValue, orgValue)\n baseCounts.set(key, { tenantId: tenantValue, organizationId: orgValue, count })\n }\n\n const groupByTenant = hasTenantCol && tenantId === undefined\n const groupByOrg = hasOrgCol && organizationId === undefined\n\n if (groupByTenant || groupByOrg) {\n let groupQuery = applyBaseWhere(\n db.selectFrom(`${table} as b` as any).select(sql<number>`count(*)`.as('count')),\n )\n if (groupByTenant) {\n groupQuery = groupQuery.select('b.tenant_id as tenant_id' as any).groupBy('b.tenant_id' as any)\n }\n if (groupByOrg) {\n groupQuery = groupQuery.select('b.organization_id as organization_id' as any).groupBy('b.organization_id' as any)\n }\n const rows = await groupQuery.execute() as Array<Record<string, unknown>>\n for (const row of rows) {\n const bucketTenant = groupByTenant\n ? ((row as any)?.tenant_id ?? null)\n : (projectionTenantId === undefined ? null : projectionTenantId ?? null)\n const bucketOrg = groupByOrg\n ? ((row as any)?.organization_id ?? null)\n : (projectionOrganizationId === undefined ? null : projectionOrganizationId ?? null)\n registerBaseCount(bucketTenant, bucketOrg, toNumber((row as any)?.count))\n }\n } else {\n const row = await applyBaseWhere(\n db.selectFrom(`${table} as b` as any).select(sql<number>`count(*)`.as('count')),\n ).executeTakeFirst() as { count: unknown } | undefined\n const bucketTenant = projectionTenantId === undefined ? null : projectionTenantId ?? null\n const bucketOrg = projectionOrganizationId === undefined ? null : projectionOrganizationId ?? null\n registerBaseCount(bucketTenant, bucketOrg, toNumber(row?.count))\n }\n\n const total = Array.from(baseCounts.values()).reduce((acc, value) => acc + (Number.isFinite(value.count) ? value.count : 0), 0)\n await prepareJob(db, jobScope, 'reindexing', { totalCount: total })\n const jobRow = await db\n .selectFrom('entity_index_jobs' as any)\n .select(['started_at' as any])\n .where('entity_type' as any, '=', entityType)\n .where('organization_id' as any, 'is', null as any)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantId ?? null}`)\n .where(sql<boolean>`partition_index is not distinct from ${partitionIndex}`)\n .where(sql<boolean>`partition_count is not distinct from ${usingPartitions ? partitionCountRaw : null}`)\n .orderBy('started_at' as any, 'desc')\n .executeTakeFirst() as { started_at: Date | string } | undefined\n const jobStartedAt = jobRow?.started_at ? new Date(jobRow.started_at) : new Date()\n const deriveOrg = deriveOrgFromId.has(entityType)\n ? (row: AnyRow) => String(row.id)\n : undefined\n\n const scopeOverrides: { tenantId?: string; orgId?: string } = {}\n if (projectionTenantId !== undefined && projectionTenantId !== null) {\n scopeOverrides.tenantId = String(projectionTenantId)\n }\n if (projectionOrganizationId !== undefined && projectionOrganizationId !== null) {\n scopeOverrides.orgId = String(projectionOrganizationId)\n }\n\n const scopeEntries = Array.from(baseCounts.values()).map((entry) => ({\n tenantId: entry.tenantId,\n organizationId: entry.organizationId,\n }))\n const tenantScopes = Array.from(\n new Set(scopeEntries.map((entry) => entry.tenantId ?? null)),\n )\n\n let processed = 0\n let lastId: string | null = null\n let jobFailed = false\n const writeTotals = createEmptyUpsertIndexBatchResult()\n\n options?.onProgress?.({ processed, total, chunkSize: 0 })\n\n // Partitions run concurrently, so a scope-wide purge here would delete rows a sibling\n // partition has already written and never rebuild them (the run still reports success\n // because progress counts attempted writes). Each partition therefore purges only the\n // slice it is about to rebuild, and every partition purges \u2014 restricting the purge to\n // the coverage-resetting partition would otherwise leave the other slices' stale rows\n // behind on a forced rebuild.\n if (force && (resetCoverage || usingPartitions)) {\n try {\n let purgeQuery = db\n .deleteFrom('entity_indexes' as any)\n .where('entity_type' as any, '=', entityType)\n if (projectionTenantId !== undefined) {\n purgeQuery = purgeQuery.where(sql<boolean>`tenant_id is not distinct from ${projectionTenantId ?? null}`)\n }\n if (projectionOrganizationId !== undefined) {\n purgeQuery = purgeQuery.where(sql<boolean>`organization_id is not distinct from ${projectionOrganizationId ?? null}`)\n }\n if (usingPartitions && partitionIndex !== null) {\n purgeQuery = purgeQuery.where(\n sql<boolean>`mod(abs(hashtext(entity_id::text)), ${partitionCountRaw}) = ${partitionIndex}`,\n )\n }\n await purgeQuery.execute()\n } catch (error) {\n logger.warn('Failed to purge index rows before force reindex', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n partitionIndex: usingPartitions ? partitionIndex : null,\n error: error instanceof Error ? error.message : error,\n })\n }\n }\n\n // The vector purge is scope-wide and cannot be partitioned \u2014 the queued job deletes every\n // vector for the scope. Emitting it from one partition while siblings are already queueing\n // per-record vectorize jobs is the same race the row purge just had, so a partitioned run\n // leaves it to the caller that owns the fan-out (`api/reindex.ts` queues it once, before\n // dispatching any partition).\n if (force && resetCoverage && !usingPartitions && emitVectorize && eventBus) {\n if (vectorTenantId !== undefined) {\n const payload: Record<string, unknown> = {\n entityType,\n tenantId: vectorTenantId ?? null,\n }\n if (vectorOrganizationId !== undefined) payload.organizationId = vectorOrganizationId ?? null\n try {\n await eventBus.emitEvent('query_index.vectorize_purge', payload)\n } catch (err) {\n logger.warn('Failed to queue vector purge before force reindex', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n error: err instanceof Error ? err.message : err,\n })\n }\n } else {\n logger.warn('Skipping vector purge for force reindex without tenant scope', {\n entityType,\n })\n }\n }\n\n if (resetCoverage) {\n // Only meaningful for an unpartitioned run: `baseCounts` holds this partition's slice,\n // so writing it as the scope's base count under-reports by the partition factor, and\n // zeroing indexed_count scope-wide discards deltas siblings have already applied. The\n // authoritative `refreshCoverageSnapshot` at the end of every partition owns the counts\n // for partitioned runs.\n const nowTs = Date.now()\n for (const scope of usingPartitions ? [] : baseCounts.values()) {\n const key = `${entityType}|${scopeKey(scope.tenantId, scope.organizationId)}`\n const last = lastCoverageReset.get(key) ?? 0\n if (force || nowTs - last >= COVERAGE_REFRESH_THROTTLE_MS) {\n await writeCoverageCounts(em, {\n entityType,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n withDeleted: false,\n }, {\n baseCount: scope.count,\n indexedCount: 0,\n vectorCount: emitVectorize ? 0 : undefined,\n })\n lastCoverageReset.set(key, nowTs)\n }\n }\n }\n\n try {\n while (true) {\n let query = applyBaseWhere(\n db\n .selectFrom(`${table} as b` as any)\n .selectAll('b' as any)\n .orderBy('b.id' as any, 'asc')\n .limit(batchSize),\n )\n if (lastId !== null) {\n query = query.where('b.id' as any, '>', lastId)\n }\n const rows = await query.execute() as AnyRow[]\n if (!rows.length) break\n\n const encryption = resolveTenantEncryptionService(em as any)\n const searchTokenGateQueryEngine = createSearchTokenGateQueryEngine(em)\n const dekKeyCache = new Map<string | null, string | null>()\n const encryptDoc = async (\n targetEntity: string,\n doc: Record<string, unknown>,\n scope: { organizationId: string | null; tenantId: string | null },\n ) => {\n return await encryptIndexDocForStorage(\n targetEntity,\n doc,\n { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId ?? null },\n encryption,\n )\n }\n const decryptDoc = async (\n targetEntity: string,\n doc: Record<string, unknown>,\n scope: { organizationId: string | null; tenantId: string | null },\n ) => {\n const tenantId = scope.tenantId ?? null\n if (dekKeyCache.get(tenantId) === null) dekKeyCache.delete(tenantId)\n const result = await decryptIndexDocForSearch(\n targetEntity,\n doc,\n { tenantId, organizationId: scope.organizationId ?? null },\n encryption,\n dekKeyCache,\n )\n if (isSearchDebugEnabled()) {\n logger.debug('Reindex decrypt', buildReindexDecryptDebugPayload(targetEntity, result as Record<string, unknown>, scope))\n }\n return result\n }\n\n const batchResult = await upsertIndexBatch(db, entityType, rows, scopeOverrides, {\n deriveOrganizationId: deriveOrg,\n encryptDoc,\n decryptDoc,\n searchTokenGateQueryEngine,\n ciphertextGuard: () => resolveCiphertextGuard(encryption),\n })\n mergeUpsertIndexBatchResults(writeTotals, batchResult)\n\n // A whole batch failing is infrastructural (pool exhausted, disk full, KMS down),\n // not a poison record. Abort now instead of grinding through the rest of the table.\n if (batchResult.written === 0 && batchResult.attempted > 0) {\n throw new QueryIndexBatchWriteError(entityType, writeTotals)\n }\n\n const failedInBatch = new Set(batchResult.failedRecordIds)\n const writtenRows = failedInBatch.size ? rows.filter((row) => !failedInBatch.has(String(row.id))) : rows\n\n const coverageDeltas = new Map<string, { tenantId: string | null; organizationId: string | null; delta: number }>()\n for (const row of writtenRows) {\n const scopeTenant = projectionTenantId !== undefined\n ? projectionTenantId ?? null\n : (hasTenantCol ? ((row as AnyRow).tenant_id ?? null) : null)\n const scopeOrg = projectionOrganizationId !== undefined\n ? projectionOrganizationId ?? null\n : (hasOrgCol ? ((row as AnyRow).organization_id ?? null) : (deriveOrg ? deriveOrg(row) ?? null : null))\n const key = scopeKey(scopeTenant ?? null, scopeOrg ?? null)\n const existingDelta = coverageDeltas.get(key)\n if (existingDelta) existingDelta.delta += 1\n else coverageDeltas.set(key, {\n tenantId: scopeTenant ?? null,\n organizationId: scopeOrg ?? null,\n delta: 1,\n })\n }\n if (coverageDeltas.size > 0) {\n await applyCoverageAdjustments(\n em,\n Array.from(coverageDeltas.values()).map((entry) => ({\n entityType,\n tenantId: entry.tenantId,\n organizationId: entry.organizationId,\n withDeleted: false,\n deltaBase: 0,\n deltaIndex: entry.delta,\n })),\n )\n }\n\n if (emitVectorize && eventBus) {\n await Promise.all(\n writtenRows.map((row) => {\n const scopeOrg = vectorOrganizationId !== undefined\n ? vectorOrganizationId ?? null\n : hasOrgCol\n ? ((row as AnyRow).organization_id ?? null)\n : (deriveOrg ? deriveOrg(row) ?? null : null)\n const scopeTenant = vectorTenantId !== undefined\n ? vectorTenantId ?? null\n : (hasTenantCol ? ((row as AnyRow).tenant_id ?? null) : null)\n return eventBus\n .emitEvent('query_index.vectorize_one', {\n entityType,\n recordId: String(row.id),\n organizationId: scopeOrg,\n tenantId: scopeTenant,\n })\n .catch(() => undefined)\n }),\n )\n }\n\n processed += batchResult.written\n lastId = String(rows[rows.length - 1]!.id)\n options?.onProgress?.({ processed, total, chunkSize: batchResult.written })\n await updateJobProgress(db, jobScope, batchResult.written)\n }\n\n // Records this run failed to write still look untouched to the purge predicate, so\n // without the exclusion the purge would delete the index rows it just failed to\n // rebuild \u2014 turning a stale entry into a missing one.\n const purgeExclusions = writeTotals.failedRecordIds\n if (purgeExclusions.length > MAX_PURGE_EXCLUSIONS) {\n logger.warn('Skipping orphan purge after widespread write failures', {\n entityType,\n failedRecords: purgeExclusions.length,\n })\n } else {\n await purgeOrphans(db, {\n entityType,\n tenantId: projectionTenantId,\n organizationId: projectionOrganizationId,\n partitionIndex: usingPartitions ? partitionIndex : null,\n partitionCount: usingPartitions ? partitionCountRaw : null,\n startedAt: jobStartedAt,\n excludeRecordIds: purgeExclusions,\n })\n // The purge above only sees the canonical null scope. Rows earlier sweeps stamped with\n // a caller's tenant and organization are other keys of the same records, so a sweep of\n // a declared catalogue also retires them - after the canonical rows are written, so the\n // catalogue never goes unserved in between.\n if (writesGlobalProjection) {\n await retireScopedCatalogueRows(db, {\n entityType,\n partitionIndex: usingPartitions ? partitionIndex : null,\n partitionCount: usingPartitions ? partitionCountRaw : null,\n excludeRecordIds: purgeExclusions,\n })\n if (resetCoverage) await deleteScopedCoverageForEntity(db, entityType)\n }\n }\n\n if (force && vectorService && (!usingPartitions || partitionIndex === null)) {\n try {\n await vectorService.removeOrphans({\n entityId: entityType,\n tenantId: vectorTenantId,\n organizationId: vectorOrganizationId,\n olderThan: jobStartedAt,\n })\n } catch (error) {\n logger.warn('Failed to prune vector orphans after reindex', {\n entityType,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n error: error instanceof Error ? error.message : error,\n })\n }\n }\n\n for (const scope of scopeEntries) {\n await refreshCoverageSnapshot(\n em,\n {\n entityType,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n withDeleted: false,\n },\n )\n }\n\n // Deliberately after the coverage refresh: the authoritative recount is what keeps\n // indexed_count truthful, and it is most worth having when a run has just failed.\n // Throwing here fails the queue job so the loss is visible instead of silent.\n if (writeTotals.searchTokenFailures > 0) {\n logger.warn('Search token writes failed during reindex', {\n entityType,\n batches: writeTotals.searchTokenFailures,\n })\n }\n assertIndexBatchWritesLanded(entityType, writeTotals)\n } catch (error) {\n jobFailed = true\n throw error\n } finally {\n // Still finalized on failure: the scope stays wedged behind the active-job guard\n // while finished_at is null. The status carries the outcome instead.\n await finalizeJob(db, jobScope, jobFailed ? { status: 'failed' } : {})\n }\n\n return {\n processed,\n total,\n scopes: scopeEntries,\n tenantScopes,\n }\n}\n"],
5
+ "mappings": "AACA,SAAsB,WAAW;AACjC,SAAS,4CAA4C;AACrD,SAAS,sCAAsC;AAC/C,SAAS,0BAA0B,iCAAiC;AACpE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,wCAAwC;AACjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,mBAAmB,mBAAkC;AAC1E,SAAS,cAAc,iCAAiC;AAExD,SAAS,sBAAsB,8BAA8B;AAC7D,SAAS,gCAAgC;AACzC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,YAAY,CAAC;AAiDpE,MAAM,6BAA6B;AAC1C,MAAM,qBAAqB;AAM3B,MAAM,uBAAuB;AAC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AAM,0BAA0B,IAAI;AAAA,UAClC;AAAA,UACA,gBAAgB,kBAAkB,iBAAiB;AAAA,UACnD,gBAAgB,kBAAkB,oBAAoB;AAAA,UACtD,kBAAkB;AAAA,QACpB,CAAC;AACD,YAAI,cAAe,OAAM,8BAA8B,IAAI,UAAU;AAAA,MACvE;AAAA,IACF;AAEA,QAAI,SAAS,kBAAkB,CAAC,mBAAmB,mBAAmB,OAAO;AAC3E,UAAI;AACF,cAAM,cAAc,cAAc;AAAA,UAChC,UAAU;AAAA,UACV,UAAU;AAAA,UACV,gBAAgB;AAAA,UAChB,WAAW;AAAA,QACb,CAAC;AAAA,MACH,SAAS,OAAO;AACd,eAAO,KAAK,gDAAgD;AAAA,UAC1D;AAAA,UACA,UAAU,YAAY;AAAA,UACtB,gBAAgB,kBAAkB;AAAA,UAClC,OAAO,iBAAiB,QAAQ,MAAM,UAAU;AAAA,QAClD,CAAC;AAAA,MACH;AAAA,IACF;AAEA,eAAW,SAAS,cAAc;AAChC,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,UACE;AAAA,UACA,UAAU,MAAM;AAAA,UAChB,gBAAgB,MAAM;AAAA,UACtB,aAAa;AAAA,QACf;AAAA,MACF;AAAA,IACF;AAKA,QAAI,YAAY,sBAAsB,GAAG;AACvC,aAAO,KAAK,6CAA6C;AAAA,QACvD;AAAA,QACA,SAAS,YAAY;AAAA,MACvB,CAAC;AAAA,IACH;AACA,iCAA6B,YAAY,WAAW;AAAA,EACtD,SAAS,OAAO;AACd,gBAAY;AACZ,UAAM;AAAA,EACR,UAAE;AAGA,UAAM,YAAY,IAAI,UAAU,YAAY,EAAE,QAAQ,SAAS,IAAI,CAAC,CAAC;AAAA,EACvE;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,EACF;AACF;",
6
+ "names": ["tenantId"]
7
7
  }
@@ -46,6 +46,10 @@ function shouldGuardCiphertext() {
46
46
  guardKmsService ??= createKmsService();
47
47
  return resolveEncryptionMode(guardKmsService) !== "active";
48
48
  }
49
+ function resolveCiphertextGuard(encryption) {
50
+ if (typeof encryption?.isEnabled !== "function") return shouldGuardCiphertext();
51
+ return !encryption.isEnabled();
52
+ }
49
53
  function ciphertextFieldsOf(doc, guard) {
50
54
  const fields = /* @__PURE__ */ new Set();
51
55
  if (!guard || !doc) return fields;
@@ -293,17 +297,18 @@ async function replaceSearchTokensForBatch(db, allPayloads) {
293
297
  if (!indexablePayloads.length) return;
294
298
  const config = resolveSearchConfig();
295
299
  if (!config.enabled) return;
296
- const guardCiphertext = shouldGuardCiphertext();
300
+ let processGuard;
301
+ const guardFor = (payload) => payload.guardCiphertext ?? (processGuard ??= shouldGuardCiphertext());
297
302
  const preservedRecordIds = /* @__PURE__ */ new Set();
298
303
  const payloads = indexablePayloads.filter((payload) => {
299
- const ciphertextFields = ciphertextFieldsOf(payload.doc, guardCiphertext);
304
+ const ciphertextFields = ciphertextFieldsOf(payload.doc, guardFor(payload));
300
305
  if (!ciphertextFields.size) return true;
301
306
  warnCiphertextSkipped(payload.entityType, payload.tenantId ?? null, ciphertextFields);
302
307
  preservedRecordIds.add(String(payload.recordId));
303
308
  return false;
304
309
  });
305
310
  if (!payloads.length) return;
306
- const rows = payloads.flatMap((payload) => buildSearchTokenRows({ ...payload, config, guardCiphertext }));
311
+ const rows = payloads.flatMap((payload) => buildSearchTokenRows({ ...payload, config, guardCiphertext: guardFor(payload) }));
307
312
  if (!rows.length) {
308
313
  const entityType = payloads[0]?.entityType;
309
314
  if (!entityType) return;
@@ -387,6 +392,7 @@ export {
387
392
  isSearchDebugEnabled,
388
393
  replaceSearchTokensForBatch,
389
394
  replaceSearchTokensForRecord,
390
- resetCiphertextGuardState
395
+ resetCiphertextGuardState,
396
+ resolveCiphertextGuard
391
397
  };
392
398
  //# sourceMappingURL=search-tokens.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/query_index/lib/search-tokens.ts"],
4
- "sourcesContent": ["import { type Kysely, type Transaction, sql } from 'kysely'\nimport {\n isSearchFieldBlocklisted,\n resolveSearchConfig,\n resolveSearchTokenLimits,\n type SearchConfig,\n} from '@open-mercato/shared/lib/search/config'\nimport { tokenizeText } from '@open-mercato/shared/lib/search/tokenize'\nimport { looksLikeEncryptedPayload } from '@open-mercato/shared/lib/encryption/aes'\nimport { createKmsService, resolveEncryptionMode, type KmsService } from '@open-mercato/shared/lib/encryption/kms'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { isIndexDocEnrichedKey } from './doc-enrichers'\n\nconst logger = createLogger('query_index').child({ component: 'search-tokens' })\n\nconst INSERT_BATCH_SIZE = 500\nconst TOKEN_EXCLUDED_ENTITY_TYPES = new Set(['audit_logs:action_log', 'audit_logs:access_log'])\n\nfunction chunk<T>(items: T[], size: number): T[][] {\n if (size <= 0) return [items]\n const out: T[][] = []\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size))\n return out\n}\n\nexport type SearchTokenRow = {\n entity_type: string\n entity_id: string\n organization_id: string | null\n tenant_id: string | null\n field: string\n token_hash: string\n token?: string | null\n}\n\ntype BuildTokenOptions = {\n entityType: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n doc?: Record<string, unknown> | null\n config?: SearchConfig\n /** Resolved once per write by the exported entry points; see {@link shouldGuardCiphertext}. */\n guardCiphertext?: boolean\n}\n\nconst DEFAULT_SCOPE = { organizationId: null, tenantId: null }\ntype EntityFieldPair = [string, string]\ntype SearchTokenExecutor = Kysely<any> | Transaction<any>\n\nexport const isSearchDebugEnabled = (): boolean => {\n return parseBooleanToken(process.env.OM_SEARCH_DEBUG ?? '') === true\n}\n\nconst debug = (event: string, payload: Record<string, unknown>) => {\n if (!isSearchDebugEnabled()) return\n try {\n logger.debug('Search token event', { event, payload })\n } catch {\n // ignore\n }\n}\n\nfunction collectTextValues(value: unknown): string[] {\n if (typeof value === 'string') return [value]\n if (Array.isArray(value)) {\n const out: string[] = []\n for (const entry of value) {\n if (typeof entry === 'string') out.push(entry)\n }\n return out\n }\n return []\n}\n\nlet guardKmsService: KmsService | null = null\n\n/**\n * Whether the ciphertext guard below is allowed to run for this write.\n *\n * The guard recognises an envelope by its SHAPE, which is forgeable: `<16 b64>:<b64>:<24 b64>:v1`\n * is a string any user can type into a searchable field. `tenantDataEncryptionService` removed the\n * same structural test for that reason (#2720). So the guard may only run where the shape is the\n * ONLY test available -- which is exactly where no DEK is reachable:\n *\n * - `active` -- the indexer decrypted the document before handing it here, so a value still\n * shaped like an envelope is plaintext somebody typed. Indexing it is correct,\n * and skipping it would let that person freeze their own record's tokens at a\n * past state. The guard stays off, which also keeps it off the hot path of\n * every normal deployment.\n * - `disabled` -- `decryptIndexDocForSearch` is a no-op, so ciphertext arrives undecrypted.\n * - `unavailable` -- the decrypt was attempted and could not complete, same outcome.\n *\n * Resolved once per write rather than per document, over a KMS built once per process:\n * {@link createKmsService} logs when it falls back, and a reindex calls this once per record. The\n * toggle itself is still re-read every call by {@link resolveEncryptionMode}; only the KMS is\n * cached, and it already requires a restart to change, since DEK and map caches are in-process.\n */\nfunction shouldGuardCiphertext(): boolean {\n guardKmsService ??= createKmsService()\n return resolveEncryptionMode(guardKmsService) !== 'active'\n}\n\n/**\n * Fields whose value is an AES-GCM envelope rather than the text it is supposed to hold.\n *\n * Search tokens are hashes of PLAINTEXT: the indexer decrypts a document before tokenising it\n * (`indexer.ts` -> `decryptIndexDocForSearch`), which is what lets the token index survive\n * encryption being switched on or off. That decrypt step is a no-op once\n * `TENANT_DATA_ENCRYPTION=no`, so an operator who flips the toggle before running\n * `mercato entities decrypt-database` starts feeding ciphertext into the tokeniser. The tokens\n * that come out are hashes of base64 noise and match nothing, and because a write REPLACES a\n * record's tokens, the good plaintext tokens already in the table would be deleted to make room\n * for them -- turning a recoverable misordering into permanent search loss.\n *\n * Detecting the envelope by shape lets the write skip those fields and leave what is already\n * indexed alone. `guard` gates that detection; see {@link shouldGuardCiphertext} for why it is not\n * unconditional.\n */\nfunction ciphertextFieldsOf(\n doc: Record<string, unknown> | null | undefined,\n guard: boolean,\n): Set<string> {\n const fields = new Set<string>()\n if (!guard || !doc) return fields\n for (const [field, value] of Object.entries(doc)) {\n const values = collectTextValues(value)\n if (values.length && values.some((text) => looksLikeEncryptedPayload(text))) fields.add(field)\n }\n return fields\n}\n\nconst warnedCiphertextEntities = new Set<string>()\n\nfunction warnCiphertextSkipped(entityType: string, tenantId: string | null, fields: Set<string>): void {\n if (!fields.size) return\n // Once per entity type per tenant per process: a full reindex would otherwise emit this per\n // record, while keying on the entity type alone would let the first affected tenant in a shared\n // process consume the one warning every other tenant's operator needed.\n const key = `${entityType}|${tenantId ?? ''}`\n if (warnedCiphertextEntities.has(key)) return\n warnedCiphertextEntities.add(key)\n logger.warn(\n 'Search indexing skipped ciphertext fields and preserved their existing tokens. '\n + 'This means TENANT_DATA_ENCRYPTION was switched off while encrypted data was still at rest. '\n + 'Run `mercato entities decrypt-database` and reindex; until then these fields are not searchable.',\n { entityType, tenantId, fields: Array.from(fields).sort((left, right) => left.localeCompare(right)) },\n )\n}\n\n/** Test seam: both the warning above and the KMS behind the guard are once-per-process. */\nexport function resetCiphertextGuardState(): void {\n warnedCiphertextEntities.clear()\n guardKmsService = null\n}\n\nfunction shouldIndexField(\n field: string,\n value: unknown,\n config: SearchConfig,\n entityType: string | null,\n): boolean {\n if (typeof value !== 'string' && !Array.isArray(value)) return false\n const lower = field.toLowerCase()\n if (lower === 'id' || lower.endsWith('_id') || lower.endsWith('.id')) return false\n if (lower.endsWith('_at')) return false\n if (['created_at', 'updated_at', 'deleted_at', 'tenant_id', 'organization_id'].includes(lower)) return false\n if (isSearchFieldBlocklisted(field, entityType, config)) return false\n if (isIndexDocEnrichedKey(entityType, field)) return false\n return collectTextValues(value).some((text) => text.length > 0)\n}\n\n/**\n * Builds the `search_tokens` rows for one document.\n *\n * `maxTokensPerRecord` is spent in the iteration order of `params.doc`'s own keys: fields are\n * tokenized one after another and the loop stops at the first field that exhausts the budget, so\n * on an over-budget record the surviving fields are whichever ones come first. That order is a\n * property of the object handed in, not of the entity, and the two write-path builders order it\n * differently: `buildIndexDocument` (`lib/document.ts`, the batch reindex path) appends `cf:*` keys\n * after the base columns and the aggregate `search_text` field last. `buildIndexDoc` (`lib/indexer.ts`,\n * the incremental single-record write path \u2014 `upsertIndexRow` \u2192 `reindexSearchTokensForRecord`) adds\n * `l10n:{locale}:{field}` translation keys between the `cf:*` keys and `search_text`. The budget is\n * spent front-to-back, so the fields nearest the end of that order are starved first: `search_text`\n * is last on both paths and starves first either way, but starves sooner on the incremental path,\n * because the `l10n:*` keys ahead of it there consume budget the batch path would have spent on it.\n * Those translation fields starve next, before any `cf:*` key or base column. The two paths can\n * therefore keep different fields searchable for an otherwise equivalent record.\n *\n * Every write path tokenizes an in-memory document it is about to write \u2014 `TokenSearchStrategy.index`\n * writes only `search_tokens` rows and never touches `entity_indexes.doc` \u2014 which keeps each path\n * self-consistent on its own. A document read back out of the `entity_indexes.doc` `jsonb` column is\n * not the same object: Postgres stores `jsonb` keys in a canonical order (by key length, then byte\n * order), not in insertion order. Re-tokenizing such a document can therefore truncate at a different\n * field than the write did, so code that verifies or recomputes a record's expected tokens must\n * rebuild the document through the builder that matches the write path being checked \u2014 `buildIndexDoc`\n * for incrementally-written records, `buildIndexDocument` for batch-reindexed ones \u2014 rather than\n * reading it back from the database.\n *\n * Making truncation reproducible from a `jsonb` read \u2014 by sorting fields before tokenization \u2014\n * would change which terms stay searchable on over-budget records, so it is a behavior decision\n * rather than a clarification (#5971).\n */\nexport function buildSearchTokenRows(params: BuildTokenOptions): SearchTokenRow[] {\n if (TOKEN_EXCLUDED_ENTITY_TYPES.has(params.entityType)) return []\n const config = params.config ?? resolveSearchConfig()\n if (!config.enabled) return []\n if (!params.doc) return []\n const tokens: SearchTokenRow[] = []\n const capturePairs = isSearchDebugEnabled() && params.entityType === 'customers:customer_deal'\n const debugPairs: Array<{ field: string; hash: string }> = []\n const scope = {\n organizationId: params.organizationId ?? DEFAULT_SCOPE.organizationId,\n tenantId: params.tenantId ?? DEFAULT_SCOPE.tenantId,\n }\n const limits = resolveSearchTokenLimits(config)\n const recordLimit = limits.maxTokensPerRecord > 0 ? limits.maxTokensPerRecord : Number.POSITIVE_INFINITY\n const fieldLimit = limits.maxTokensPerField > 0 ? limits.maxTokensPerField : Number.POSITIVE_INFINITY\n const ciphertextFields = ciphertextFieldsOf(params.doc, params.guardCiphertext ?? shouldGuardCiphertext())\n warnCiphertextSkipped(params.entityType, scope.tenantId, ciphertextFields)\n\n for (const [field, rawValue] of Object.entries(params.doc)) {\n if (tokens.length >= recordLimit) break\n if (ciphertextFields.has(field)) continue\n if (!shouldIndexField(field, rawValue, config, params.entityType)) continue\n const values = collectTextValues(rawValue)\n const seen = new Set<string>()\n let fieldTokenCount = 0\n for (const text of values) {\n if (tokens.length >= recordLimit || fieldTokenCount >= fieldLimit) break\n const remainingLimit = Math.min(recordLimit - tokens.length, fieldLimit - fieldTokenCount)\n const candidateLimit = fieldTokenCount + remainingLimit\n const tokenConfig = Number.isFinite(candidateLimit)\n ? { ...config, maxTokensPerField: candidateLimit }\n : config\n const { tokens: textTokens, hashes } = tokenizeText(text, tokenConfig)\n for (let i = 0; i < textTokens.length; i += 1) {\n if (tokens.length >= recordLimit || fieldTokenCount >= fieldLimit) break\n const token = textTokens[i]\n const hash = hashes[i]\n const dedupeKey = `${field}|${hash}`\n if (seen.has(dedupeKey)) continue\n seen.add(dedupeKey)\n fieldTokenCount += 1\n debug('token.generated', { entityType: params.entityType, recordId: params.recordId, field, hash })\n tokens.push({\n entity_type: params.entityType,\n entity_id: String(params.recordId),\n organization_id: scope.organizationId,\n tenant_id: scope.tenantId,\n field,\n token_hash: hash,\n token: config.storeRawTokens ? token : null,\n })\n if (capturePairs) {\n debugPairs.push({ field, hash })\n }\n }\n }\n }\n if (capturePairs) {\n debug('deal.tokens', {\n entityType: params.entityType,\n recordId: params.recordId,\n tokenCount: debugPairs.length,\n tokens: debugPairs,\n })\n }\n debug('doc.completed', { entityType: params.entityType, recordId: params.recordId, tokenCount: tokens.length })\n\n return tokens\n}\n\nfunction buildFieldPairs(\n recordId: string,\n doc?: Record<string, unknown> | null,\n skipFields?: Set<string>,\n): EntityFieldPair[] {\n if (!doc) return []\n const pairs: EntityFieldPair[] = []\n const dedupe = new Set<string>()\n for (const field of Object.keys(doc)) {\n // The delete below is scoped to these pairs, so omitting a field here is what preserves the\n // tokens already stored for it rather than merely declining to write new ones.\n if (skipFields?.has(field)) continue\n const key = `${recordId}|${field}`\n if (dedupe.has(key)) continue\n dedupe.add(key)\n pairs.push([recordId, field])\n }\n return pairs\n}\n\ntype TokenRowLike = { field?: unknown; token_hash?: unknown; token?: unknown }\n\n// NUL, not a printable separator: a field name may itself contain a space, so `a b` + hash `c`\n// would otherwise sign identically to field `a` + hash `b c`.\nconst SIGNATURE_SEPARATOR = String.fromCharCode(0)\n\n// Identifies one token row for comparison. `token` is NULL unless `storeRawTokens` is on, and a\n// stored NULL has to sign the same as the `null` a freshly built row carries \u2014 otherwise every\n// record compares as changed and the skip never fires.\nfunction tokenSignature(row: TokenRowLike): string {\n return [\n String(row.field ?? ''),\n String(row.token_hash ?? ''),\n row.token == null ? '' : String(row.token),\n ].join(SIGNATURE_SEPARATOR)\n}\n\n// Multiplicities, not sets: #4681 reports token rows duplicated by the concurrent-replacement\n// defect, and a set comparison reads such a record as already correct and preserves the duplicates\n// forever. Counting sends it through a full rewrite, which collapses them.\nfunction tallyOf(rows: Iterable<TokenRowLike>): Map<string, number> {\n const tally = new Map<string, number>()\n for (const row of rows) {\n const signature = tokenSignature(row)\n tally.set(signature, (tally.get(signature) ?? 0) + 1)\n }\n return tally\n}\n\nfunction tallyEquals(a: Map<string, number> | undefined, b: Map<string, number> | undefined): boolean {\n const left = a ?? new Map<string, number>()\n const right = b ?? new Map<string, number>()\n if (left.size !== right.size) return false\n for (const [key, count] of left.entries()) {\n if (right.get(key) !== count) return false\n }\n return true\n}\n\nfunction tallyTokenRows<TRow extends TokenRowLike>(\n rows: Iterable<TRow>,\n keyOf: (row: TRow) => string\n): Map<string, Map<string, number>> {\n const tallies = new Map<string, Map<string, number>>()\n for (const row of rows) {\n const key = keyOf(row)\n const tally = tallies.get(key) ?? new Map<string, number>()\n const signature = tokenSignature(row)\n tally.set(signature, (tally.get(signature) ?? 0) + 1)\n tallies.set(key, tally)\n }\n return tallies\n}\n\nexport async function replaceSearchTokensForRecord(\n db: Kysely<any>,\n params: BuildTokenOptions,\n options?: { trx?: SearchTokenExecutor },\n): Promise<void> {\n if (TOKEN_EXCLUDED_ENTITY_TYPES.has(params.entityType)) {\n await deleteSearchTokensForRecord(db, params, options)\n return\n }\n const guardCiphertext = params.guardCiphertext ?? shouldGuardCiphertext()\n const rows = buildSearchTokenRows({ ...params, guardCiphertext })\n const config = params.config ?? resolveSearchConfig()\n if (!config.enabled) return\n const organizationId = params.organizationId ?? null\n const tenantId = params.tenantId ?? null\n const ciphertextFields = ciphertextFieldsOf(params.doc, guardCiphertext)\n const fieldPairs = buildFieldPairs(String(params.recordId), params.doc, ciphertextFields)\n\n // An empty pair list normally means the document is gone, and the delete below then purges the\n // record wholesale. It can now also mean every field was skipped as ciphertext, where a purge\n // would destroy precisely the tokens the skip exists to protect. Distinguish the two.\n if (params.doc && ciphertextFields.size && !fieldPairs.length) {\n debug('record.preserve-ciphertext', { entityType: params.entityType, recordId: params.recordId })\n return\n }\n\n // Same comparison #5402 gave the batch path, over the scope this path actually writes: the\n // delete below is narrowed to the document's own `(entity_id, field)` pairs, so the comparison\n // has to be narrowed the same way. Reading wider would let a token row under a field this\n // document does not carry \u2014 the `cf_` twin the search module used to write, say \u2014 read as a\n // difference forever and defeat the skip on every write.\n const scopeTokenQuery = (query: any): any => {\n let scoped = query\n .where('entity_type' as any, '=', params.entityType)\n .where(sql<boolean>`organization_id is not distinct from ${organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantId}`)\n .where('entity_id' as any, '=', String(params.recordId))\n if (fieldPairs.length) {\n scoped = scoped.where('field' as any, 'in', fieldPairs.map(([, field]) => field))\n }\n return scoped\n }\n\n // Read through the caller's transaction when there is one. A separate connection cannot see that\n // transaction's own uncommitted writes, so it could report rows a pending delete has already\n // removed and talk this call out of re-inserting them.\n const reader = options?.trx ?? db\n\n // Count probe first, as in the batch path: it returns one row whatever the table holds, so a\n // record whose stored rows have run away (#4681) is settled without materializing them.\n const storedCountRows = await scopeTokenQuery(\n reader.selectFrom('search_tokens' as any).select(sql<number>`count(*)`.as('token_count') as any),\n ).execute()\n const storedCount = Number((storedCountRows as any[])[0]?.token_count ?? 0)\n\n let unchanged = storedCount === rows.length\n if (unchanged && rows.length) {\n const stored = await scopeTokenQuery(\n reader.selectFrom('search_tokens' as any).select(['field' as any, 'token_hash' as any, 'token' as any]),\n )\n // Counts already match, so this cannot truncate. It bounds the read if a concurrent writer\n // inserts between the probe and here; a truncated read compares as changed, which costs a\n // rewrite rather than a wrong skip.\n .limit(rows.length)\n .execute()\n unchanged = tallyEquals(tallyOf(rows), tallyOf(stored as any[]))\n }\n if (unchanged) {\n debug('record.skip', { entityType: params.entityType, recordId: params.recordId, tokenCount: rows.length })\n return\n }\n\n const writeTokens = async (executor: SearchTokenExecutor): Promise<void> => {\n let deleteQuery = executor\n .deleteFrom('search_tokens' as any)\n .where('entity_type' as any, '=', params.entityType)\n .where(sql<boolean>`organization_id is not distinct from ${organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantId}`)\n if (fieldPairs.length) {\n deleteQuery = deleteQuery.where((eb: any) => eb.or(\n fieldPairs.map(([rid, field]) => eb.and([\n eb('entity_id' as any, '=', rid),\n eb('field' as any, '=', field),\n ])),\n ))\n } else {\n deleteQuery = deleteQuery.where('entity_id' as any, '=', String(params.recordId))\n }\n await deleteQuery.execute()\n if (!rows.length) return\n const payloads = rows.map((row) => ({ ...row, created_at: sql`now()` }))\n for (const batch of chunk(payloads, INSERT_BATCH_SIZE)) {\n await executor.insertInto('search_tokens' as any).values(batch as any).execute()\n }\n }\n\n if (options?.trx) {\n await writeTokens(options.trx)\n return\n }\n\n await db.transaction().execute(writeTokens)\n}\n\nexport async function deleteSearchTokensForRecord(\n db: Kysely<any>,\n params: { entityType: string; recordId: string; organizationId?: string | null; tenantId?: string | null },\n options?: { trx?: SearchTokenExecutor },\n): Promise<void> {\n const organizationId = params.organizationId ?? null\n const tenantId = params.tenantId ?? null\n const executor = options?.trx ?? db\n await executor\n .deleteFrom('search_tokens' as any)\n .where('entity_type' as any, '=', params.entityType)\n .where('entity_id' as any, '=', String(params.recordId))\n .where(sql<boolean>`organization_id is not distinct from ${organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantId}`)\n .execute()\n}\n\nexport async function replaceSearchTokensForBatch(\n db: Kysely<any>,\n allPayloads: Array<BuildTokenOptions & { doc: Record<string, unknown> }>\n): Promise<void> {\n if (!allPayloads.length) return\n const excludedBuckets = new Map<string, {\n entityType: string\n organizationId: string | null\n tenantId: string | null\n ids: Set<string>\n }>()\n const indexablePayloads = allPayloads.filter((payload) => {\n if (!TOKEN_EXCLUDED_ENTITY_TYPES.has(payload.entityType)) return true\n const organizationId = payload.organizationId ?? null\n const tenantId = payload.tenantId ?? null\n const key = JSON.stringify([payload.entityType, organizationId, tenantId])\n const bucket = excludedBuckets.get(key) ?? {\n entityType: payload.entityType,\n organizationId,\n tenantId,\n ids: new Set<string>(),\n }\n bucket.ids.add(String(payload.recordId))\n excludedBuckets.set(key, bucket)\n return false\n })\n if (excludedBuckets.size) {\n await db.transaction().execute(async (trx) => {\n for (const bucket of excludedBuckets.values()) {\n await trx\n .deleteFrom('search_tokens')\n .where('entity_type', '=', bucket.entityType)\n .where(sql<boolean>`organization_id is not distinct from ${bucket.organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${bucket.tenantId}`)\n .where('entity_id', 'in', Array.from(bucket.ids))\n .execute()\n }\n })\n }\n if (!indexablePayloads.length) return\n const config = resolveSearchConfig()\n if (!config.enabled) return\n\n // A record carrying ciphertext drops out of the batch entirely, rather than being rewritten\n // without its encrypted fields. This path deletes by `entity_id` -- it cannot express \"replace\n // these fields and leave those alone\" the way the per-record path can -- so partial handling\n // here would still delete the tokens we are trying to protect. Skipping the record leaves every\n // one of its tokens, encrypted-field and plaintext-field alike, exactly as it was. The state is\n // transient by construction: `decrypt-database` followed by a reindex rebuilds all of it.\n const guardCiphertext = shouldGuardCiphertext()\n const preservedRecordIds = new Set<string>()\n const payloads = indexablePayloads.filter((payload) => {\n const ciphertextFields = ciphertextFieldsOf(payload.doc, guardCiphertext)\n if (!ciphertextFields.size) return true\n warnCiphertextSkipped(payload.entityType, payload.tenantId ?? null, ciphertextFields)\n preservedRecordIds.add(String(payload.recordId))\n return false\n })\n if (!payloads.length) return\n\n const rows = payloads.flatMap((payload) => buildSearchTokenRows({ ...payload, config, guardCiphertext }))\n if (!rows.length) {\n const entityType = payloads[0]?.entityType\n if (!entityType) return\n const ids = payloads.map((p) => String(p.recordId))\n await db\n .deleteFrom('search_tokens' as any)\n .where('entity_type' as any, '=', entityType)\n .where('entity_id' as any, 'in', ids)\n .execute()\n return\n }\n\n const scopeKey = (org: string | null, tenant: string | null) => `${org ?? '__null__'}|${tenant ?? '__null__'}`\n const scopeBuckets = new Map<string, { organizationId: string | null; tenantId: string | null; ids: Set<string> }>()\n\n for (const payload of payloads) {\n const org = payload.organizationId ?? null\n const tenant = payload.tenantId ?? null\n const key = scopeKey(org, tenant)\n const bucket = scopeBuckets.get(key) ?? { organizationId: org, tenantId: tenant, ids: new Set<string>() }\n bucket.ids.add(String(payload.recordId))\n scopeBuckets.set(key, bucket)\n }\n\n const recordKeyOf = (row: SearchTokenRow) =>\n `${scopeKey(row.organization_id ?? null, row.tenant_id ?? null)}|${String(row.entity_id)}`\n const builtTally = tallyTokenRows(rows, recordKeyOf)\n\n // Read outside the transaction, deliberately. The comparison decides only whether to skip a\n // rewrite, so a concurrent writer costs us at most a rewrite we declined \u2014 declined because the\n // table already held exactly the rows this call wanted to write. One ordering is worth naming\n // though: if the read matches and a concurrent writer then commits tokens built from a *staler*\n // doc, the unconditional rewrite this call used to perform would have overwritten them by\n // accident. It no longer does, so those stale rows survive until the record's next write. That\n // is a repair we lose, not a guarantee we break.\n const changedIdsByBucket = new Map<string, Set<string>>()\n for (const [key, bucket] of scopeBuckets.entries()) {\n const ids = Array.from(bucket.ids)\n const builtCountById = new Map<string, number>()\n for (const id of ids) {\n let total = 0\n const tally = builtTally.get(`${key}|${id}`)\n if (tally) for (const count of tally.values()) total += count\n builtCountById.set(id, total)\n }\n\n // Count probe first. Its result is one row per record in the batch, so it is bounded by the\n // batch size \u2014 unlike a bare row read, which would be bounded only by how many token rows the\n // table already holds for these ids, a quantity this function does not control and (per #4681)\n // has no reason to trust.\n const storedCounts = await db\n .selectFrom('search_tokens' as any)\n .select(['entity_id' as any, sql<number>`count(*)`.as('token_count') as any])\n .where('entity_type' as any, '=', payloads[0].entityType)\n .where(sql<boolean>`organization_id is not distinct from ${bucket.organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${bucket.tenantId}`)\n .where('entity_id' as any, 'in', ids)\n .groupBy('entity_id' as any)\n .execute()\n const storedCountById = new Map<string, number>()\n for (const row of storedCounts as any[]) {\n storedCountById.set(String(row.entity_id), Number(row.token_count))\n }\n\n const changed = new Set<string>()\n // A record whose stored row count already differs is changed, whatever the rows say \u2014 the\n // duplicate case from #4681 resolves here without ever materializing the duplicated rows.\n const contentCandidates = ids.filter((id) => {\n const builtCount = builtCountById.get(id) ?? 0\n if ((storedCountById.get(id) ?? 0) !== builtCount) {\n changed.add(id)\n return false\n }\n return builtCount > 0\n })\n\n if (contentCandidates.length) {\n const rowBudget = contentCandidates.reduce((sum, id) => sum + (builtCountById.get(id) ?? 0), 0)\n const stored = await db\n .selectFrom('search_tokens' as any)\n .select(['entity_id' as any, 'field' as any, 'token_hash' as any, 'token' as any])\n .where('entity_type' as any, '=', payloads[0].entityType)\n .where(sql<boolean>`organization_id is not distinct from ${bucket.organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${bucket.tenantId}`)\n .where('entity_id' as any, 'in', contentCandidates)\n // Counts already match, so this cannot truncate \u2014 it bounds the damage if a concurrent\n // writer inserts between the probe and this read. A truncated read compares as changed,\n // which costs a rewrite rather than a wrong skip.\n .limit(rowBudget)\n .execute()\n const storedTally = tallyTokenRows(stored as any[], (row) => String(row.entity_id))\n for (const id of contentCandidates) {\n if (!tallyEquals(builtTally.get(`${key}|${id}`), storedTally.get(id))) changed.add(id)\n }\n }\n changedIdsByBucket.set(key, changed)\n }\n\n const changedRecordKeys = new Set<string>()\n for (const [key, changed] of changedIdsByBucket.entries()) {\n for (const id of changed) changedRecordKeys.add(`${key}|${id}`)\n }\n debug('batch.skip', {\n entityType: payloads[0].entityType,\n recordCount: payloads.length,\n changedCount: changedRecordKeys.size,\n preservedCiphertextRecordCount: preservedRecordIds.size,\n })\n if (!changedRecordKeys.size) return\n\n await db.transaction().execute(async (trx) => {\n for (const [key, bucket] of scopeBuckets.entries()) {\n const changed = changedIdsByBucket.get(key)\n if (!changed?.size) continue\n // Delete by entity_id: a batch replaces all of a record's tokens, and a per-field OR over the\n // whole batch overflows the query compiler's call stack on large batches.\n const deleteQuery = trx\n .deleteFrom('search_tokens' as any)\n .where('entity_type' as any, '=', payloads[0].entityType)\n .where(sql<boolean>`organization_id is not distinct from ${bucket.organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${bucket.tenantId}`)\n .where('entity_id' as any, 'in', Array.from(changed))\n await deleteQuery.execute()\n }\n const payloadWithTimestamps = rows\n .filter((row) => changedRecordKeys.has(recordKeyOf(row)))\n .map((row) => ({ ...row, created_at: sql`now()` }))\n for (const batch of chunk(payloadWithTimestamps, INSERT_BATCH_SIZE)) {\n await trx.insertInto('search_tokens' as any).values(batch as any).execute()\n }\n })\n}\n"],
5
- "mappings": "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Q,OAAO,QAAQ;AAC5C,eAAW,CAAC,KAAK,MAAM,KAAK,aAAa,QAAQ,GAAG;AAClD,YAAM,UAAU,mBAAmB,IAAI,GAAG;AAC1C,UAAI,CAAC,SAAS,KAAM;AAGpB,YAAM,cAAc,IACjB,WAAW,eAAsB,EACjC,MAAM,eAAsB,KAAK,SAAS,CAAC,EAAE,UAAU,EACvD,MAAM,2CAAoD,OAAO,cAAc,EAAE,EACjF,MAAM,qCAA8C,OAAO,QAAQ,EAAE,EACrE,MAAM,aAAoB,MAAM,MAAM,KAAK,OAAO,CAAC;AACtD,YAAM,YAAY,QAAQ;AAAA,IAC5B;AACA,UAAM,wBAAwB,KAC3B,OAAO,CAAC,QAAQ,kBAAkB,IAAI,YAAY,GAAG,CAAC,CAAC,EACvD,IAAI,CAAC,SAAS,EAAE,GAAG,KAAK,YAAY,WAAW,EAAE;AACpD,eAAW,SAAS,MAAM,uBAAuB,iBAAiB,GAAG;AACnE,YAAM,IAAI,WAAW,eAAsB,EAAE,OAAO,KAAY,EAAE,QAAQ;AAAA,IAC5E;AAAA,EACF,CAAC;AACH;",
4
+ "sourcesContent": ["import { type Kysely, type Transaction, sql } from 'kysely'\nimport {\n isSearchFieldBlocklisted,\n resolveSearchConfig,\n resolveSearchTokenLimits,\n type SearchConfig,\n} from '@open-mercato/shared/lib/search/config'\nimport { tokenizeText } from '@open-mercato/shared/lib/search/tokenize'\nimport { looksLikeEncryptedPayload } from '@open-mercato/shared/lib/encryption/aes'\nimport { createKmsService, resolveEncryptionMode, type KmsService } from '@open-mercato/shared/lib/encryption/kms'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { isIndexDocEnrichedKey } from './doc-enrichers'\n\nconst logger = createLogger('query_index').child({ component: 'search-tokens' })\n\nconst INSERT_BATCH_SIZE = 500\nconst TOKEN_EXCLUDED_ENTITY_TYPES = new Set(['audit_logs:action_log', 'audit_logs:access_log'])\n\nfunction chunk<T>(items: T[], size: number): T[][] {\n if (size <= 0) return [items]\n const out: T[][] = []\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size))\n return out\n}\n\nexport type SearchTokenRow = {\n entity_type: string\n entity_id: string\n organization_id: string | null\n tenant_id: string | null\n field: string\n token_hash: string\n token?: string | null\n}\n\ntype BuildTokenOptions = {\n entityType: string\n recordId: string\n organizationId?: string | null\n tenantId?: string | null\n doc?: Record<string, unknown> | null\n config?: SearchConfig\n /** Resolved once per write by the exported entry points; see {@link shouldGuardCiphertext}. */\n guardCiphertext?: boolean\n}\n\nconst DEFAULT_SCOPE = { organizationId: null, tenantId: null }\ntype EntityFieldPair = [string, string]\ntype SearchTokenExecutor = Kysely<any> | Transaction<any>\n\nexport const isSearchDebugEnabled = (): boolean => {\n return parseBooleanToken(process.env.OM_SEARCH_DEBUG ?? '') === true\n}\n\nconst debug = (event: string, payload: Record<string, unknown>) => {\n if (!isSearchDebugEnabled()) return\n try {\n logger.debug('Search token event', { event, payload })\n } catch {\n // ignore\n }\n}\n\nfunction collectTextValues(value: unknown): string[] {\n if (typeof value === 'string') return [value]\n if (Array.isArray(value)) {\n const out: string[] = []\n for (const entry of value) {\n if (typeof entry === 'string') out.push(entry)\n }\n return out\n }\n return []\n}\n\nlet guardKmsService: KmsService | null = null\n\n/**\n * Whether the ciphertext guard below is allowed to run for this write.\n *\n * The guard recognises an envelope by its SHAPE, which is forgeable: `<16 b64>:<b64>:<24 b64>:v1`\n * is a string any user can type into a searchable field. `tenantDataEncryptionService` removed the\n * same structural test for that reason (#2720). So the guard may only run where the shape is the\n * ONLY test available -- which is exactly where no DEK is reachable:\n *\n * - `active` -- the indexer decrypted the document before handing it here, so a value still\n * shaped like an envelope is plaintext somebody typed. Indexing it is correct,\n * and skipping it would let that person freeze their own record's tokens at a\n * past state. The guard stays off, which also keeps it off the hot path of\n * every normal deployment.\n * - `disabled` -- `decryptIndexDocForSearch` is a no-op, so ciphertext arrives undecrypted.\n * - `unavailable` -- the decrypt was attempted and could not complete, same outcome.\n *\n * Resolved once per write rather than per document, over a KMS built once per process:\n * {@link createKmsService} logs when it falls back, and a reindex calls this once per record. The\n * toggle itself is still re-read every call by {@link resolveEncryptionMode}; only the KMS is\n * cached, and it already requires a restart to change, since DEK and map caches are in-process.\n */\nfunction shouldGuardCiphertext(): boolean {\n guardKmsService ??= createKmsService()\n return resolveEncryptionMode(guardKmsService) !== 'active'\n}\n\nexport type CiphertextGuardSource = { isEnabled?: () => boolean } | null | undefined\n\n/**\n * The guard decision for a document decrypted by `encryption`, read AFTER that decrypt.\n *\n * {@link shouldGuardCiphertext} asks a KMS that never fetches a key, so its Vault circuit breaker\n * never trips: it reports `active` through a real outage while the decrypt that ran just before\n * got no DEK and handed back ciphertext. `encryption.isEnabled()` is the toggle ANDed with the\n * health of the KMS whose `getDek` just called Vault, and it is the same signal\n * `decryptIndexDocForSearch` uses to skip decryption, so the decrypt and the guard cannot disagree.\n * Callers without a service keep the process-level check.\n */\nexport function resolveCiphertextGuard(encryption: CiphertextGuardSource): boolean {\n if (typeof encryption?.isEnabled !== 'function') return shouldGuardCiphertext()\n return !encryption.isEnabled()\n}\n\n/**\n * Fields whose value is an AES-GCM envelope rather than the text it is supposed to hold.\n *\n * Search tokens are hashes of PLAINTEXT: the indexer decrypts a document before tokenising it\n * (`indexer.ts` -> `decryptIndexDocForSearch`), which is what lets the token index survive\n * encryption being switched on or off. That decrypt step is a no-op once\n * `TENANT_DATA_ENCRYPTION=no`, so an operator who flips the toggle before running\n * `mercato entities decrypt-database` starts feeding ciphertext into the tokeniser. The tokens\n * that come out are hashes of base64 noise and match nothing, and because a write REPLACES a\n * record's tokens, the good plaintext tokens already in the table would be deleted to make room\n * for them -- turning a recoverable misordering into permanent search loss.\n *\n * Detecting the envelope by shape lets the write skip those fields and leave what is already\n * indexed alone. `guard` gates that detection; see {@link shouldGuardCiphertext} for why it is not\n * unconditional.\n */\nfunction ciphertextFieldsOf(\n doc: Record<string, unknown> | null | undefined,\n guard: boolean,\n): Set<string> {\n const fields = new Set<string>()\n if (!guard || !doc) return fields\n for (const [field, value] of Object.entries(doc)) {\n const values = collectTextValues(value)\n if (values.length && values.some((text) => looksLikeEncryptedPayload(text))) fields.add(field)\n }\n return fields\n}\n\nconst warnedCiphertextEntities = new Set<string>()\n\nfunction warnCiphertextSkipped(entityType: string, tenantId: string | null, fields: Set<string>): void {\n if (!fields.size) return\n // Once per entity type per tenant per process: a full reindex would otherwise emit this per\n // record, while keying on the entity type alone would let the first affected tenant in a shared\n // process consume the one warning every other tenant's operator needed.\n const key = `${entityType}|${tenantId ?? ''}`\n if (warnedCiphertextEntities.has(key)) return\n warnedCiphertextEntities.add(key)\n logger.warn(\n 'Search indexing skipped ciphertext fields and preserved their existing tokens. '\n + 'This means TENANT_DATA_ENCRYPTION was switched off while encrypted data was still at rest. '\n + 'Run `mercato entities decrypt-database` and reindex; until then these fields are not searchable.',\n { entityType, tenantId, fields: Array.from(fields).sort((left, right) => left.localeCompare(right)) },\n )\n}\n\n/** Test seam: both the warning above and the KMS behind the guard are once-per-process. */\nexport function resetCiphertextGuardState(): void {\n warnedCiphertextEntities.clear()\n guardKmsService = null\n}\n\nfunction shouldIndexField(\n field: string,\n value: unknown,\n config: SearchConfig,\n entityType: string | null,\n): boolean {\n if (typeof value !== 'string' && !Array.isArray(value)) return false\n const lower = field.toLowerCase()\n if (lower === 'id' || lower.endsWith('_id') || lower.endsWith('.id')) return false\n if (lower.endsWith('_at')) return false\n if (['created_at', 'updated_at', 'deleted_at', 'tenant_id', 'organization_id'].includes(lower)) return false\n if (isSearchFieldBlocklisted(field, entityType, config)) return false\n if (isIndexDocEnrichedKey(entityType, field)) return false\n return collectTextValues(value).some((text) => text.length > 0)\n}\n\n/**\n * Builds the `search_tokens` rows for one document.\n *\n * `maxTokensPerRecord` is spent in the iteration order of `params.doc`'s own keys: fields are\n * tokenized one after another and the loop stops at the first field that exhausts the budget, so\n * on an over-budget record the surviving fields are whichever ones come first. That order is a\n * property of the object handed in, not of the entity, and the two write-path builders order it\n * differently: `buildIndexDocument` (`lib/document.ts`, the batch reindex path) appends `cf:*` keys\n * after the base columns and the aggregate `search_text` field last. `buildIndexDoc` (`lib/indexer.ts`,\n * the incremental single-record write path \u2014 `upsertIndexRow` \u2192 `reindexSearchTokensForRecord`) adds\n * `l10n:{locale}:{field}` translation keys between the `cf:*` keys and `search_text`. The budget is\n * spent front-to-back, so the fields nearest the end of that order are starved first: `search_text`\n * is last on both paths and starves first either way, but starves sooner on the incremental path,\n * because the `l10n:*` keys ahead of it there consume budget the batch path would have spent on it.\n * Those translation fields starve next, before any `cf:*` key or base column. The two paths can\n * therefore keep different fields searchable for an otherwise equivalent record.\n *\n * Every write path tokenizes an in-memory document it is about to write \u2014 `TokenSearchStrategy.index`\n * writes only `search_tokens` rows and never touches `entity_indexes.doc` \u2014 which keeps each path\n * self-consistent on its own. A document read back out of the `entity_indexes.doc` `jsonb` column is\n * not the same object: Postgres stores `jsonb` keys in a canonical order (by key length, then byte\n * order), not in insertion order. Re-tokenizing such a document can therefore truncate at a different\n * field than the write did, so code that verifies or recomputes a record's expected tokens must\n * rebuild the document through the builder that matches the write path being checked \u2014 `buildIndexDoc`\n * for incrementally-written records, `buildIndexDocument` for batch-reindexed ones \u2014 rather than\n * reading it back from the database.\n *\n * Making truncation reproducible from a `jsonb` read \u2014 by sorting fields before tokenization \u2014\n * would change which terms stay searchable on over-budget records, so it is a behavior decision\n * rather than a clarification (#5971).\n */\nexport function buildSearchTokenRows(params: BuildTokenOptions): SearchTokenRow[] {\n if (TOKEN_EXCLUDED_ENTITY_TYPES.has(params.entityType)) return []\n const config = params.config ?? resolveSearchConfig()\n if (!config.enabled) return []\n if (!params.doc) return []\n const tokens: SearchTokenRow[] = []\n const capturePairs = isSearchDebugEnabled() && params.entityType === 'customers:customer_deal'\n const debugPairs: Array<{ field: string; hash: string }> = []\n const scope = {\n organizationId: params.organizationId ?? DEFAULT_SCOPE.organizationId,\n tenantId: params.tenantId ?? DEFAULT_SCOPE.tenantId,\n }\n const limits = resolveSearchTokenLimits(config)\n const recordLimit = limits.maxTokensPerRecord > 0 ? limits.maxTokensPerRecord : Number.POSITIVE_INFINITY\n const fieldLimit = limits.maxTokensPerField > 0 ? limits.maxTokensPerField : Number.POSITIVE_INFINITY\n const ciphertextFields = ciphertextFieldsOf(params.doc, params.guardCiphertext ?? shouldGuardCiphertext())\n warnCiphertextSkipped(params.entityType, scope.tenantId, ciphertextFields)\n\n for (const [field, rawValue] of Object.entries(params.doc)) {\n if (tokens.length >= recordLimit) break\n if (ciphertextFields.has(field)) continue\n if (!shouldIndexField(field, rawValue, config, params.entityType)) continue\n const values = collectTextValues(rawValue)\n const seen = new Set<string>()\n let fieldTokenCount = 0\n for (const text of values) {\n if (tokens.length >= recordLimit || fieldTokenCount >= fieldLimit) break\n const remainingLimit = Math.min(recordLimit - tokens.length, fieldLimit - fieldTokenCount)\n const candidateLimit = fieldTokenCount + remainingLimit\n const tokenConfig = Number.isFinite(candidateLimit)\n ? { ...config, maxTokensPerField: candidateLimit }\n : config\n const { tokens: textTokens, hashes } = tokenizeText(text, tokenConfig)\n for (let i = 0; i < textTokens.length; i += 1) {\n if (tokens.length >= recordLimit || fieldTokenCount >= fieldLimit) break\n const token = textTokens[i]\n const hash = hashes[i]\n const dedupeKey = `${field}|${hash}`\n if (seen.has(dedupeKey)) continue\n seen.add(dedupeKey)\n fieldTokenCount += 1\n debug('token.generated', { entityType: params.entityType, recordId: params.recordId, field, hash })\n tokens.push({\n entity_type: params.entityType,\n entity_id: String(params.recordId),\n organization_id: scope.organizationId,\n tenant_id: scope.tenantId,\n field,\n token_hash: hash,\n token: config.storeRawTokens ? token : null,\n })\n if (capturePairs) {\n debugPairs.push({ field, hash })\n }\n }\n }\n }\n if (capturePairs) {\n debug('deal.tokens', {\n entityType: params.entityType,\n recordId: params.recordId,\n tokenCount: debugPairs.length,\n tokens: debugPairs,\n })\n }\n debug('doc.completed', { entityType: params.entityType, recordId: params.recordId, tokenCount: tokens.length })\n\n return tokens\n}\n\nfunction buildFieldPairs(\n recordId: string,\n doc?: Record<string, unknown> | null,\n skipFields?: Set<string>,\n): EntityFieldPair[] {\n if (!doc) return []\n const pairs: EntityFieldPair[] = []\n const dedupe = new Set<string>()\n for (const field of Object.keys(doc)) {\n // The delete below is scoped to these pairs, so omitting a field here is what preserves the\n // tokens already stored for it rather than merely declining to write new ones.\n if (skipFields?.has(field)) continue\n const key = `${recordId}|${field}`\n if (dedupe.has(key)) continue\n dedupe.add(key)\n pairs.push([recordId, field])\n }\n return pairs\n}\n\ntype TokenRowLike = { field?: unknown; token_hash?: unknown; token?: unknown }\n\n// NUL, not a printable separator: a field name may itself contain a space, so `a b` + hash `c`\n// would otherwise sign identically to field `a` + hash `b c`.\nconst SIGNATURE_SEPARATOR = String.fromCharCode(0)\n\n// Identifies one token row for comparison. `token` is NULL unless `storeRawTokens` is on, and a\n// stored NULL has to sign the same as the `null` a freshly built row carries \u2014 otherwise every\n// record compares as changed and the skip never fires.\nfunction tokenSignature(row: TokenRowLike): string {\n return [\n String(row.field ?? ''),\n String(row.token_hash ?? ''),\n row.token == null ? '' : String(row.token),\n ].join(SIGNATURE_SEPARATOR)\n}\n\n// Multiplicities, not sets: #4681 reports token rows duplicated by the concurrent-replacement\n// defect, and a set comparison reads such a record as already correct and preserves the duplicates\n// forever. Counting sends it through a full rewrite, which collapses them.\nfunction tallyOf(rows: Iterable<TokenRowLike>): Map<string, number> {\n const tally = new Map<string, number>()\n for (const row of rows) {\n const signature = tokenSignature(row)\n tally.set(signature, (tally.get(signature) ?? 0) + 1)\n }\n return tally\n}\n\nfunction tallyEquals(a: Map<string, number> | undefined, b: Map<string, number> | undefined): boolean {\n const left = a ?? new Map<string, number>()\n const right = b ?? new Map<string, number>()\n if (left.size !== right.size) return false\n for (const [key, count] of left.entries()) {\n if (right.get(key) !== count) return false\n }\n return true\n}\n\nfunction tallyTokenRows<TRow extends TokenRowLike>(\n rows: Iterable<TRow>,\n keyOf: (row: TRow) => string\n): Map<string, Map<string, number>> {\n const tallies = new Map<string, Map<string, number>>()\n for (const row of rows) {\n const key = keyOf(row)\n const tally = tallies.get(key) ?? new Map<string, number>()\n const signature = tokenSignature(row)\n tally.set(signature, (tally.get(signature) ?? 0) + 1)\n tallies.set(key, tally)\n }\n return tallies\n}\n\nexport async function replaceSearchTokensForRecord(\n db: Kysely<any>,\n params: BuildTokenOptions,\n options?: { trx?: SearchTokenExecutor },\n): Promise<void> {\n if (TOKEN_EXCLUDED_ENTITY_TYPES.has(params.entityType)) {\n await deleteSearchTokensForRecord(db, params, options)\n return\n }\n const guardCiphertext = params.guardCiphertext ?? shouldGuardCiphertext()\n const rows = buildSearchTokenRows({ ...params, guardCiphertext })\n const config = params.config ?? resolveSearchConfig()\n if (!config.enabled) return\n const organizationId = params.organizationId ?? null\n const tenantId = params.tenantId ?? null\n const ciphertextFields = ciphertextFieldsOf(params.doc, guardCiphertext)\n const fieldPairs = buildFieldPairs(String(params.recordId), params.doc, ciphertextFields)\n\n // An empty pair list normally means the document is gone, and the delete below then purges the\n // record wholesale. It can now also mean every field was skipped as ciphertext, where a purge\n // would destroy precisely the tokens the skip exists to protect. Distinguish the two.\n if (params.doc && ciphertextFields.size && !fieldPairs.length) {\n debug('record.preserve-ciphertext', { entityType: params.entityType, recordId: params.recordId })\n return\n }\n\n // Same comparison #5402 gave the batch path, over the scope this path actually writes: the\n // delete below is narrowed to the document's own `(entity_id, field)` pairs, so the comparison\n // has to be narrowed the same way. Reading wider would let a token row under a field this\n // document does not carry \u2014 the `cf_` twin the search module used to write, say \u2014 read as a\n // difference forever and defeat the skip on every write.\n const scopeTokenQuery = (query: any): any => {\n let scoped = query\n .where('entity_type' as any, '=', params.entityType)\n .where(sql<boolean>`organization_id is not distinct from ${organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantId}`)\n .where('entity_id' as any, '=', String(params.recordId))\n if (fieldPairs.length) {\n scoped = scoped.where('field' as any, 'in', fieldPairs.map(([, field]) => field))\n }\n return scoped\n }\n\n // Read through the caller's transaction when there is one. A separate connection cannot see that\n // transaction's own uncommitted writes, so it could report rows a pending delete has already\n // removed and talk this call out of re-inserting them.\n const reader = options?.trx ?? db\n\n // Count probe first, as in the batch path: it returns one row whatever the table holds, so a\n // record whose stored rows have run away (#4681) is settled without materializing them.\n const storedCountRows = await scopeTokenQuery(\n reader.selectFrom('search_tokens' as any).select(sql<number>`count(*)`.as('token_count') as any),\n ).execute()\n const storedCount = Number((storedCountRows as any[])[0]?.token_count ?? 0)\n\n let unchanged = storedCount === rows.length\n if (unchanged && rows.length) {\n const stored = await scopeTokenQuery(\n reader.selectFrom('search_tokens' as any).select(['field' as any, 'token_hash' as any, 'token' as any]),\n )\n // Counts already match, so this cannot truncate. It bounds the read if a concurrent writer\n // inserts between the probe and here; a truncated read compares as changed, which costs a\n // rewrite rather than a wrong skip.\n .limit(rows.length)\n .execute()\n unchanged = tallyEquals(tallyOf(rows), tallyOf(stored as any[]))\n }\n if (unchanged) {\n debug('record.skip', { entityType: params.entityType, recordId: params.recordId, tokenCount: rows.length })\n return\n }\n\n const writeTokens = async (executor: SearchTokenExecutor): Promise<void> => {\n let deleteQuery = executor\n .deleteFrom('search_tokens' as any)\n .where('entity_type' as any, '=', params.entityType)\n .where(sql<boolean>`organization_id is not distinct from ${organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantId}`)\n if (fieldPairs.length) {\n deleteQuery = deleteQuery.where((eb: any) => eb.or(\n fieldPairs.map(([rid, field]) => eb.and([\n eb('entity_id' as any, '=', rid),\n eb('field' as any, '=', field),\n ])),\n ))\n } else {\n deleteQuery = deleteQuery.where('entity_id' as any, '=', String(params.recordId))\n }\n await deleteQuery.execute()\n if (!rows.length) return\n const payloads = rows.map((row) => ({ ...row, created_at: sql`now()` }))\n for (const batch of chunk(payloads, INSERT_BATCH_SIZE)) {\n await executor.insertInto('search_tokens' as any).values(batch as any).execute()\n }\n }\n\n if (options?.trx) {\n await writeTokens(options.trx)\n return\n }\n\n await db.transaction().execute(writeTokens)\n}\n\nexport async function deleteSearchTokensForRecord(\n db: Kysely<any>,\n params: { entityType: string; recordId: string; organizationId?: string | null; tenantId?: string | null },\n options?: { trx?: SearchTokenExecutor },\n): Promise<void> {\n const organizationId = params.organizationId ?? null\n const tenantId = params.tenantId ?? null\n const executor = options?.trx ?? db\n await executor\n .deleteFrom('search_tokens' as any)\n .where('entity_type' as any, '=', params.entityType)\n .where('entity_id' as any, '=', String(params.recordId))\n .where(sql<boolean>`organization_id is not distinct from ${organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantId}`)\n .execute()\n}\n\nexport async function replaceSearchTokensForBatch(\n db: Kysely<any>,\n allPayloads: Array<BuildTokenOptions & { doc: Record<string, unknown> }>\n): Promise<void> {\n if (!allPayloads.length) return\n const excludedBuckets = new Map<string, {\n entityType: string\n organizationId: string | null\n tenantId: string | null\n ids: Set<string>\n }>()\n const indexablePayloads = allPayloads.filter((payload) => {\n if (!TOKEN_EXCLUDED_ENTITY_TYPES.has(payload.entityType)) return true\n const organizationId = payload.organizationId ?? null\n const tenantId = payload.tenantId ?? null\n const key = JSON.stringify([payload.entityType, organizationId, tenantId])\n const bucket = excludedBuckets.get(key) ?? {\n entityType: payload.entityType,\n organizationId,\n tenantId,\n ids: new Set<string>(),\n }\n bucket.ids.add(String(payload.recordId))\n excludedBuckets.set(key, bucket)\n return false\n })\n if (excludedBuckets.size) {\n await db.transaction().execute(async (trx) => {\n for (const bucket of excludedBuckets.values()) {\n await trx\n .deleteFrom('search_tokens')\n .where('entity_type', '=', bucket.entityType)\n .where(sql<boolean>`organization_id is not distinct from ${bucket.organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${bucket.tenantId}`)\n .where('entity_id', 'in', Array.from(bucket.ids))\n .execute()\n }\n })\n }\n if (!indexablePayloads.length) return\n const config = resolveSearchConfig()\n if (!config.enabled) return\n\n // A record carrying ciphertext drops out of the batch entirely, rather than being rewritten\n // without its encrypted fields. This path deletes by `entity_id` -- it cannot express \"replace\n // these fields and leave those alone\" the way the per-record path can -- so partial handling\n // here would still delete the tokens we are trying to protect. Skipping the record leaves every\n // one of its tokens, encrypted-field and plaintext-field alike, exactly as it was. The state is\n // transient by construction: `decrypt-database` followed by a reindex rebuilds all of it.\n let processGuard: boolean | undefined\n const guardFor = (payload: BuildTokenOptions): boolean =>\n payload.guardCiphertext ?? (processGuard ??= shouldGuardCiphertext())\n const preservedRecordIds = new Set<string>()\n const payloads = indexablePayloads.filter((payload) => {\n const ciphertextFields = ciphertextFieldsOf(payload.doc, guardFor(payload))\n if (!ciphertextFields.size) return true\n warnCiphertextSkipped(payload.entityType, payload.tenantId ?? null, ciphertextFields)\n preservedRecordIds.add(String(payload.recordId))\n return false\n })\n if (!payloads.length) return\n\n const rows = payloads.flatMap((payload) => buildSearchTokenRows({ ...payload, config, guardCiphertext: guardFor(payload) }))\n if (!rows.length) {\n const entityType = payloads[0]?.entityType\n if (!entityType) return\n const ids = payloads.map((p) => String(p.recordId))\n await db\n .deleteFrom('search_tokens' as any)\n .where('entity_type' as any, '=', entityType)\n .where('entity_id' as any, 'in', ids)\n .execute()\n return\n }\n\n const scopeKey = (org: string | null, tenant: string | null) => `${org ?? '__null__'}|${tenant ?? '__null__'}`\n const scopeBuckets = new Map<string, { organizationId: string | null; tenantId: string | null; ids: Set<string> }>()\n\n for (const payload of payloads) {\n const org = payload.organizationId ?? null\n const tenant = payload.tenantId ?? null\n const key = scopeKey(org, tenant)\n const bucket = scopeBuckets.get(key) ?? { organizationId: org, tenantId: tenant, ids: new Set<string>() }\n bucket.ids.add(String(payload.recordId))\n scopeBuckets.set(key, bucket)\n }\n\n const recordKeyOf = (row: SearchTokenRow) =>\n `${scopeKey(row.organization_id ?? null, row.tenant_id ?? null)}|${String(row.entity_id)}`\n const builtTally = tallyTokenRows(rows, recordKeyOf)\n\n // Read outside the transaction, deliberately. The comparison decides only whether to skip a\n // rewrite, so a concurrent writer costs us at most a rewrite we declined \u2014 declined because the\n // table already held exactly the rows this call wanted to write. One ordering is worth naming\n // though: if the read matches and a concurrent writer then commits tokens built from a *staler*\n // doc, the unconditional rewrite this call used to perform would have overwritten them by\n // accident. It no longer does, so those stale rows survive until the record's next write. That\n // is a repair we lose, not a guarantee we break.\n const changedIdsByBucket = new Map<string, Set<string>>()\n for (const [key, bucket] of scopeBuckets.entries()) {\n const ids = Array.from(bucket.ids)\n const builtCountById = new Map<string, number>()\n for (const id of ids) {\n let total = 0\n const tally = builtTally.get(`${key}|${id}`)\n if (tally) for (const count of tally.values()) total += count\n builtCountById.set(id, total)\n }\n\n // Count probe first. Its result is one row per record in the batch, so it is bounded by the\n // batch size \u2014 unlike a bare row read, which would be bounded only by how many token rows the\n // table already holds for these ids, a quantity this function does not control and (per #4681)\n // has no reason to trust.\n const storedCounts = await db\n .selectFrom('search_tokens' as any)\n .select(['entity_id' as any, sql<number>`count(*)`.as('token_count') as any])\n .where('entity_type' as any, '=', payloads[0].entityType)\n .where(sql<boolean>`organization_id is not distinct from ${bucket.organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${bucket.tenantId}`)\n .where('entity_id' as any, 'in', ids)\n .groupBy('entity_id' as any)\n .execute()\n const storedCountById = new Map<string, number>()\n for (const row of storedCounts as any[]) {\n storedCountById.set(String(row.entity_id), Number(row.token_count))\n }\n\n const changed = new Set<string>()\n // A record whose stored row count already differs is changed, whatever the rows say \u2014 the\n // duplicate case from #4681 resolves here without ever materializing the duplicated rows.\n const contentCandidates = ids.filter((id) => {\n const builtCount = builtCountById.get(id) ?? 0\n if ((storedCountById.get(id) ?? 0) !== builtCount) {\n changed.add(id)\n return false\n }\n return builtCount > 0\n })\n\n if (contentCandidates.length) {\n const rowBudget = contentCandidates.reduce((sum, id) => sum + (builtCountById.get(id) ?? 0), 0)\n const stored = await db\n .selectFrom('search_tokens' as any)\n .select(['entity_id' as any, 'field' as any, 'token_hash' as any, 'token' as any])\n .where('entity_type' as any, '=', payloads[0].entityType)\n .where(sql<boolean>`organization_id is not distinct from ${bucket.organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${bucket.tenantId}`)\n .where('entity_id' as any, 'in', contentCandidates)\n // Counts already match, so this cannot truncate \u2014 it bounds the damage if a concurrent\n // writer inserts between the probe and this read. A truncated read compares as changed,\n // which costs a rewrite rather than a wrong skip.\n .limit(rowBudget)\n .execute()\n const storedTally = tallyTokenRows(stored as any[], (row) => String(row.entity_id))\n for (const id of contentCandidates) {\n if (!tallyEquals(builtTally.get(`${key}|${id}`), storedTally.get(id))) changed.add(id)\n }\n }\n changedIdsByBucket.set(key, changed)\n }\n\n const changedRecordKeys = new Set<string>()\n for (const [key, changed] of changedIdsByBucket.entries()) {\n for (const id of changed) changedRecordKeys.add(`${key}|${id}`)\n }\n debug('batch.skip', {\n entityType: payloads[0].entityType,\n recordCount: payloads.length,\n changedCount: changedRecordKeys.size,\n preservedCiphertextRecordCount: preservedRecordIds.size,\n })\n if (!changedRecordKeys.size) return\n\n await db.transaction().execute(async (trx) => {\n for (const [key, bucket] of scopeBuckets.entries()) {\n const changed = changedIdsByBucket.get(key)\n if (!changed?.size) continue\n // Delete by entity_id: a batch replaces all of a record's tokens, and a per-field OR over the\n // whole batch overflows the query compiler's call stack on large batches.\n const deleteQuery = trx\n .deleteFrom('search_tokens' as any)\n .where('entity_type' as any, '=', payloads[0].entityType)\n .where(sql<boolean>`organization_id is not distinct from ${bucket.organizationId}`)\n .where(sql<boolean>`tenant_id is not distinct from ${bucket.tenantId}`)\n .where('entity_id' as any, 'in', Array.from(changed))\n await deleteQuery.execute()\n }\n const payloadWithTimestamps = rows\n .filter((row) => changedRecordKeys.has(recordKeyOf(row)))\n .map((row) => ({ ...row, created_at: sql`now()` }))\n for (const batch of chunk(payloadWithTimestamps, INSERT_BATCH_SIZE)) {\n await trx.insertInto('search_tokens' as any).values(batch as any).execute()\n }\n })\n}\n"],
5
+ "mappings": "AAAA,SAAwC,WAAW;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AAC,EAAE;AAAA,IACxB,aAAa,SAAS;AAAA,IACtB,cAAc,kBAAkB;AAAA,IAChC,gCAAgC,mBAAmB;AAAA,EACrD,CAAC;AACD,MAAI,CAAC,kBAAkB,KAAM;AAE7B,QAAM,GAAG,YAAY,EAAE,QAAQ,OAAO,QAAQ;AAC5C,eAAW,CAAC,KAAK,MAAM,KAAK,aAAa,QAAQ,GAAG;AAClD,YAAM,UAAU,mBAAmB,IAAI,GAAG;AAC1C,UAAI,CAAC,SAAS,KAAM;AAGpB,YAAM,cAAc,IACjB,WAAW,eAAsB,EACjC,MAAM,eAAsB,KAAK,SAAS,CAAC,EAAE,UAAU,EACvD,MAAM,2CAAoD,OAAO,cAAc,EAAE,EACjF,MAAM,qCAA8C,OAAO,QAAQ,EAAE,EACrE,MAAM,aAAoB,MAAM,MAAM,KAAK,OAAO,CAAC;AACtD,YAAM,YAAY,QAAQ;AAAA,IAC5B;AACA,UAAM,wBAAwB,KAC3B,OAAO,CAAC,QAAQ,kBAAkB,IAAI,YAAY,GAAG,CAAC,CAAC,EACvD,IAAI,CAAC,SAAS,EAAE,GAAG,KAAK,YAAY,WAAW,EAAE;AACpD,eAAW,SAAS,MAAM,uBAAuB,iBAAiB,GAAG;AACnE,YAAM,IAAI,WAAW,eAAsB,EAAE,OAAO,KAAY,EAAE,QAAQ;AAAA,IAC5E;AAAA,EACF,CAAC;AACH;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.11.1-develop.8517.1.f52e23452d",
3
+ "version": "0.11.1-develop.8523.1.c6b0fd2058",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -268,16 +268,16 @@
268
268
  "zod": "^4.6.6"
269
269
  },
270
270
  "peerDependencies": {
271
- "@open-mercato/ai-assistant": "0.11.1-develop.8517.1.f52e23452d",
272
- "@open-mercato/shared": "0.11.1-develop.8517.1.f52e23452d",
273
- "@open-mercato/ui": "0.11.1-develop.8517.1.f52e23452d",
271
+ "@open-mercato/ai-assistant": "0.11.1-develop.8523.1.c6b0fd2058",
272
+ "@open-mercato/shared": "0.11.1-develop.8523.1.c6b0fd2058",
273
+ "@open-mercato/ui": "0.11.1-develop.8523.1.c6b0fd2058",
274
274
  "react": "^19.0.0",
275
275
  "react-dom": "^19.0.0"
276
276
  },
277
277
  "devDependencies": {
278
- "@open-mercato/ai-assistant": "0.11.1-develop.8517.1.f52e23452d",
279
- "@open-mercato/shared": "0.11.1-develop.8517.1.f52e23452d",
280
- "@open-mercato/ui": "0.11.1-develop.8517.1.f52e23452d",
278
+ "@open-mercato/ai-assistant": "0.11.1-develop.8523.1.c6b0fd2058",
279
+ "@open-mercato/shared": "0.11.1-develop.8523.1.c6b0fd2058",
280
+ "@open-mercato/ui": "0.11.1-develop.8523.1.c6b0fd2058",
281
281
  "@testing-library/dom": "^10.4.1",
282
282
  "@testing-library/jest-dom": "^7.0.1",
283
283
  "@testing-library/react": "^16.3.3",
@@ -35,6 +35,7 @@ import { Organization } from '@open-mercato/core/modules/directory/data/entities
35
35
  import { CustomEntity } from '@open-mercato/core/modules/entities/data/entities'
36
36
  import { Role } from '@open-mercato/core/modules/auth/data/entities'
37
37
  import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
38
+ import { isExplicitlyEmptyOrganizationScope } from '@open-mercato/shared/lib/auth/organizationScope'
38
39
  import {
39
40
  applySidebarPreference,
40
41
  findSidebarPreference,
@@ -367,6 +368,7 @@ export async function resolveBackendChromePayload({
367
368
  // resolved id cannot answer "which organization am I viewing".
368
369
  let concretelySelectedOrganizationId: string | null = null
369
370
  let allowNavigation = true
371
+ let organizationScopeIsEmpty = false
370
372
 
371
373
  try {
372
374
  const { organizationId, scope, allowedOrganizationIds } = await resolveFeatureCheckContext({
@@ -379,6 +381,7 @@ export async function resolveBackendChromePayload({
379
381
  scopedOrganizationId = organizationId
380
382
  scopedTenantId = scope.tenantId ?? auth.tenantId ?? null
381
383
  concretelySelectedOrganizationId = scope.selectedId ?? null
384
+ organizationScopeIsEmpty = isExplicitlyEmptyOrganizationScope(scope)
382
385
  if (Array.isArray(allowedOrganizationIds) && allowedOrganizationIds.length === 0) {
383
386
  allowNavigation = false
384
387
  }
@@ -505,8 +508,10 @@ export async function resolveBackendChromePayload({
505
508
 
506
509
  const requestOrganizationId = request ? getSelectedOrganizationFromRequest(request) : null
507
510
  const fallbackOrganizationId = selectedOrganizationId ?? requestOrganizationId ?? auth.orgId ?? null
508
- const brandOrganizationId = scopedOrganizationId
509
- ?? (fallbackOrganizationId && !isAllOrganizationsSelection(fallbackOrganizationId) ? fallbackOrganizationId : null)
511
+ const brandOrganizationId = organizationScopeIsEmpty
512
+ ? null
513
+ : scopedOrganizationId
514
+ ?? (fallbackOrganizationId && !isAllOrganizationsSelection(fallbackOrganizationId) ? fallbackOrganizationId : null)
510
515
 
511
516
  let brand: BackendChromePayload['brand'] = null
512
517
  // Resolved here rather than left to callers. `brand` only populates when the organization has a