-
Notifications
You must be signed in to change notification settings - Fork 8.5k
[Streams][SigEvents] Add background task for significant events query generation #248608
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
ef2e0bf
feat(sigevents queries): add sig events queries task
cesco-f 3cc5133
feat(split): split _task and _status endpoints
cesco-f 6b49c6c
fix(cr): code review
cesco-f f7f5149
Changes from yarn openapi:bundle
kibanamachine 66ae75c
Merge branch 'main' into sig-events-queries-task
cesco-f 4140fed
Changes from make api-docs
kibanamachine 08e73b4
Changes from node scripts/lint_ts_projects --fix
kibanamachine 32a8351
Changes from node scripts/regenerate_moon_projects.js --update
kibanamachine 93fb7d2
fix(generate endpoint): bring back generate endpoint
cesco-f de2229b
Changes from yarn openapi:bundle
kibanamachine b8810cb
Changes from make api-docs
kibanamachine 26e4bb8
fix(internal): new endpoints are internal
cesco-f c8864ac
fix(description): remove description generation when generating sig e…
cesco-f 8bebf19
refactor(task status): add task status enum
cesco-f 61424af
refactor(plimit): use plimit for sigevents queries generation
cesco-f d54fcf3
refactor(internal endpoints): move internal endpoints
cesco-f 3b1cb4b
Changes from yarn openapi:bundle
kibanamachine a4978e1
fix(tokens): remove total tokens used
cesco-f f2e01e2
refactor(task status): use task status
cesco-f 8ca997f
Changes from make api-docs
kibanamachine 60a5ef7
Changes from node scripts/lint_ts_projects --fix
kibanamachine ce06b40
Changes from node scripts/regenerate_moon_projects.js --update
kibanamachine 0f4a9f5
fix(types): fix types
cesco-f 69d71fc
Merge branch 'main' into sig-events-queries-task
cesco-f dc6b4c3
fix(test): fix test
cesco-f 4f1d0ad
Merge branch 'main' into sig-events-queries-task
cesco-f 2faf0b4
fix(privilege): manage privilege for _task endpoint
cesco-f File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
180 changes: 180 additions & 0 deletions
180
...shared/streams/server/lib/tasks/task_definitions/significant_events_queries_generation.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0; you may not use this file except in compliance with the Elastic License | ||
| * 2.0. | ||
| */ | ||
|
|
||
| import type { TaskDefinitionRegistry } from '@kbn/task-manager-plugin/server'; | ||
| import { isInferenceProviderError } from '@kbn/inference-common'; | ||
| import { | ||
| TaskStatus, | ||
| getStreamTypeFromDefinition, | ||
| type SignificantEventsQueriesGenerationResult, | ||
| type System, | ||
| } from '@kbn/streams-schema'; | ||
| import pLimit from 'p-limit'; | ||
| import { formatInferenceProviderError } from '../../../routes/utils/create_connector_sse_error'; | ||
| import type { TaskContext } from '.'; | ||
| import type { TaskParams } from '../types'; | ||
| import { PromptsConfigService } from '../../saved_objects/significant_events/prompts_config_service'; | ||
| import { cancellableTask } from '../cancellable_task'; | ||
| import { generateSignificantEventDefinitions } from '../../significant_events/generate_significant_events'; | ||
|
|
||
| export interface SignificantEventsQueriesGenerationTaskParams { | ||
| connectorId: string; | ||
| start: number; | ||
| end: number; | ||
| systems?: System[]; | ||
| sampleDocsSize?: number; | ||
| } | ||
|
|
||
| export const SIGNIFICANT_EVENTS_QUERIES_GENERATION_TASK_TYPE = | ||
| 'streams_significant_events_queries_generation'; | ||
|
|
||
| export function createStreamsSignificantEventsQueriesGenerationTask(taskContext: TaskContext) { | ||
| return { | ||
| [SIGNIFICANT_EVENTS_QUERIES_GENERATION_TASK_TYPE]: { | ||
| createTaskRunner: (runContext) => { | ||
| return { | ||
| run: cancellableTask( | ||
| async () => { | ||
| if (!runContext.fakeRequest) { | ||
| throw new Error('Request is required to run this task'); | ||
| } | ||
|
|
||
| const { connectorId, start, end, systems, sampleDocsSize, _task } = runContext | ||
| .taskInstance.params as TaskParams<SignificantEventsQueriesGenerationTaskParams>; | ||
| const { stream: name } = _task; | ||
|
|
||
| const { taskClient, scopedClusterClient, streamsClient, inferenceClient, soClient } = | ||
| await taskContext.getScopedClients({ | ||
| request: runContext.fakeRequest, | ||
| }); | ||
|
|
||
| try { | ||
| const stream = await streamsClient.getStream(name); | ||
|
|
||
| const esClient = scopedClusterClient.asCurrentUser; | ||
|
|
||
| const promptsConfigService = new PromptsConfigService({ | ||
| soClient, | ||
| logger: taskContext.logger, | ||
| }); | ||
|
|
||
| const { significantEventsPromptOverride } = await promptsConfigService.getPrompt(); | ||
|
|
||
| // If no systems are passed, generate for all data | ||
| // If systems are passed, generate for each system with concurrency limit | ||
| const systemsToProcess: Array<System | undefined> = | ||
| systems && systems.length > 0 ? systems : [undefined]; | ||
|
|
||
| // Process systems with concurrency limit to avoid overwhelming the LLM provider | ||
| const CONCURRENCY_LIMIT = 3; | ||
cesco-f marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| const limiter = pLimit(CONCURRENCY_LIMIT); | ||
|
|
||
| const resultsArray = await Promise.all( | ||
| systemsToProcess.map((system) => | ||
| limiter(() => | ||
| generateSignificantEventDefinitions( | ||
| { | ||
| definition: stream, | ||
| connectorId, | ||
| start, | ||
| end, | ||
| system, | ||
| sampleDocsSize, | ||
| systemPromptOverride: significantEventsPromptOverride, | ||
| }, | ||
| { | ||
| inferenceClient, | ||
| esClient, | ||
| logger: taskContext.logger.get('significant_events_generation'), | ||
| signal: runContext.abortController.signal, | ||
| } | ||
| ) | ||
| ) | ||
| ) | ||
| ); | ||
|
|
||
| // Combine results from all parallel generations in a single pass | ||
| const combinedResults = | ||
| resultsArray.reduce<SignificantEventsQueriesGenerationResult>( | ||
| (acc, result) => { | ||
| acc.queries.push(...result.queries); | ||
| acc.tokensUsed.prompt += result.tokensUsed.prompt; | ||
| acc.tokensUsed.completion += result.tokensUsed.completion; | ||
| return acc; | ||
| }, | ||
| { queries: [], tokensUsed: { prompt: 0, completion: 0 } } | ||
| ); | ||
|
|
||
| taskContext.telemetry.trackSignificantEventsQueriesGenerated({ | ||
| count: combinedResults.queries.length, | ||
| systems_count: systems?.length ?? 0, | ||
| stream_name: stream.name, | ||
| stream_type: getStreamTypeFromDefinition(stream), | ||
| input_tokens_used: combinedResults.tokensUsed.prompt, | ||
| output_tokens_used: combinedResults.tokensUsed.completion, | ||
| }); | ||
|
|
||
| await taskClient.update< | ||
| SignificantEventsQueriesGenerationTaskParams, | ||
| SignificantEventsQueriesGenerationResult | ||
| >({ | ||
| ..._task, | ||
| status: TaskStatus.Completed, | ||
| task: { | ||
| params: { | ||
| connectorId, | ||
| start, | ||
| end, | ||
| systems, | ||
| sampleDocsSize, | ||
| }, | ||
| payload: combinedResults, | ||
| }, | ||
| }); | ||
| } catch (error) { | ||
| // Get connector info for error enrichment | ||
| const connector = await inferenceClient.getConnectorById(connectorId); | ||
|
|
||
| const errorMessage = isInferenceProviderError(error) | ||
| ? formatInferenceProviderError(error, connector) | ||
| : error.message; | ||
|
|
||
| if ( | ||
| errorMessage.includes('ERR_CANCELED') || | ||
| errorMessage.includes('Request was aborted') | ||
| ) { | ||
| return; | ||
| } | ||
|
|
||
| taskContext.logger.error( | ||
| `Task ${runContext.taskInstance.id} failed: ${errorMessage}` | ||
| ); | ||
|
|
||
| await taskClient.update<SignificantEventsQueriesGenerationTaskParams>({ | ||
| ..._task, | ||
| status: TaskStatus.Failed, | ||
| task: { | ||
| params: { | ||
| connectorId, | ||
| start, | ||
| end, | ||
| systems, | ||
| sampleDocsSize, | ||
| }, | ||
| error: errorMessage, | ||
| }, | ||
| }); | ||
| } | ||
| }, | ||
| runContext, | ||
| taskContext | ||
| ), | ||
| }; | ||
| }, | ||
| }, | ||
| } satisfies TaskDefinitionRegistry; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.