Skip to content

refactor(task): Task system v4 — Binder-based dependency declaration and declarative Module registration - #1116

Merged
kyasbal merged 38 commits into
mainfrom
epic/task-system-v4
Oct 6, 2026
Merged

kyasbal merged 38 commits into
mainfrom
epic/task-system-v4

Conversation

@kyasbal

@kyasbal kyasbal commented Oct 6, 2026

Copy link
Copy Markdown
Member

Summary

Merges epic/task-system-v4 into main, completing Task System v4 (Closes #1063).

Key Changes

  1. Binder-based Task Definition API (coretask.Define & coretask.Binder):

    • Co-locates dependency declaration (coretask.Use, coretask.UseOptional, coretask.UseTag, coretask.After) with typed input handle creation (Input[T], OptionalInput[T]) inside a single bind(b *coretask.Binder) closure.
    • Replaces untyped UntypedTask.Dependencies() and context-key lookups (coretask.GetTaskResult, coretask.GetOptionalTaskResult) with structured UntypedTask.Inputs() []InputSpec and handle-based Input[T].Get(ctx).
    • Enforces active-task ownership checks on Input.Get(ctx) and OptionalInput.Get(ctx) and validates dependency result types during task graph resolution.
    • Automatically merges duplicate input declarations on the same Binder (promoting ordering/optional to required when combined with Use).
  2. Declarative Module Registration (coreinspection.Module):

    • Replaces imperative RegisterTasks functions and ScopedTaskRegistry with declarative coreinspection.Module values (Name, Scope, InspectionTypes, Tasks, SubModules) in each pkg/task/inspection/**/impl/module.go.
    • Unifies inspection-type scoping onto Module.Scope and updates scripts/backend-codegen to register modules via inspectionServer.AddModules.
  3. Domain & Form Task Factories:

    • Migrates all inspection task helpers (DefineInspectionTask, DefineCachedTask, DefineInventoryTask, DefineLogFilterTask, DefineLogGrouperTask, DefineLogIngesterTask, DefineGroupedLogIngesterTask, DefineLogToTimelineMapperTask, DefineStructuredListLogEntriesTask, DefineGCPOperationLogIngesterTask, DefineManifestLogToTimelineMapper) and form factories (DefineTextForm, DefineCheckboxForm, DefineSetForm, DefineFileForm) to the Define* + Binder pattern.
  4. Input-Validating Test Harness (tasktest.Run & inspectiontest.Run):

    • Validates tasktest.Given and tasktest.GivenTag test inputs against the task's declared Inputs() (catching undeclared inputs, scope mismatches, and unprovided required inputs in unit tests).
    • Updates documentation (docs/en/task-system/*, docs/ja/task-system/*), READMEs, and agent skills/rules to reflect the v4 API.
…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
…tories (#1074)

* feat(backend): add Binder-based log mapper, ingester, and grouper factories

Refs #1063

* refactor(backend): drop redundant context check in ingestLogs

hasErr already returns true when the context is cancelled, and ingestLogs
returns ctx.Err() after the pool finishes.

Refs #1063
… log ingester factories (#1075)

* feat(backend): add Binder-based gcpcommon log query and GCP operation log ingester factories

Refs #1063

* test(backend): avoid deprecated MustForceConvertSRGBHex in GCP operation ingester test

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
)

* refactor(backend): migrate k8snode to Binder factories and Module

* fix(backend): return the worker error from podSandboxIDDiscoveryTask
…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
… 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
…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
…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
@kyasbal
kyasbal requested review from RyuSA and jyane as code owners October 6, 2026 04:47
@kyasbal kyasbal added the area:backend-core Core backend frameworks, DAG task runner, and server API label Oct 6, 2026
@kyasbal
kyasbal requested a review from kkuchima as a code owner October 6, 2026 04:47
@kyasbal kyasbal added area:backend-parser Log parsers and log timeline mapper tasks type:refactor Code refactoring without behavioral change labels Oct 6, 2026
@kyasbal
kyasbal requested a review from renamoo as a code owner October 6, 2026 04:47
@kyasbal kyasbal added area:devenv Development environment, Makefile, and build tooling area:agent AI agent skills, rules, and prompt workflows labels Oct 6, 2026
@kyasbal
kyasbal requested a review from K53 as a code owner October 6, 2026 04:47

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pkg/core/task/define.go
Comment on lines +94 to +101
// 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))
}
}()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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)
}
Comment on lines +284 to 292
// 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
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
// 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
}
}
Comment on lines +277 to +282
// 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
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
// 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
}
}
Comment on lines +182 to +187
// 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
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
// 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
}
}
@kyasbal
kyasbal added this pull request to the merge queue Oct 6, 2026
Merged via the queue into main with commit 1c7149a Oct 6, 2026
21 checks passed
@kyasbal
kyasbal deleted the epic/task-system-v4 branch October 6, 2026 06:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent AI agent skills, rules, and prompt workflows area:backend-core Core backend frameworks, DAG task runner, and server API area:backend-parser Log parsers and log timeline mapper tasks area:devenv Development environment, Makefile, and build tooling type:refactor Code refactoring without behavioral change

1 participant