|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + * |
| 4 | + * Structural guard for the tag-slot check in `updateDocument`. |
| 5 | + * |
| 6 | + * The property under test is not an interleaving — a real race cannot be |
| 7 | + * reproduced against a mocked driver — but the shape that makes the |
| 8 | + * interleaving impossible: the check must run inside the write's transaction, |
| 9 | + * after the knowledge-base row lock tag deletion also takes, and before the |
| 10 | + * document row is written. Read outside that lock it is check-then-act, and a |
| 11 | + * tag deletion committing in between strands a value in a slot no definition |
| 12 | + * covers. |
| 13 | + * |
| 14 | + * The shared drizzle mock hands the transaction callback the same client as |
| 15 | + * `db`, so "ran against the transaction" cannot be asserted by identity; call |
| 16 | + * ordering relative to `db.transaction` is what pins it. |
| 17 | + */ |
| 18 | +import { document, knowledgeBase, knowledgeBaseTagDefinitions } from '@sim/db/schema' |
| 19 | +import { dbChainMockFns, queueTableRows, resetDbChainMock } from '@sim/testing' |
| 20 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 21 | + |
| 22 | +const { |
| 23 | + mockApplyStorageUsageDeltasInTx, |
| 24 | + mockCheckStorageQuota, |
| 25 | + mockCheckStorageQuotaForBillingContext, |
| 26 | + mockDecrementStorageUsageForBillingContextInTx, |
| 27 | + mockIncrementStorageUsageForBillingContextInTx, |
| 28 | + mockMaybeNotifyStorageLimitForBillingContext, |
| 29 | + mockResolveStorageBillingContext, |
| 30 | + mockGetFileMetadataByKeys, |
| 31 | + mockEnqueueKnowledgeDocumentProcessing, |
| 32 | +} = vi.hoisted(() => ({ |
| 33 | + mockApplyStorageUsageDeltasInTx: vi.fn(), |
| 34 | + mockCheckStorageQuota: vi.fn(), |
| 35 | + mockCheckStorageQuotaForBillingContext: vi.fn(), |
| 36 | + mockDecrementStorageUsageForBillingContextInTx: vi.fn(), |
| 37 | + mockIncrementStorageUsageForBillingContextInTx: vi.fn(), |
| 38 | + mockMaybeNotifyStorageLimitForBillingContext: vi.fn(), |
| 39 | + mockResolveStorageBillingContext: vi.fn(), |
| 40 | + mockGetFileMetadataByKeys: vi.fn(), |
| 41 | + mockEnqueueKnowledgeDocumentProcessing: vi.fn(), |
| 42 | +})) |
| 43 | + |
| 44 | +vi.mock('@/lib/billing/storage', () => ({ |
| 45 | + applyStorageUsageDeltasInTx: mockApplyStorageUsageDeltasInTx, |
| 46 | + checkStorageQuota: mockCheckStorageQuota, |
| 47 | + checkStorageQuotaForBillingContext: mockCheckStorageQuotaForBillingContext, |
| 48 | + decrementStorageUsageForBillingContextInTx: mockDecrementStorageUsageForBillingContextInTx, |
| 49 | + incrementStorageUsageForBillingContextInTx: mockIncrementStorageUsageForBillingContextInTx, |
| 50 | + maybeNotifyStorageLimitForBillingContext: mockMaybeNotifyStorageLimitForBillingContext, |
| 51 | + resolveStorageBillingContext: mockResolveStorageBillingContext, |
| 52 | +})) |
| 53 | + |
| 54 | +vi.mock('@/lib/uploads/server/metadata', () => ({ |
| 55 | + deleteFileMetadata: vi.fn(), |
| 56 | + getFileMetadataByKeys: mockGetFileMetadataByKeys, |
| 57 | +})) |
| 58 | + |
| 59 | +vi.mock('@/lib/knowledge/documents/processing-outbox-event', () => ({ |
| 60 | + enqueueKnowledgeDocumentProcessing: mockEnqueueKnowledgeDocumentProcessing, |
| 61 | +})) |
| 62 | + |
| 63 | +import { createSingleDocument, updateDocument } from '@/lib/knowledge/documents/service' |
| 64 | + |
| 65 | +const KNOWLEDGE_BASE_ID = 'kb-1' |
| 66 | +const NOW = new Date('2026-01-01T00:00:00.000Z') |
| 67 | + |
| 68 | +/** invocationCallOrder of the first call to `spy` whose first argument is `table`. */ |
| 69 | +function orderForTable( |
| 70 | + spy: { mock: { calls: unknown[][]; invocationCallOrder: number[] } }, |
| 71 | + table: unknown |
| 72 | +): number { |
| 73 | + for (let i = 0; i < spy.mock.calls.length; i++) { |
| 74 | + if (spy.mock.calls[i][0] === table) return spy.mock.invocationCallOrder[i] |
| 75 | + } |
| 76 | + return -1 |
| 77 | +} |
| 78 | + |
| 79 | +function definition(tagSlot: string, displayName: string) { |
| 80 | + return { |
| 81 | + id: `tag-def-${tagSlot}`, |
| 82 | + knowledgeBaseId: KNOWLEDGE_BASE_ID, |
| 83 | + tagSlot, |
| 84 | + displayName, |
| 85 | + fieldType: 'text', |
| 86 | + createdAt: NOW, |
| 87 | + updatedAt: NOW, |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +describe('updateDocument tag-slot validation', () => { |
| 92 | + beforeEach(() => { |
| 93 | + vi.clearAllMocks() |
| 94 | + resetDbChainMock() |
| 95 | + queueTableRows(document, [ |
| 96 | + { id: 'doc-1', knowledgeBaseId: KNOWLEDGE_BASE_ID, secretProvenanceVersion: null }, |
| 97 | + ]) |
| 98 | + dbChainMockFns.returning.mockResolvedValue([ |
| 99 | + { id: 'doc-1', knowledgeBaseId: KNOWLEDGE_BASE_ID, secretProvenanceVersion: null }, |
| 100 | + ]) |
| 101 | + }) |
| 102 | + |
| 103 | + it('checks the slot inside the write transaction, under the knowledge-base row lock, before writing', async () => { |
| 104 | + queueTableRows(knowledgeBaseTagDefinitions, [definition('tag1', 'category')]) |
| 105 | + |
| 106 | + await updateDocument('doc-1', { tag1: 'priority' }, 'req-1', { |
| 107 | + knowledgeBaseId: KNOWLEDGE_BASE_ID, |
| 108 | + }) |
| 109 | + |
| 110 | + const transactionOrder = dbChainMockFns.transaction.mock.invocationCallOrder[0] |
| 111 | + const lockOrder = dbChainMockFns.execute.mock.invocationCallOrder[0] ?? -1 |
| 112 | + const definitionReadOrder = orderForTable(dbChainMockFns.from, knowledgeBaseTagDefinitions) |
| 113 | + const documentWriteOrder = orderForTable(dbChainMockFns.update, document) |
| 114 | + |
| 115 | + expect(transactionOrder).toBeGreaterThan(0) |
| 116 | + expect(lockOrder).toBeGreaterThan(transactionOrder) |
| 117 | + expect(definitionReadOrder).toBeGreaterThan(lockOrder) |
| 118 | + expect(documentWriteOrder).toBeGreaterThan(definitionReadOrder) |
| 119 | + }) |
| 120 | + |
| 121 | + it('refuses a slot no definition covers, and writes neither the document nor its embeddings', async () => { |
| 122 | + queueTableRows(knowledgeBaseTagDefinitions, [definition('tag1', 'category')]) |
| 123 | + |
| 124 | + await expect( |
| 125 | + updateDocument('doc-1', { tag2: 'purple' }, 'req-1', { |
| 126 | + knowledgeBaseId: KNOWLEDGE_BASE_ID, |
| 127 | + }) |
| 128 | + ).rejects.toMatchObject({ code: 'validation' }) |
| 129 | + |
| 130 | + expect(dbChainMockFns.update).not.toHaveBeenCalled() |
| 131 | + }) |
| 132 | + |
| 133 | + it('takes no knowledge-base lock for an update that lands no tag value', async () => { |
| 134 | + await updateDocument('doc-1', { filename: 'renamed.txt' }, 'req-1', { |
| 135 | + knowledgeBaseId: KNOWLEDGE_BASE_ID, |
| 136 | + }) |
| 137 | + |
| 138 | + expect(dbChainMockFns.execute).not.toHaveBeenCalled() |
| 139 | + expect(orderForTable(dbChainMockFns.from, knowledgeBase)).toBe(-1) |
| 140 | + expect(orderForTable(dbChainMockFns.update, document)).toBeGreaterThan(0) |
| 141 | + }) |
| 142 | + |
| 143 | + it('takes no knowledge-base lock when clearing a slot, so a stranded value stays erasable', async () => { |
| 144 | + await updateDocument('doc-1', { tag2: '' }, 'req-1', { knowledgeBaseId: KNOWLEDGE_BASE_ID }) |
| 145 | + |
| 146 | + expect(dbChainMockFns.execute).not.toHaveBeenCalled() |
| 147 | + expect(orderForTable(dbChainMockFns.update, document)).toBeGreaterThan(0) |
| 148 | + }) |
| 149 | +}) |
| 150 | + |
| 151 | +describe('createSingleDocument tag-slot validation', () => { |
| 152 | + beforeEach(() => { |
| 153 | + vi.clearAllMocks() |
| 154 | + resetDbChainMock() |
| 155 | + dbChainMockFns.limit.mockResolvedValue([ |
| 156 | + { id: KNOWLEDGE_BASE_ID, workspaceId: 'workspace-1', userId: 'knowledge-owner' }, |
| 157 | + ]) |
| 158 | + mockResolveStorageBillingContext.mockResolvedValue({ |
| 159 | + workspaceId: 'workspace-1', |
| 160 | + billedAccountUserId: 'workspace-owner', |
| 161 | + billingEntity: { type: 'organization' as const, id: 'workspace-org' }, |
| 162 | + plan: 'team_25000', |
| 163 | + customStorageLimitGB: null, |
| 164 | + }) |
| 165 | + mockCheckStorageQuotaForBillingContext.mockResolvedValue({ allowed: true }) |
| 166 | + mockIncrementStorageUsageForBillingContextInTx.mockResolvedValue(5) |
| 167 | + mockApplyStorageUsageDeltasInTx.mockResolvedValue(undefined) |
| 168 | + mockMaybeNotifyStorageLimitForBillingContext.mockResolvedValue(undefined) |
| 169 | + mockGetFileMetadataByKeys.mockResolvedValue([]) |
| 170 | + mockEnqueueKnowledgeDocumentProcessing.mockResolvedValue('outbox-1') |
| 171 | + }) |
| 172 | + |
| 173 | + const documentData = { |
| 174 | + filename: 'note.txt', |
| 175 | + fileUrl: 'data:text/plain;base64,SGVsbG8=', |
| 176 | + fileSize: 5, |
| 177 | + mimeType: 'text/plain', |
| 178 | + } |
| 179 | + |
| 180 | + it('checks the slot inside the insert transaction, under the knowledge-base row lock', async () => { |
| 181 | + queueTableRows(knowledgeBaseTagDefinitions, [definition('tag1', 'category')]) |
| 182 | + |
| 183 | + await createSingleDocument({ ...documentData, tag1: 'priority' }, KNOWLEDGE_BASE_ID, 'req-1') |
| 184 | + |
| 185 | + const transactionOrder = dbChainMockFns.transaction.mock.invocationCallOrder[0] |
| 186 | + const lockOrder = dbChainMockFns.execute.mock.invocationCallOrder[0] ?? -1 |
| 187 | + const definitionReadOrder = orderForTable(dbChainMockFns.from, knowledgeBaseTagDefinitions) |
| 188 | + const documentInsertOrder = orderForTable(dbChainMockFns.insert, document) |
| 189 | + |
| 190 | + expect(transactionOrder).toBeGreaterThan(0) |
| 191 | + expect(lockOrder).toBeGreaterThan(transactionOrder) |
| 192 | + expect(definitionReadOrder).toBeGreaterThan(lockOrder) |
| 193 | + expect(documentInsertOrder).toBeGreaterThan(definitionReadOrder) |
| 194 | + }) |
| 195 | + |
| 196 | + it('refuses a slot no definition covers, and inserts nothing', async () => { |
| 197 | + queueTableRows(knowledgeBaseTagDefinitions, [definition('tag1', 'category')]) |
| 198 | + |
| 199 | + await expect( |
| 200 | + createSingleDocument({ ...documentData, tag2: 'purple' }, KNOWLEDGE_BASE_ID, 'req-1') |
| 201 | + ).rejects.toMatchObject({ code: 'validation' }) |
| 202 | + |
| 203 | + expect(orderForTable(dbChainMockFns.insert, document)).toBe(-1) |
| 204 | + }) |
| 205 | +}) |
0 commit comments