Skip to content

refactor(backend): unify lifecycle hooks and expose Connect-RPC handler options - #1069

Merged
kyasbal merged 1 commit into
GoogleCloudPlatform:mainfrom
kyasbal:push-nknulsttplxw
Sep 30, 2026
Merged

kyasbal merged 1 commit into
GoogleCloudPlatform:mainfrom
kyasbal:push-nknulsttplxw

Conversation

@kyasbal

@kyasbal kyasbal commented Sep 30, 2026

Copy link
Copy Markdown
Member

Background & Problem

KHI previously maintained a legacy global pkg/lifecycle callback registry alongside the pkg/core/init initializer framework and InspectionInterceptor chain. Having two parallel lifecycle mechanisms complicated extension points and created three limitations for custom initializers and interceptors:

  1. Unfinalized Metadata in Inspection Interceptors: In InspectionTaskRunner.Run, progress phase transitions (MarkDone, MarkError, MarkCancelled) were executed in a goroutine after the InspectionInterceptor chain had already returned. As a result, interceptors wrapping next(ctx) observed TaskPhaseRunning instead of the finalized terminal phase.
  2. No Shared Connect-RPC Handler Options in InitContext: While Gin middleware could be attached to GinEngineKey, all Connect-RPC service initializers under pkg/core/init/default/ instantiated apiv1connect.New*ServiceHandler(srv) without connect.HandlerOption arguments, preventing custom initializers from registering typed Connect-RPC interceptors across services.
  3. Redundant Legacy Lifecycle Callbacks: pkg/lifecycle duplicated lifecycle hooks already provided by InitContext.OnInit, InitContext.OnRun, InitContext.OnTerminate, and InspectionTaskServer.AddInspectionInterceptor.

Solution Approach

  1. Finalize Progress Inside the Innermost runFunc: Move progress.MarkCancelled(), progress.MarkError(), and progress.MarkDone() inside the innermost runFunc of InspectionTaskRunner.Run before returning to the InspectionInterceptor chain, and remove the duplicate SerializerTaskID result size lookup (as HeaderMetadata.FileSize is already populated by SerializeTask during task graph execution).
  2. Expose Connect-RPC Handler Options in defaultinit: Add ConnectHandlerOptionsKey, AddConnectHandlerOptions, and AddConnectInterceptors in pkg/core/init/default/server.go, and pass the registered options from InitContext to all 8 Connect-RPC service handler constructors in pkg/core/init/default/.
  3. Remove Legacy pkg/lifecycle: Remove pkg/lifecycle and its remaining call sites in cmd/kubernetes-history-inspector/main.go and pkg/core/inspection/runner.go, consolidating lifecycle management onto pkg/core/init and InspectionInterceptor.

Remaining Issues & Future Work

None.

@kyasbal kyasbal added type:refactor Code refactoring without behavioral change area:backend-core Core backend frameworks, DAG task runner, and server API labels Sep 30, 2026

@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 removes the legacy lifecycle package and its event notification system, refactoring the InspectionTaskRunner to handle task progress states (done, cancelled, error) directly. Additionally, it introduces support for shared Connect-RPC handler options and interceptors via InitContext, applying them to all registered Connect service handlers. Unit tests have been updated to reflect these changes. I have no further feedback to provide as no review comments were submitted.

@kyasbal
kyasbal added this pull request to the merge queue Sep 30, 2026
Merged via the queue into GoogleCloudPlatform:main with commit 56ee8e2 Sep 30, 2026
17 checks passed
@kyasbal
kyasbal deleted the push-nknulsttplxw branch September 30, 2026 12:36
kyasbal added a commit that referenced this pull request Oct 6, 2026
…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
kyasbal added a commit to kyasbal/khi that referenced this pull request Oct 7, 2026
…and declarative Module registration (GoogleCloudPlatform#1116)

* feat(backend): validate dependency result types during task graph resolution (GoogleCloudPlatform#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 GoogleCloudPlatform#1063

* feat(backend): add Binder-based task definition API (GoogleCloudPlatform#1065)

* 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 GoogleCloudPlatform#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 (GoogleCloudPlatform#1070)

* 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 GoogleCloudPlatform#1063

* test(backend): use t.Context() in test harness tests

Refs GoogleCloudPlatform#1063

* feat(backend): add declarative inspection task Modules (GoogleCloudPlatform#1071)

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 GoogleCloudPlatform#1063

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

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

Refs GoogleCloudPlatform#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 GoogleCloudPlatform#1063

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

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

Refs GoogleCloudPlatform#1063

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

Refs GoogleCloudPlatform#1063

* refactor(backend): remove unused NewListLogEntriesTask and query task label (GoogleCloudPlatform#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 GoogleCloudPlatform#1063

* fix(devenv): regenerate inspection task registration when impl packages change (GoogleCloudPlatform#1077)

* refactor(backend): migrate gkeapiaudit to Binder-based task definitions and Module (GoogleCloudPlatform#1078)

* feat(backend): add Binder-based form, cached, inventory and alias task factories (GoogleCloudPlatform#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

* refactor(backend): migrate inspectioncore and gcpcommon tasks to Binder factories and Module (GoogleCloudPlatform#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 GoogleCloudPlatform#1063.

TAG=agy

* refactor(backend): add formtask.DefineTextForm and DefineSetForm with required fields as arguments (GoogleCloudPlatform#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

* refactor(backend): migrate k8scommon tasks to Binder factories and Module (GoogleCloudPlatform#1087)

TAG=agy

* refactor(backend): migrate cluster type packages to Binder factories and Modules (GoogleCloudPlatform#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

* refactor(backend): migrate composer cluster and composerapiaudit packages to Binder factories and Modules (GoogleCloudPlatform#1092)

TAG=agy

* refactor(backend): migrate composerairflow to Binder factories and Module (GoogleCloudPlatform#1094)

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

TAG=agy

* refactor(backend): remove unused fields of dagProcessorManagerTimelineMapper

TAG=agy

* refactor(backend): migrate multicloudapiaudit and onpremapiaudit to Binder factories and Modules (GoogleCloudPlatform#1096)

TAG=agy

* refactor(backend): migrate computeapiaudit and networkapiaudit to Binder factories and Modules (GoogleCloudPlatform#1097)

TAG=agy

* refactor(backend): migrate serialport and gkeautoscaler to Binder factories and Modules (GoogleCloudPlatform#1098)

TAG=agy

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

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

* fix(backend): return the worker error from podSandboxIDDiscoveryTask

* refactor(backend): migrate oss/k8s and DefineFileForm to Binder and Module (GoogleCloudPlatform#1101)

refactor(backend): migrate oss/k8s to Binder factories and Module

* refactor(backend): migrate csm and csmcp to Binder factories and Modules (GoogleCloudPlatform#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

* refactor(backend): migrate caik8s and CAITaskSuite to Binder and Module (GoogleCloudPlatform#1102)

* refactor(backend): migrate common/k8saudit to Binder factories and Module (GoogleCloudPlatform#1103)

* refactor(backend): migrate k8sevent and googlecloud/k8saudit to Binder factories and Modules (GoogleCloudPlatform#1104)

* refactor(backend): migrate k8scontainer and k8scontrolplane to Binder factories and Modules (GoogleCloudPlatform#1105)

* refactor(backend): migrate k8scontainer and k8scontrolplane to Binder factories and Modules

* perf(backend): preallocate node name slice in k8scontainer discovery task

* refactor(backend): remove NewGCPOperationLogIngesterTask and NewStructuredListLogEntriesTask (GoogleCloudPlatform#1106)

* refactor(backend): remove legacy inspectiontaskbase task factories (GoogleCloudPlatform#1107)

* refactor(backend): remove legacy inspectiontaskbase task factories

* test(backend): fold leftover mapper mock into inputPathMapper

* refactor: apply naming review fixes

* refactor(backend): replace legacy form task builders with Define* factories (GoogleCloudPlatform#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

* refactor(backend): remove TaskRegistry, GetTaskResult and legacy test helpers (GoogleCloudPlatform#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

* refactor(backend): remove coretask.NewTask and fold TaskImpl into Define (GoogleCloudPlatform#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 (GoogleCloudPlatform#1111)

* 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

* refactor(backend): replace UntypedTask.Dependencies with Inputs and merge DefinedTask into Task (GoogleCloudPlatform#1112)

* docs: update task system docs and skills for Binder-based Define API (GoogleCloudPlatform#1113)

* docs: update task system docs and skills for Binder-based Define API

* docs: specify FromActiveGraph in UseOptional rule and update index diagram count

* chore: merge main into epic/task-system-v4 and update registration docs (GoogleCloudPlatform#1114)

* refactor(backend): unify lifecycle hooks and expose Connect-RPC handler options (GoogleCloudPlatform#1069)

* fix(k8scontainer): use audit timeline creation time inventory instead of querying builder state (GoogleCloudPlatform#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 (GoogleCloudPlatform#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

* refactor(task): refine v4 task API and clean up pre-merge review items (GoogleCloudPlatform#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

* fix(inspectioncore): format job mode flags individually to avoid CodeQL unsafe-quoting false positive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:backend-core Core backend frameworks, DAG task runner, and server API type:refactor Code refactoring without behavioral change

1 participant