From feb12a957c0bfda172f60cb8b3cb54c89b388e9e Mon Sep 17 00:00:00 2001 From: Alegan55 Date: Sat, 5 Dec 2026 17:51:40 +0530 Subject: [PATCH] feat(cloud): support per-workspace tool invocation retention and payload trimming --- .../src/ee/cloud/kg-cron.service.spec.ts | 30 ++ .../backend/src/ee/cloud/kg-cron.service.ts | 294 +++++++++++++----- 2 files changed, 249 insertions(+), 75 deletions(-) diff --git a/packages/backend/src/ee/cloud/kg-cron.service.spec.ts b/packages/backend/src/ee/cloud/kg-cron.service.spec.ts index 362cc6056..b3b80bcb7 100644 --- a/packages/backend/src/ee/cloud/kg-cron.service.spec.ts +++ b/packages/backend/src/ee/cloud/kg-cron.service.spec.ts @@ -127,3 +127,33 @@ describe('KgCronService.trimOldPayloads', () => { expect(prisma.$executeRaw).not.toHaveBeenCalled(); }); }); + + +describe('KgCronService per-workspace retention overrides', () => { + const OLD = { ...process.env }; + afterEach(() => { process.env = { ...OLD }; jest.clearAllMocks(); }); + + function build(rows: Array<{ organizationId: string; value: string }>, execResults: number[] = []) { + const prisma: any = { orgSettings: { findMany: jest.fn().mockResolvedValue(rows) }, toolInvocation: { deleteMany: jest.fn().mockResolvedValue({ count: 0 }) }, $executeRaw: jest.fn() }; + for (const r of execResults) prisma.$executeRaw.mockResolvedValueOnce(r); + const svc = new KgCronService(prisma, {} as any, {} as any, {} as any, {} as any, {} as any); + return { svc, prisma }; + } + + it('trims payloads for overridden workspace and runs global fallback', async () => { + process.env.INVOCATION_PAYLOAD_RETENTION_DAYS = '14'; + process.env.INVOCATION_TRIM_BATCH = '100'; + process.env.INVOCATION_TRIM_MAX_BATCHES = '2'; + const { svc, prisma } = build([{ organizationId: 'org-custom', value: '3' }], [15, 25]); + await expect(svc.trimOldPayloads()).resolves.toBe(40); + expect(prisma.$executeRaw).toHaveBeenCalledTimes(2); + }); + + it('prunes rows per overridden workspace and excludes overridden orgs in retention()', async () => { + process.env.INVOCATION_RETENTION_DAYS = '90'; + const { svc, prisma } = build([{ organizationId: 'org-short', value: '30' }]); + prisma.toolInvocation.deleteMany.mockResolvedValueOnce({ count: 4 }).mockResolvedValueOnce({ count: 6 }); + await expect((svc as any).retention()).resolves.toBe(10); + expect(prisma.toolInvocation.deleteMany).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: expect.objectContaining({ organizationId: { notIn: ['org-short'] } }) })); + }); +}); diff --git a/packages/backend/src/ee/cloud/kg-cron.service.ts b/packages/backend/src/ee/cloud/kg-cron.service.ts index d1da51f43..b45b1b8f5 100644 --- a/packages/backend/src/ee/cloud/kg-cron.service.ts +++ b/packages/backend/src/ee/cloud/kg-cron.service.ts @@ -1,15 +1,16 @@ -import { Injectable, Logger } from '@nestjs/common'; -import { PrismaService } from '../../common/prisma.service'; -import { KgStaticService } from '../../knowledge-graph/kg-static.service'; -import { KgObservationalService } from '../../knowledge-graph/kg-observational.service'; -import { KgLlmService } from '../../knowledge-graph/kg-llm.service'; -import { KgSkillService } from '../../knowledge-graph/kg-skill.service'; +import { OrgSettingsService } from "../../settings/org-settings.service"; +import { Injectable, Logger } from "@nestjs/common"; +import { PrismaService } from "../../common/prisma.service"; +import { KgStaticService } from "../../knowledge-graph/kg-static.service"; +import { KgObservationalService } from "../../knowledge-graph/kg-observational.service"; +import { KgLlmService } from "../../knowledge-graph/kg-llm.service"; +import { KgSkillService } from "../../knowledge-graph/kg-skill.service"; import { resolveLlmConfig, submitBatch, getBatchResults, type BatchRequest, -} from '../../knowledge-graph/llm-client'; +} from "../../knowledge-graph/llm-client"; type LlmExtendResult = { llmOrgs: number; @@ -19,7 +20,7 @@ type LlmExtendResult = { }; function intEnv(name: string, fallback: number): number { - const v = parseInt(process.env[name] || '', 10); + const v = parseInt(process.env[name] || "", 10); return Number.isFinite(v) ? v : fallback; } @@ -45,8 +46,50 @@ export class KgCronService { private readonly kgObservational: KgObservationalService, private readonly kgLlm: KgLlmService, private readonly kgSkill: KgSkillService, + private readonly orgSettings?: OrgSettingsService, ) {} + private static readonly RETENTION_DAYS_KEY = "invocation_retention_days"; + private static readonly PAYLOAD_RETENTION_DAYS_KEY = "invocation_payload_retention_days"; + + private parseDays(raw: unknown, fallback: number): number { + if (typeof raw === "number") { + return Number.isFinite(raw) ? Math.floor(raw) : fallback; + } + if (typeof raw === "string" && raw.trim() !== "") { + const parsed = Number(raw.trim()); + return Number.isFinite(parsed) ? Math.floor(parsed) : fallback; + } + return fallback; + } + + private async getOrgOverrides( + key: string, + defaultDays: number, + ): Promise> { + if (!this.orgSettings || typeof (this.prisma as any).orgSettings?.findMany !== "function") { + return []; + } + const rows = await this.prisma.orgSettings.findMany({ + where: { key }, + select: { organizationId: true, value: true }, + }); + const overrides: Array<{ organizationId: string; days: number }> = []; + for (const row of rows) { + let parsed: unknown = row.value; + try { + parsed = JSON.parse(row.value); + } catch { + // plain string numeric value + } + const days = this.parseDays(parsed, defaultDays); + if (days !== defaultDays) { + overrides.push({ organizationId: row.organizationId, days }); + } + } + return overrides; + } + async run(): Promise<{ orgsProcessed: number; orgsTotal: number; @@ -57,7 +100,7 @@ export class KgCronService { prunedInvocations: number; trimmedPayloads: number; }> { - const maxOrgs = intEnv('KG_CRON_MAX_ORGS', 50); + const maxOrgs = intEnv("KG_CRON_MAX_ORGS", 50); // Orgs that have at least one connector. Staleness-ordered: those whose KG // was observed longest ago (or never) come first. @@ -72,14 +115,12 @@ export class KgCronService { } const allOrgs = ( await this.prisma.connector.findMany({ - distinct: ['organizationId'], + distinct: ["organizationId"], select: { organizationId: true }, }) ).map((c) => c.organizationId); - const ordered = allOrgs.sort( - (a, b) => (oldestByOrg.get(a) ?? 0) - (oldestByOrg.get(b) ?? 0), - ); + const ordered = allOrgs.sort((a, b) => (oldestByOrg.get(a) ?? 0) - (oldestByOrg.get(b) ?? 0)); const batch = ordered.slice(0, maxOrgs); let nodes = 0; @@ -138,12 +179,12 @@ export class KgCronService { * intents arrived since the last AI run. */ private async runLlmExtend(): Promise { - if (process.env.KG_LLM_CRON_ENABLED !== 'true') { + if (process.env.KG_LLM_CRON_ENABLED !== "true") { return { llmOrgs: 0, llmGraphSuggested: 0, llmSkillsCreated: 0 }; } // Batch mode (Anthropic only): submit on one run, apply on a later run, at // ~50% of the synchronous price. Opt-in via KG_LLM_BATCH. - if (process.env.KG_LLM_BATCH === 'true' && resolveLlmConfig()?.provider === 'anthropic') { + if (process.env.KG_LLM_BATCH === "true" && resolveLlmConfig()?.provider === "anthropic") { return this.runLlmExtendBatch(); } return this.runLlmExtendSync(); @@ -151,14 +192,14 @@ export class KgCronService { private async runLlmExtendSync(): Promise { const empty = { llmOrgs: 0, llmGraphSuggested: 0, llmSkillsCreated: 0 }; - if (process.env.KG_LLM_CRON_ENABLED !== 'true') return empty; + if (process.env.KG_LLM_CRON_ENABLED !== "true") return empty; - const maxOrgs = intEnv('KG_LLM_CRON_MAX_ORGS', 20); - const cooldownMs = intEnv('KG_LLM_MIN_INTERVAL_HOURS', 24) * 60 * 60 * 1000; + const maxOrgs = intEnv("KG_LLM_CRON_MAX_ORGS", 20); + const cooldownMs = intEnv("KG_LLM_MIN_INTERVAL_HOURS", 24) * 60 * 60 * 1000; // Workspaces that opted into scheduled AI extension. const optedIn = await this.prisma.orgSettings.findMany({ - where: { key: 'kg_llm_auto', value: 'true' }, + where: { key: "kg_llm_auto", value: "true" }, select: { organizationId: true }, }); if (optedIn.length === 0) return empty; @@ -213,8 +254,8 @@ export class KgCronService { // ── APPLY phase ── const pending = await this.prisma.kgLlmBatch.findFirst({ - where: { status: 'pending' }, - orderBy: { createdAt: 'asc' }, + where: { status: "pending" }, + orderBy: { createdAt: "asc" }, }); if (pending) { let graph = 0; @@ -230,12 +271,12 @@ export class KgCronService { const c = ctx[customId]; if (!c) continue; try { - if (c.type === 'enrich') { + if (c.type === "enrich") { graph += await this.kgLlm.applyEnrichResult(c.organizationId, json, { idByRef: c.idByRef, hash: c.hash, }); - } else if (c.type === 'skill') { + } else if (c.type === "skill") { skills += await this.kgSkill.applyConnectorResult(c.organizationId, json); } orgs.add(c.organizationId); @@ -260,10 +301,10 @@ export class KgCronService { } // ── SUBMIT phase ── - const maxOrgs = intEnv('KG_LLM_CRON_MAX_ORGS', 20); - const cooldownMs = intEnv('KG_LLM_MIN_INTERVAL_HOURS', 24) * 60 * 60 * 1000; + const maxOrgs = intEnv("KG_LLM_CRON_MAX_ORGS", 20); + const cooldownMs = intEnv("KG_LLM_MIN_INTERVAL_HOURS", 24) * 60 * 60 * 1000; const optedIn = await this.prisma.orgSettings.findMany({ - where: { key: 'kg_llm_auto', value: 'true' }, + where: { key: "kg_llm_auto", value: "true" }, select: { organizationId: true }, }); @@ -279,11 +320,11 @@ export class KgCronService { let added = false; const enrichReq = await this.kgLlm.buildEnrichRequest(organizationId, { force: false }); - if (enrichReq && !('skipped' in enrichReq)) { + if (enrichReq && !("skipped" in enrichReq)) { const cid = `enrich:${organizationId}`; requests.push({ customId: cid, system: enrichReq.system, user: enrichReq.user }); context[cid] = { - type: 'enrich', + type: "enrich", organizationId, idByRef: enrichReq.idByRef, hash: enrichReq.hash, @@ -295,7 +336,7 @@ export class KgCronService { if (skillReq) { const cid = `skill:${organizationId}`; requests.push({ customId: cid, system: skillReq.system, user: skillReq.user }); - context[cid] = { type: 'skill', organizationId }; + context[cid] = { type: "skill", organizationId }; added = true; } } @@ -312,17 +353,22 @@ export class KgCronService { } const externalId = await submitBatch(cfg, requests); await this.prisma.kgLlmBatch.create({ - data: { provider: cfg.provider, externalId, status: 'pending', context }, + data: { provider: cfg.provider, externalId, status: "pending", context }, }); this.logger.log( `KG LLM batch submitted: ${requests.length} request(s) across ${orgsBuilt} org(s) (${externalId}).`, ); - return { llmOrgs: 0, llmGraphSuggested: 0, llmSkillsCreated: 0, llmBatchSubmitted: requests.length }; + return { + llmOrgs: 0, + llmGraphSuggested: 0, + llmSkillsCreated: 0, + llmBatchSubmitted: requests.length, + }; } private async getLastRun(organizationId: string): Promise { const row = await this.prisma.orgSettings.findUnique({ - where: { organizationId_key: { organizationId, key: 'kg_llm_auto_last' } }, + where: { organizationId_key: { organizationId, key: "kg_llm_auto_last" } }, select: { value: true }, }); const t = row ? parseInt(row.value, 10) : NaN; @@ -332,16 +378,13 @@ export class KgCronService { private async setLastRun(organizationId: string, ts: number): Promise { const value = String(ts); await this.prisma.orgSettings.upsert({ - where: { organizationId_key: { organizationId, key: 'kg_llm_auto_last' } }, - create: { organizationId, key: 'kg_llm_auto_last', value }, + where: { organizationId_key: { organizationId, key: "kg_llm_auto_last" } }, + create: { organizationId, key: "kg_llm_auto_last", value }, update: { value }, }); } - private async hasNewIntentsSince( - organizationId: string, - since: number | null, - ): Promise { + private async hasNewIntentsSince(organizationId: string, since: number | null): Promise { const n = await this.prisma.toolInvocation.count({ where: { organizationId, @@ -354,7 +397,7 @@ export class KgCronService { /** Drop hashed identifier rows older than the TTL. */ private async pruneValueSeen(): Promise { - const days = intEnv('KG_VALUE_TTL_DAYS', 30); + const days = intEnv("KG_VALUE_TTL_DAYS", 30); if (days <= 0) return 0; const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000); const { count } = await this.prisma.kgValueSeen.deleteMany({ @@ -368,49 +411,150 @@ export class KgCronService { * batches so the table is never locked for long. Up to TRIM_MAX_BATCHES * batches per run; the next run continues where this one stopped. */ - async trimOldPayloads(): Promise { - const days = intEnv('INVOCATION_PAYLOAD_RETENTION_DAYS', 14); - if (days <= 0) return 0; - const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000); - const batchSize = intEnv('INVOCATION_TRIM_BATCH', 5000); - const maxBatches = intEnv('INVOCATION_TRIM_MAX_BATCHES', 40); - let total = 0; + private async trimPayloadsForScope( + cutoff: Date, + batchSize: number, + maxBatches: number, + organizationId?: string, + excludedOrgIds: string[] = [], + ): Promise { + let trimmed = 0; for (let i = 0; i < maxBatches; i++) { - const updated = await this.prisma.$executeRaw` - UPDATE tool_invocations AS t SET - output = CASE WHEN pg_column_size(t.output) > 2048 - THEN jsonb_build_object('_amcp_truncated', - jsonb_build_object('originalBytes', octet_length(t.output::text), 'trimmed', 'age'), - 'excerpt', left(t.output::text, 1000)) - ELSE t.output END, - input = CASE WHEN pg_column_size(t.input) > 8192 - THEN jsonb_build_object('_amcp_truncated', - jsonb_build_object('originalBytes', octet_length(t.input::text), 'trimmed', 'age'), - 'excerpt', left(t.input::text, 1000)) - ELSE t.input END - WHERE t.id IN ( - SELECT id FROM tool_invocations - WHERE created_at < ${cutoff} - AND (pg_column_size(output) > 2048 OR pg_column_size(input) > 8192) - LIMIT ${batchSize} - )`; - total += updated; + const updated = organizationId + ? await this.prisma.$executeRaw` + UPDATE tool_invocations AS t SET + output = CASE WHEN pg_column_size(t.output) > 2048 + THEN jsonb_build_object('_amcp_truncated', + jsonb_build_object('originalBytes', octet_length(t.output::text), 'trimmed', 'age'), + 'excerpt', left(t.output::text, 1000)) + ELSE t.output END, + input = CASE WHEN pg_column_size(t.input) > 8192 + THEN jsonb_build_object('_amcp_truncated', + jsonb_build_object('originalBytes', octet_length(t.input::text), 'trimmed', 'age'), + 'excerpt', left(t.input::text, 1000)) + ELSE t.input END + WHERE t.id IN ( + SELECT id FROM tool_invocations + WHERE organization_id = ${organizationId} + AND created_at < ${cutoff} + AND (pg_column_size(output) > 2048 OR pg_column_size(input) > 8192) + LIMIT ${batchSize} + )` + : excludedOrgIds.length > 0 + ? await this.prisma.$executeRaw` + UPDATE tool_invocations AS t SET + output = CASE WHEN pg_column_size(t.output) > 2048 + THEN jsonb_build_object('_amcp_truncated', + jsonb_build_object('originalBytes', octet_length(t.output::text), 'trimmed', 'age'), + 'excerpt', left(t.output::text, 1000)) + ELSE t.output END, + input = CASE WHEN pg_column_size(t.input) > 8192 + THEN jsonb_build_object('_amcp_truncated', + jsonb_build_object('originalBytes', octet_length(t.input::text), 'trimmed', 'age'), + 'excerpt', left(t.input::text, 1000)) + ELSE t.input END + WHERE t.id IN ( + SELECT id FROM tool_invocations + WHERE created_at < ${cutoff} + AND NOT (organization_id = ANY(${excludedOrgIds}::text[])) + AND (pg_column_size(output) > 2048 OR pg_column_size(input) > 8192) + LIMIT ${batchSize} + )` + : await this.prisma.$executeRaw` + UPDATE tool_invocations AS t SET + output = CASE WHEN pg_column_size(t.output) > 2048 + THEN jsonb_build_object('_amcp_truncated', + jsonb_build_object('originalBytes', octet_length(t.output::text), 'trimmed', 'age'), + 'excerpt', left(t.output::text, 1000)) + ELSE t.output END, + input = CASE WHEN pg_column_size(t.input) > 8192 + THEN jsonb_build_object('_amcp_truncated', + jsonb_build_object('originalBytes', octet_length(t.input::text), 'trimmed', 'age'), + 'excerpt', left(t.input::text, 1000)) + ELSE t.input END + WHERE t.id IN ( + SELECT id FROM tool_invocations + WHERE created_at < ${cutoff} + AND (pg_column_size(output) > 2048 OR pg_column_size(input) > 8192) + LIMIT ${batchSize} + )`; + trimmed += updated; if (updated < batchSize) break; await new Promise((resolve) => setImmediate(resolve)); } - if (total > 0) this.logger.log(`Payload trim: shortened ${total} tool_invocations older than ${days}d.`); + return trimmed; + } + + async trimOldPayloads(): Promise { + const defaultDays = intEnv("INVOCATION_PAYLOAD_RETENTION_DAYS", 14); + const batchSize = intEnv("INVOCATION_TRIM_BATCH", 5000); + const maxBatches = intEnv("INVOCATION_TRIM_MAX_BATCHES", 40); + const overrides = await this.getOrgOverrides( + KgCronService.PAYLOAD_RETENTION_DAYS_KEY, + defaultDays, + ); + const overriddenOrgIds = overrides.map((o) => o.organizationId); + + let total = 0; + for (const override of overrides) { + if (override.days <= 0) continue; + const orgCutoff = new Date(Date.now() - override.days * 24 * 60 * 60 * 1000); + total += await this.trimPayloadsForScope( + orgCutoff, + batchSize, + maxBatches, + override.organizationId, + ); + } + + if (defaultDays > 0) { + const defaultCutoff = new Date(Date.now() - defaultDays * 24 * 60 * 60 * 1000); + total += await this.trimPayloadsForScope( + defaultCutoff, + batchSize, + maxBatches, + undefined, + overriddenOrgIds, + ); + } + + if (total > 0) { + this.logger.log( + `Payload trim: shortened ${total} tool_invocations (default ${defaultDays}d).`, + ); + } return total; } - /** Delete audit rows older than the retention window (cloud-only). */ private async retention(): Promise { - const days = intEnv('INVOCATION_RETENTION_DAYS', 90); - if (days <= 0) return 0; - const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000); - const { count } = await this.prisma.toolInvocation.deleteMany({ - where: { createdAt: { lt: cutoff } }, - }); - if (count > 0) this.logger.log(`Retention: pruned ${count} tool_invocations older than ${days}d.`); - return count; + const defaultDays = intEnv("INVOCATION_RETENTION_DAYS", 90); + const overrides = await this.getOrgOverrides(KgCronService.RETENTION_DAYS_KEY, defaultDays); + const overriddenOrgIds = overrides.map((o) => o.organizationId); + + let total = 0; + for (const override of overrides) { + if (override.days <= 0) continue; + const orgCutoff = new Date(Date.now() - override.days * 24 * 60 * 60 * 1000); + const { count } = await this.prisma.toolInvocation.deleteMany({ + where: { organizationId: override.organizationId, createdAt: { lt: orgCutoff } }, + }); + total += count; + } + + if (defaultDays > 0) { + const defaultCutoff = new Date(Date.now() - defaultDays * 24 * 60 * 60 * 1000); + const { count } = await this.prisma.toolInvocation.deleteMany({ + where: { + createdAt: { lt: defaultCutoff }, + ...(overriddenOrgIds.length > 0 ? { organizationId: { notIn: overriddenOrgIds } } : {}), + }, + }); + total += count; + } + + if (total > 0) { + this.logger.log(`Retention: pruned ${total} tool_invocations (default ${defaultDays}d).`); + } + return total; } }