Repository navigation
refactor(task): Task system v4 — Binder-based dependency declaration and declarative Module registration - #1116
Conversation
…olution (#1064) Graph resolution now returns an error when a producer task's result type is not assignable to the result type that a dependency expects. The check covers point-to-point edges, including optional ones, and fan-in edges. Assignability is used because task results are read with a type assertion, so any or interface-typed dependencies still accept concrete producers. The taskrecord replay stub was a Task[any] that returned a value of the recorded type. It now reports the recorded task's result type so that the new check accepts it as the original producer. Refs #1063
* feat(backend): add Binder-based task definition API Add coretask.Define, Binder, Use/UseOptional/UseTag/After and typed input handles so tasks read inputs only through the handles returned by their declarations. Unused inputs surface as compile errors or govet unusedresult findings. DefinedTask exposes the declared inputs, and inspectiontaskbase.DefineInspectionTask wraps Define for inspection tasks. Legacy result getters panic inside tasks defined with Define. The legacy API remains available during the migration. Refs #1063 * chore: add license headers to new task system files * fix(backend): panic on unknown InputKind in String
) * feat(backend): add input-validating test harness for Define tasks Add tasktest.Run, Given and GivenTag, and inspectiontest.Run. They check the given values against DefinedTask.Inputs() and fail the test on missing required inputs or undeclared inputs. GivenTag supplies fan-in inputs. Refs #1063 * test(backend): use t.Context() in test harness tests Refs #1063
Add Module and Scope so impl packages can declare their inspection types, tasks, and the inspection types the tasks apply to. Nested modules add conditions to the parent scope and can only narrow it. AddModules registers modules and reports scope conflicts and duplicated IDs with the module name. Codegen registers packages with a Module variable through AddModules and the others through Register during the migration. Refs #1063
… label (#1076) * refactor(backend): remove unused NewListLogEntriesTask and query task label NewListLogEntriesTask has no production callers since all Cloud Logging parsers moved to NewStructuredListLogEntriesTask. Remove it together with ListLogEntriesTaskSetting, ListLogEntriesTaskDescription, setQueryInfo and the inspectioncore query task label that only it used, and update the khi_parser skill example to the structured factory. * refactor(backend): move remaining list log entries helpers into the structured task file Refs #1063
…k factories (#1079) * feat(backend): add Binder-based form, cached, inventory and alias task factories * refactor(backend): simplify default cached result literal * refactor(backend): define cached tasks with a key function and a cache scope
…er factories and Module (#1084) Migrate inspectioncore/impl and gcpcommon/impl from legacy task factories and Register functions to Binder-based Define factories and declarative Modules. Unexport task variables, register inspectioncore through AddModules in NewServer, and update tests to inspectiontest.Run and tasktest.Given. Part of #1063. TAG=agy
… required fields as arguments (#1085) * refactor(backend): add formtask.DefineTextForm and DefineSetForm with required fields as arguments Replace the text/set form builder Define methods (TextFormFuncs/SetFormFuncs) with standalone DefineTextForm/DefineSetForm functions. ID, priority, label and description are positional arguments; optional callbacks and settings are returned in a TextFormSpec/SetFormSpec from the bind function. Migrate inspectioncore and gcpcommon forms to them. TAG=agy * test(backend): run TestDefineTextForm_FormField cases in Run mode and assert returned values TAG=agy
…and Modules (#1088) * refactor(backend): migrate cluster type packages (gke, gkeonaws, gkeonazure, gdcbaremetal, gdcvmware) to Binder factories and Modules TAG=agy * refactor(backend): add coretask.DefineConstant for tasks returning a fixed value TAG=agy
…ages to Binder factories and Modules (#1092) TAG=agy
…dule (#1094) * refactor(backend): migrate composerairflow to Binder factories and Module TAG=agy * refactor(backend): remove unused fields of dagProcessorManagerTimelineMapper TAG=agy
…inder factories and Modules (#1096) TAG=agy
…der factories and Modules (#1097) TAG=agy
…tories and Modules (#1098) TAG=agy
…odule (#1101) refactor(backend): migrate oss/k8s to Binder factories and Module
…les (#1099) * refactor(backend): migrate csm and csmcp to Binder factories and Modules * fix(backend): report progress in csmClusterIdentifierTask * refactor(backend): add formtask.PreviousOrDefaultValue and use it in csm form
…r factories and Modules (#1104)
… factories and Modules (#1105) * refactor(backend): migrate k8scontainer and k8scontrolplane to Binder factories and Modules * perf(backend): preallocate node name slice in k8scontainer discovery task
…turedListLogEntriesTask (#1106)
…1107) * refactor(backend): remove legacy inspectiontaskbase task factories * test(backend): fold leftover mapper mock into inputPathMapper * refactor: apply naming review fixes
…tories (#1108) * refactor(backend): replace legacy form task builders with Define* factories * test(backend): cover Binder inputs and form label in DefineCheckboxForm * refactor: apply naming review fixes to formtask tests
… helpers (#1109) * refactor(backend): remove RunInspectionTask, tasktest.RunTask and dependency-value test helpers * refactor(backend): remove GetTaskResult family and TaskDependenciesContextKey * refactor(backend): remove TaskRegistry, InspectionTaskRegistry and the codegen Register fallback * refactor(backend): drop dead result-map test fallback and redundant UntypedRun forwarder * refactor(backend): rename INSPECTION_TASK_IMPL_SRCS to _DIRS and avoid shadowed bound in define_test
…ine (#1110) * refactor(backend): remove coretask.NewTask and fold TaskImpl into Define * refactor(backend): panic on unknown dependency types in dependencyKey instead of a dedicated nil check * test(backend): clarify names in Define tests now that every task is defined with Define * refactor(backend): annotate bind-time panics with the task ID in Define * test(backend): refine Define test names after review * refactor(backend): polish bind panic annotation after review
* feat(backend): merge inputs declared more than once on a Binder * docs(backend): describe InputKind as the merged kind of all declarations * refactor(backend): derive merged value kind from the merged scope on a Binder * test(backend): cover order independence and runtime effect of merged Binder inputs * test(backend): unify merged input test names, cover chained merges and spell out the merge rule * refactor(backend): derive tag kind from the merged dependency type in mergeInputSpecs
…erge DefinedTask into Task (#1112)
…1113) * docs: update task system docs and skills for Binder-based Define API * docs: specify FromActiveGraph in UseOptional rule and update index diagram count
…cs (#1114) * refactor(backend): unify lifecycle hooks and expose Connect-RPC handler options (#1069) * fix(k8scontainer): use audit timeline creation time inventory instead of querying builder state (#1086) * fix(k8scontainer): use audit timeline path inventory instead of querying builder state TAG=agy * refactor(k8saudit): replace TimelinePathInventoryTask with TimelineCreationTimeInventoryTask TAG=agy * refactor(k8saudit): split PodPhase creation time discovery into dedicated task TAG=agy * feat(k8saudit): add progress reporting and task labels to timeline creation time discovery tasks * fix(k8saudit): prevent condition timeline inversion and stale inferred creation states (#1093) * fix(k8saudit): prevent condition timeline inversion and stale inferred creation states * refactor(k8saudit): simplify hasConditionAtOrBefore fallback logic * docs: update task registration docs to Module and Scope
#1115) * refactor(inspection): unify inspection type scoping onto Module.Scope * refactor(task): rename DefineAliasTask/DefineInventoryTask, unify labelOpts, and reject ScopeAll tags * refactor(inspection): simplify StructuredLogQuerySource and invert SetFormSpec AddAll/RemoveAll flags * fix(taskrecord): use UntypedTask.ResultType for recorded input decoding * chore(inspection): remove unused ordering dependencies and minor migration remnants * docs(task): fix documentation, skill, README, and GoDoc discrepancies for v4 task API * refactor(k8saudit): bind audit log extractors with coretask.Use instead of UseOptional
There was a problem hiding this comment.
Code Review
This pull request refactors the KHI task system, transitioning from the legacy NewTask pattern to a declarative Define pattern using a Binder for input and dependency declarations. It updates task definitions, form tasks, and test files to use the new input handles and module-based registration. Feedback on these changes suggests capturing the stack trace using debug.Stack() when re-panicking in callBind to aid in debugging, and cloning returned slices using slices.Clone in several form task helper functions to prevent accidental mutations of shared slices.
| // callBind calls bind and re-panics any panic raised in it with the task ID prepended. | ||
| // Bind functions run at package initialization, where the stack trace alone rarely tells which task failed. | ||
| func callBind[T any](id taskid.TaskImplementationID[T], b *Binder, bind func(b *Binder) func(ctx context.Context) (T, error)) func(ctx context.Context) (T, error) { | ||
| defer func() { | ||
| if r := recover(); r != nil { | ||
| panic(fmt.Sprintf("task %s: %v", id, r)) | ||
| } | ||
| }() |
There was a problem hiding this comment.
Recovering and re-panicking without capturing the stack trace makes debugging panics (such as nil pointer dereferences) inside the bind function extremely difficult because the original stack trace is lost. Consider capturing and appending the stack trace using runtime/debug's debug.Stack(). Note that you will need to import "runtime/debug" in this file.
func callBind[T any](id taskid.TaskImplementationID[T], b *Binder, bind func(b *Binder) func(ctx context.Context) (T, error)) func(ctx context.Context) (T, error) {
defer func() {
if r := recover(); r != nil {
panic(fmt.Sprintf("task %s: %v\nstack trace:\n%s", id, r, string(debug.Stack())))
}
}()
return bind(b)
}| // PreviousOrConstantDefaultValue returns a SetFormDefaultValueGenerator that returns the previous values when they exist, otherwise values. | ||
| func PreviousOrConstantDefaultValue(values []string) SetFormDefaultValueGenerator { | ||
| return func(ctx context.Context, previousValues []string) ([]string, error) { | ||
| if len(previousValues) > 0 { | ||
| return previousValues, nil | ||
| } | ||
| err = formFields.SetField(field) | ||
| if err != nil { | ||
| return *new(T), fmt.Errorf("failed to configure the form metadata in task `%s`\n%v", b.id, err) | ||
| } | ||
| return convertedValue, nil | ||
| }, append(labelOpts, inspectioncore.NewFormTaskLabelOpt( | ||
| b.label, | ||
| b.description, | ||
| ))...) | ||
| return values, nil | ||
| } | ||
| } |
There was a problem hiding this comment.
Returning the shared values or previousValues slice directly from the default value generator can lead to accidental mutations if any caller or subsequent task modifies the slice elements or capacity. It is safer to return a cloned slice using slices.Clone. Note that you will need to import "slices" in this file.
| // PreviousOrConstantDefaultValue returns a SetFormDefaultValueGenerator that returns the previous values when they exist, otherwise values. | |
| func PreviousOrConstantDefaultValue(values []string) SetFormDefaultValueGenerator { | |
| return func(ctx context.Context, previousValues []string) ([]string, error) { | |
| if len(previousValues) > 0 { | |
| return previousValues, nil | |
| } | |
| err = formFields.SetField(field) | |
| if err != nil { | |
| return *new(T), fmt.Errorf("failed to configure the form metadata in task `%s`\n%v", b.id, err) | |
| } | |
| return convertedValue, nil | |
| }, append(labelOpts, inspectioncore.NewFormTaskLabelOpt( | |
| b.label, | |
| b.description, | |
| ))...) | |
| return values, nil | |
| } | |
| } | |
| // PreviousOrConstantDefaultValue returns a SetFormDefaultValueGenerator that returns the previous values when they exist, otherwise values. | |
| func PreviousOrConstantDefaultValue(values []string) SetFormDefaultValueGenerator { | |
| return func(ctx context.Context, previousValues []string) ([]string, error) { | |
| if len(previousValues) > 0 { | |
| return slices.Clone(previousValues), nil | |
| } | |
| return slices.Clone(values), nil | |
| } | |
| } |
| // ConstantOptions returns a SetFormOptionsProvider that always returns options. | ||
| func ConstantOptions(options ...inspectionmetadata.SetParameterFormFieldOptionItem) SetFormOptionsProvider { | ||
| return func(ctx context.Context, previousValues []string) ([]inspectionmetadata.SetParameterFormFieldOptionItem, error) { | ||
| return options, nil | ||
| } | ||
| } |
There was a problem hiding this comment.
Returning the shared options slice directly from the options provider can lead to accidental mutations if any caller or subsequent task modifies the slice elements. It is safer to return a cloned slice using slices.Clone. Note that you will need to import "slices" in this file.
| // ConstantOptions returns a SetFormOptionsProvider that always returns options. | |
| func ConstantOptions(options ...inspectionmetadata.SetParameterFormFieldOptionItem) SetFormOptionsProvider { | |
| return func(ctx context.Context, previousValues []string) ([]inspectionmetadata.SetParameterFormFieldOptionItem, error) { | |
| return options, nil | |
| } | |
| } | |
| // ConstantOptions returns a SetFormOptionsProvider that always returns options. | |
| func ConstantOptions(options ...inspectionmetadata.SetParameterFormFieldOptionItem) SetFormOptionsProvider { | |
| return func(ctx context.Context, previousValues []string) ([]inspectionmetadata.SetParameterFormFieldOptionItem, error) { | |
| return slices.Clone(options), nil | |
| } | |
| } |
| // ConstantSuggestions returns a suggestions provider that always returns the given suggestions. | ||
| func ConstantSuggestions(suggestions ...string) TextFormSuggestionsProvider { | ||
| return func(ctx context.Context, value string, previousValues []string) ([]string, error) { | ||
| return suggestions, nil | ||
| } | ||
| } |
There was a problem hiding this comment.
Returning the shared suggestions slice directly from the suggestions provider can lead to accidental mutations if any caller or subsequent task modifies the slice elements. It is safer to return a cloned slice using slices.Clone. Note that you will need to import "slices" in this file.
| // ConstantSuggestions returns a suggestions provider that always returns the given suggestions. | |
| func ConstantSuggestions(suggestions ...string) TextFormSuggestionsProvider { | |
| return func(ctx context.Context, value string, previousValues []string) ([]string, error) { | |
| return suggestions, nil | |
| } | |
| } | |
| // ConstantSuggestions returns a suggestions provider that always returns the given suggestions. | |
| func ConstantSuggestions(suggestions ...string) TextFormSuggestionsProvider { | |
| return func(ctx context.Context, value string, previousValues []string) ([]string, error) { | |
| return slices.Clone(suggestions), nil | |
| } | |
| } |
…QL unsafe-quoting false positive
Summary
Merges
epic/task-system-v4intomain, completing Task System v4 (Closes #1063).Key Changes
Binder-based Task Definition API (
coretask.Define&coretask.Binder):coretask.Use,coretask.UseOptional,coretask.UseTag,coretask.After) with typed input handle creation (Input[T],OptionalInput[T]) inside a singlebind(b *coretask.Binder)closure.UntypedTask.Dependencies()and context-key lookups (coretask.GetTaskResult,coretask.GetOptionalTaskResult) with structuredUntypedTask.Inputs() []InputSpecand handle-basedInput[T].Get(ctx).Input.Get(ctx)andOptionalInput.Get(ctx)and validates dependency result types during task graph resolution.Binder(promoting ordering/optional to required when combined withUse).Declarative Module Registration (
coreinspection.Module):RegisterTasksfunctions andScopedTaskRegistrywith declarativecoreinspection.Modulevalues (Name,Scope,InspectionTypes,Tasks,SubModules) in eachpkg/task/inspection/**/impl/module.go.Module.Scopeand updatesscripts/backend-codegento register modules viainspectionServer.AddModules.Domain & Form Task Factories:
DefineInspectionTask,DefineCachedTask,DefineInventoryTask,DefineLogFilterTask,DefineLogGrouperTask,DefineLogIngesterTask,DefineGroupedLogIngesterTask,DefineLogToTimelineMapperTask,DefineStructuredListLogEntriesTask,DefineGCPOperationLogIngesterTask,DefineManifestLogToTimelineMapper) and form factories (DefineTextForm,DefineCheckboxForm,DefineSetForm,DefineFileForm) to theDefine*+Binderpattern.Input-Validating Test Harness (
tasktest.Run&inspectiontest.Run):tasktest.Givenandtasktest.GivenTagtest inputs against the task's declaredInputs()(catching undeclared inputs, scope mismatches, and unprovided required inputs in unit tests).docs/en/task-system/*,docs/ja/task-system/*), READMEs, and agent skills/rules to reflect the v4 API.