workbench

package
v0.61.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 35 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// DefaultMaxLogTimelines is the default maximum number of linked timelines returned by SearchLogs.
	DefaultMaxLogTimelines = 20
	// DefaultMaxSampleLogs is the default maximum number of sample logs returned by SearchLogs.
	DefaultMaxSampleLogs = 20
)
View Source
const DefaultMaxTimelineNodes = 200

DefaultMaxTimelineNodes is the default maximum number of timeline nodes returned by SearchTimelines.

View Source
const (
	// RuleIDLogExistence identifies the validation rule that checks whether inline code spans exist in the inspection logs.
	RuleIDLogExistence = "log-existence"
)

Variables

View Source
var (
	// ErrWorkbenchNotFound indicates that the requested inspection is not loaded, either because it was never opened or because it was evicted.
	ErrWorkbenchNotFound = errors.New("workbench not found or evicted")
	// ErrWorkbenchClosed indicates that the requested workbench has been closed.
	ErrWorkbenchClosed = errors.New("workbench has been closed")
	// ErrInspectionNotFound indicates that no inspection exists for the requested inspection ID.
	ErrInspectionNotFound = errors.New("inspection not found")
)
View Source
var (
	// ErrTimelineNotFound indicates that the requested timeline ID does not exist in the search index.
	ErrTimelineNotFound = errors.New("timeline not found")
	// ErrLogNotFound indicates that the requested log ID does not exist in the search index.
	ErrLogNotFound = errors.New("log not found")
)
View Source
var (
	// ErrIndexFailed indicates that search index construction encountered a terminal error.
	ErrIndexFailed = errors.New("search index construction failed")
)
View Source
var ErrRevisionNotFound = errors.New("revision not found")

ErrRevisionNotFound indicates that the requested revision does not exist on the timeline.

Functions

func BuildTimelineQuery added in v0.61.0

func BuildTimelineQuery(segments []TimelineSegment) string

BuildTimelineQuery builds a CEL query matching the given timeline hierarchy path.

func FormatTimelinePath added in v0.61.0

func FormatTimelinePath(segments []TimelineSegment) string

FormatTimelinePath formats timeline segments as "[Type] Name > [Type] Name".

func ValidateFilter added in v0.61.0

func ValidateFilter(filter Filter) (string, error)

ValidateFilter validates the CEL expressions within a Filter. If invalid, it returns the offending field name and the validation error.

Types

type Accessor added in v0.61.0

type Accessor int

Accessor identifies the kind of client that accesses a workbench, so the manager can tell whether the workbench is still in use.

const (
	// AccessorBrowser is the KHI frontend running in a browser.
	AccessorBrowser Accessor = iota
	// AccessorMCP is an MCP client calling KHI tools.
	AccessorMCP
)

type AppliedFilter added in v0.61.0

type AppliedFilter struct {
	TimelineQuery               string
	TimelineExclusionQuery      string
	LogQuery                    string
	StartTime                   time.Time
	EndTime                     time.Time
	ExcludeTimelinesWithoutLogs bool
}

AppliedFilter represents the concrete filter settings after defaults and time range have been resolved.

func (AppliedFilter) ToPipelineParams added in v0.61.0

func (a AppliedFilter) ToPipelineParams() FilterPipelineParams

ToPipelineParams converts an AppliedFilter to FilterPipelineParams for execution.

type BodyChunk added in v0.61.0

type BodyChunk struct {
	// Content is the sliced body text for the current chunk.
	Content string
	// TotalBytes is the total byte length of the full body before truncation.
	TotalBytes int
	// NextByteOffset is the byte offset to pass in the next call to continue reading, or 0 when no bytes remain.
	NextByteOffset int
}

BodyChunk holds a line-boundary-truncated slice of a body string along with continuation metadata.

func (BodyChunk) Truncated added in v0.61.0

func (c BodyChunk) Truncated() bool

Truncated reports whether additional bytes remain after this chunk.

type ExcludeNoLogsFilter

type ExcludeNoLogsFilter struct {
	// contains filtered or unexported fields
}

ExcludeNoLogsFilter filters out timelines that do not directly contain any logs matching the current filter criteria.

func NewExcludeNoLogsFilter

func NewExcludeNoLogsFilter(enabled bool) *ExcludeNoLogsFilter

NewExcludeNoLogsFilter creates a new ExcludeNoLogsFilter.

func (*ExcludeNoLogsFilter) Name

func (f *ExcludeNoLogsFilter) Name() string

Name returns the display name of this filter stage.

func (*ExcludeNoLogsFilter) Process

func (f *ExcludeNoLogsFilter) Process(
	ctx context.Context,
	filterCtx *FilterContext,
	index *SearchIndex,
	report ProgressReporter,
) error

Process filters out timelines from filterCtx.TimelineIDs if enabled and if they contain zero matching logs in filterCtx.LogIDs.

type Filter added in v0.61.0

type Filter struct {
	TimelineQuery               string     `json:"timelineQuery,omitempty" jsonschema:"CEL expression to select timelines to include."`
	TimelineExclusionQuery      string     `` /* 128-byte string literal not displayed */
	LogQuery                    string     `json:"logQuery,omitempty" jsonschema:"CEL expression to filter logs."`
	StartTime                   *time.Time `json:"startTime,omitempty" jsonschema:"Inclusive start of the time range in RFC3339 format."`
	EndTime                     *time.Time `json:"endTime,omitempty" jsonschema:"Inclusive end of the time range in RFC3339 format."`
	ExcludeTimelinesWithoutLogs *bool      `json:"excludeTimelinesWithoutLogs,omitempty" jsonschema:"Whether to exclude timelines that have no logs matching the filter."`
}

Filter specifies CEL and time range filter parameters for timeline reading.

type FilterContext

type FilterContext struct {
	TimelineIDs  *roaring.Bitmap
	LogIDs       *roaring.Bitmap
	HasTimeRange bool
	StartTimeNs  int64
	EndTimeNs    int64
}

FilterContext holds the mutable sets of matching timeline and log IDs across pipeline filter stages.

func NewFilterContext

func NewFilterContext() *FilterContext

NewFilterContext initializes an empty FilterContext.

type FilterOutput added in v0.61.0

type FilterOutput struct {
	Applied     AppliedFilter
	TimelineIDs *roaring.Bitmap
	LogIDs      *roaring.Bitmap
}

FilterOutput contains the applied filter configuration and matching bitmap results.

type FilterPipelineParams

type FilterPipelineParams struct {
	TimelineQuery          string
	TimelineExclusionQuery string
	LogQuery               string
	ExcludeNoLogs          bool
	FilterStartTime        *time.Time
	FilterEndTime          *time.Time
}

FilterPipelineParams contains the query parameters for running the timeline and log filter pipeline.

type FilterVocabulary added in v0.61.0

type FilterVocabulary struct {
	// PathKeys lists the keys of path in timeline CEL, which are the lowercased timeline types.
	PathKeys []string
	// TimelineTypes lists the values of timelineType in timeline CEL.
	TimelineTypes []string
	// LogTypes lists the values of logType in log CEL.
	LogTypes []string
}

FilterVocabulary lists the values that filter CEL can match in one inspection. It holds only the types that appear in the inspection data, so agents can write filters without guessing.

type IncludeAncestorsFilter

type IncludeAncestorsFilter struct{}

IncludeAncestorsFilter expands the matching timeline set by recursively including all parent and ancestor timelines.

func NewIncludeAncestorsFilter

func NewIncludeAncestorsFilter() *IncludeAncestorsFilter

NewIncludeAncestorsFilter creates a new IncludeAncestorsFilter.

func (*IncludeAncestorsFilter) Name

func (f *IncludeAncestorsFilter) Name() string

Name returns the display name of this filter stage.

func (*IncludeAncestorsFilter) Process

func (f *IncludeAncestorsFilter) Process(
	ctx context.Context,
	filterCtx *FilterContext,
	index *SearchIndex,
	report ProgressReporter,
) error

Process recursively includes all parent timeline IDs for each timeline currently in filterCtx.TimelineIDs.

type IncludeDescendantsFilter

type IncludeDescendantsFilter struct{}

IncludeDescendantsFilter expands the matching timeline set by recursively including all child and descendant timelines.

func NewIncludeDescendantsFilter

func NewIncludeDescendantsFilter() *IncludeDescendantsFilter

NewIncludeDescendantsFilter creates a new IncludeDescendantsFilter.

func (*IncludeDescendantsFilter) Name

func (f *IncludeDescendantsFilter) Name() string

Name returns the display name of this filter stage.

func (*IncludeDescendantsFilter) Process

func (f *IncludeDescendantsFilter) Process(
	ctx context.Context,
	filterCtx *FilterContext,
	index *SearchIndex,
	report ProgressReporter,
) error

Process recursively includes all descendant timeline IDs for each timeline currently in filterCtx.TimelineIDs.

type IndexProgressEvent

type IndexProgressEvent struct {
	InspectionID       string
	State              IndexState
	ProgressPercentage float64
	Message            string
	Err                error
}

IndexProgressEvent encapsulates an index progress notification broadcast to subscribers.

type IndexState

type IndexState int

IndexState represents the lifecycle phase of the search index construction.

const (
	// IndexStateNotStarted indicates that index construction has not started.
	IndexStateNotStarted IndexState = iota
	// IndexStateBuilding indicates that the search index is actively being generated.
	IndexStateBuilding
	// IndexStateReady indicates that the search index is fully built and queryable.
	IndexStateReady
	// IndexStateFailed indicates that search index construction failed.
	IndexStateFailed
)

type IndexedLog

type IndexedLog = cel.LogData

IndexedLog is an alias for cel.LogData.

type IndexedTimeline

type IndexedTimeline = cel.TimelineData

IndexedTimeline is an alias for cel.TimelineData.

type InspectionIndexManager

type InspectionIndexManager struct {
	// contains filtered or unexported fields
}

InspectionIndexManager coordinates persistent disk caching, memory caching, and background generation of TrigramIndex instances.

func NewInspectionIndexManager

func NewInspectionIndexManager(inspectionServer *coreinspection.InspectionTaskServer, dataDir string) *InspectionIndexManager

NewInspectionIndexManager creates an InspectionIndexManager.

func (*InspectionIndexManager) DeleteIndex

func (m *InspectionIndexManager) DeleteIndex(inspectionID string)

DeleteIndex evicts the TrigramIndex from memory cache and removes its disk file.

func (*InspectionIndexManager) GetTrigramIndex

func (m *InspectionIndexManager) GetTrigramIndex(inspectionID string) (*cel.TrigramIndex, bool)

GetTrigramIndex returns the cached TrigramIndex if available in memory or fast-loaded from disk.

func (*InspectionIndexManager) IndexStatus

func (m *InspectionIndexManager) IndexStatus(inspectionID string) (IndexState, float64, string, error)

IndexStatus returns the current index status snapshot for the given inspection ID.

func (*InspectionIndexManager) InvalidateInspectionIndex

func (m *InspectionIndexManager) InvalidateInspectionIndex(inspectionID string)

InvalidateInspectionIndex evicts the cached TrigramIndex from memory and disk for the inspection.

func (*InspectionIndexManager) StartAsyncIndexing

func (m *InspectionIndexManager) StartAsyncIndexing(ctx context.Context, inspectionID string)

StartAsyncIndexing initiates asynchronous background Trigram index construction if not already built or building.

func (*InspectionIndexManager) SubscribeIndexProgress

func (m *InspectionIndexManager) SubscribeIndexProgress(ctx context.Context, inspectionID string) (<-chan IndexProgressEvent, func())

SubscribeIndexProgress returns a channel streaming IndexProgressEvents and a cancel function.

func (*InspectionIndexManager) Wait

func (m *InspectionIndexManager) Wait()

Wait waits for all in-flight asynchronous indexing tasks to complete.

type LineChangeCount added in v0.61.0

type LineChangeCount struct {
	Added   int
	Deleted int
}

LineChangeCount holds the numbers of added and deleted lines in a diff.

type LinkedTimeline added in v0.61.0

type LinkedTimeline struct {
	TimelineID uint32
	Segments   []TimelineSegment
}

LinkedTimeline represents a timeline linked to a log entry.

type LoadHandle added in v0.61.0

type LoadHandle struct {
	// contains filtered or unexported fields
}

LoadHandle tracks one shared load of an inspection into a workbench. Every caller that requests the same inspection while it loads receives the same handle.

func (*LoadHandle) Progress added in v0.61.0

func (h *LoadHandle) Progress() LoadProgress

Progress returns the latest loading progress.

func (*LoadHandle) Wait added in v0.61.0

func (h *LoadHandle) Wait(ctx context.Context, onProgress ProgressCallback) (*Workbench, error)

Wait blocks until loading finishes or ctx is done, forwarding progress updates to onProgress. Cancelling ctx stops only this wait; loading continues for the other callers.

type LoadProgress added in v0.61.0

type LoadProgress struct {
	Stage      apiv1.OpenWorkbenchResponse_Stage
	Percentage float64
	Message    string
}

LoadProgress is a snapshot of the progress of loading an inspection into a workbench.

type LogCELFilter

type LogCELFilter struct {
	// contains filtered or unexported fields
}

LogCELFilter evaluates a CEL query against candidate logs associated with retained timelines.

func NewLogCELFilter

func NewLogCELFilter(query string) *LogCELFilter

NewLogCELFilter creates a new LogCELFilter with the specified CEL expression.

func (*LogCELFilter) Name

func (f *LogCELFilter) Name() string

Name returns the display name of this filter stage.

func (*LogCELFilter) Process

func (f *LogCELFilter) Process(
	ctx context.Context,
	filterCtx *FilterContext,
	index *SearchIndex,
	report ProgressReporter,
) error

Process gathers candidate logs from all currently matching timelines and evaluates the log CEL expression concurrently across workers.

type LogDetail added in v0.61.0

type LogDetail struct {
	LogID           uint32
	Time            time.Time
	Severity        *khifilev6.Severity
	LogType         string
	Summary         string
	LinkedTimelines []LinkedTimeline
	Body            BodyChunk
}

LogDetail contains metadata, linked timelines, and the truncated YAML body for a single log entry.

type LogExistenceRule added in v0.61.0

type LogExistenceRule struct{}

LogExistenceRule verifies that inline code spans in a Markdown report exist in the inspection logs.

func NewLogExistenceRule added in v0.61.0

func NewLogExistenceRule() *LogExistenceRule

NewLogExistenceRule creates a new LogExistenceRule.

func (*LogExistenceRule) Description added in v0.61.0

func (r *LogExistenceRule) Description() string

Description returns a short summary of the rule.

func (*LogExistenceRule) ID added in v0.61.0

func (r *LogExistenceRule) ID() string

ID returns the rule identifier.

func (*LogExistenceRule) Validate added in v0.61.0

func (r *LogExistenceRule) Validate(ctx context.Context, report string, wb *Workbench) ([]ValidationFinding, error)

Validate checks every inline code span in report against the workbench's search index and trigram index.

type LogSearchResult added in v0.61.0

type LogSearchResult struct {
	MatchedLogCount      int
	MatchedTimelineCount int
	FirstMatchTime       time.Time
	LastMatchTime        time.Time
	SeverityCounts       []SeverityCount
	Applied              AppliedFilter
	TimelineGroups       []TimelineLogGroup
	SampleLogs           []SampleLogEntry
	// FilterVocabulary lists the values that filter CEL can match in the inspection.
	FilterVocabulary FilterVocabulary
}

LogSearchResult contains the cross-timeline log search summary, linked timeline ranking, and evenly spaced sample logs.

type LogTimelineCSRIndex added in v0.58.4

type LogTimelineCSRIndex struct {
	// contains filtered or unexported fields
}

LogTimelineCSRIndex provides an in-memory reverse index mapping log IDs to timeline IDs using Compressed Sparse Row (CSR) layout. Offsets has length maxLogID + 2, and timelineIDs holds contiguous timeline IDs.

func NewLogTimelineCSRIndex added in v0.58.4

func NewLogTimelineCSRIndex(maxLogID uint32, timelines []*cel.TimelineData) *LogTimelineCSRIndex

NewLogTimelineCSRIndex builds a CSR reverse index from the provided timelines and maximum log ID.

func (*LogTimelineCSRIndex) GetTimelineIDs added in v0.58.4

func (idx *LogTimelineCSRIndex) GetTimelineIDs(logID uint32) []uint32

GetTimelineIDs retrieves all unique timeline IDs containing the specified log ID in O(1) time.

type OtherTimeline added in v0.61.0

type OtherTimeline struct {
	LinkedTimeline
	// MatchedLogCount is the number of matched logs linked to this timeline.
	MatchedLogCount int
}

OtherTimeline is a timeline other than the queried timeline that is linked to some of the matched logs.

type Pipeline

type Pipeline struct {
	// contains filtered or unexported fields
}

Pipeline executes a sequential chain of TimelineFilter stages.

func NewDefaultPipeline

func NewDefaultPipeline(params FilterPipelineParams) *Pipeline

NewDefaultPipeline creates a standard 7-stage timeline and log search pipeline matching frontend filter semantics.

func NewPipeline

func NewPipeline(filters ...TimelineFilter) *Pipeline

NewPipeline creates a new Pipeline with the specified sequence of TimelineFilter stages.

func (*Pipeline) Execute

func (p *Pipeline) Execute(
	ctx context.Context,
	index *SearchIndex,
	report ProgressReporter,
) (*apiv1.FilterResult, error)

Execute runs all registered filter stages sequentially and constructs the final FilterResult.

func (*Pipeline) ExecuteToFilterContext added in v0.61.0

func (p *Pipeline) ExecuteToFilterContext(
	ctx context.Context,
	index *SearchIndex,
	report ProgressReporter,
) (*FilterContext, error)

ExecuteToFilterContext runs all registered filter stages sequentially and returns the raw FilterContext.

type ProgressCallback

type ProgressCallback func(stage apiv1.OpenWorkbenchResponse_Stage, progressPercentage float64, message string) error

ProgressCallback receives streaming progress updates during dataset loading.

type ProgressReporter

type ProgressReporter func(stageName string, current uint32, total uint32) error

ProgressReporter is a callback invoked during filter execution to stream progress updates.

type ReportValidationResult added in v0.61.0

type ReportValidationResult struct {
	// Rules holds the summaries of all validation rules that were executed.
	Rules []ValidationRuleSummary
	// Findings lists all validation issues sorted by line number and rule ID.
	Findings []ValidationFinding
}

ReportValidationResult contains the aggregated results of running validation rules on a Markdown report.

type ResourceDiff added in v0.61.0

type ResourceDiff struct {
	TimelineID uint32
	Segments   []TimelineSegment
	Revision   ResourceRevision
	// Previous is the revision before Revision, or nil when Revision is the initial revision.
	Previous *ResourceRevision
	// Changes counts the lines over the whole diff, even when Diff is truncated.
	Changes LineChangeCount
	Diff    BodyChunk
}

ResourceDiff contains the unified diff between a revision and its previous revision.

type ResourceManifest added in v0.61.0

type ResourceManifest struct {
	TimelineID uint32
	Segments   []TimelineSegment
	Revision   ResourceRevision
	Body       BodyChunk
}

ResourceManifest contains the selected revision and its truncated manifest YAML.

type ResourceRevision added in v0.61.0

type ResourceRevision struct {
	// Index is the 0-based position of the revision among all revisions of the timeline, oldest first.
	Index     int
	Time      time.Time
	Verb      string
	State     string
	Principal string
	LogID     uint32
	// HasBody reports whether a resource manifest body was recorded for this revision.
	HasBody bool
}

ResourceRevision describes a single revision of a resource timeline without its manifest body.

type ResourceRevisionSummary added in v0.61.0

type ResourceRevisionSummary struct {
	ResourceRevision
	Changes LineChangeCount
}

ResourceRevisionSummary is a ResourceRevision with the line change counts from its previous revision.

type ResourceRevisionsQuery added in v0.61.0

type ResourceRevisionsQuery struct {
	// StartTime is the inclusive lower bound of the revision time, or nil for no bound.
	StartTime *time.Time
	// EndTime is the inclusive upper bound of the revision time, or nil for no bound.
	EndTime *time.Time
	// Offset is the number of revisions within the time range to skip.
	Offset int
	// Limit is the maximum number of revisions to return.
	Limit int
}

ResourceRevisionsQuery selects a window of revisions on a timeline.

type ResourceRevisionsResult added in v0.61.0

type ResourceRevisionsResult struct {
	TimelineID uint32
	Segments   []TimelineSegment
	// MatchedCount is the number of revisions within the time range across all windows.
	MatchedCount int
	Revisions    []ResourceRevisionSummary
}

ResourceRevisionsResult contains a window of revisions within the requested time range.

type RevisionSelector added in v0.61.0

type RevisionSelector struct {
	// contains filtered or unexported fields
}

RevisionSelector identifies a revision either by its index or by a point in time. Build it with RevisionAtIndex or RevisionAtTime. The zero value selects the revision at index 0.

func RevisionAtIndex added in v0.61.0

func RevisionAtIndex(index int) RevisionSelector

RevisionAtIndex returns a selector for the revision at the 0-based index among all revisions of the timeline.

func RevisionAtTime added in v0.61.0

func RevisionAtTime(t time.Time) RevisionSelector

RevisionAtTime returns a selector for the revision effective at t, i.e. the latest revision changed at or before t.

type SampleLogEntry added in v0.61.0

type SampleLogEntry struct {
	LogID       uint32
	Time        time.Time
	Severity    *khifilev6.Severity
	LogType     string
	Summary     string
	TimelineIDs []uint32
}

SampleLogEntry represents a single sampled log entry and its filtered linked timeline IDs.

type SearchIndex

type SearchIndex struct {
	Timelines        []*cel.TimelineData
	TimelineMap      map[uint32]*cel.TimelineData
	Logs             []cel.LogData
	InternPool       *khifilev6model.ReadonlyInternPool
	TrigramIndex     *cel.TrigramIndex
	StyleResolver    cel.StyleResolver
	LogTimelineIndex *LogTimelineCSRIndex
	// FilterVocabulary lists the timeline types and log types in the index for filter CEL.
	FilterVocabulary FilterVocabulary
	// contains filtered or unexported fields
}

SearchIndex encapsulates the indexed timelines and logs of a Workbench session.

func (*SearchIndex) GetLog

func (s *SearchIndex) GetLog(id uint32) *cel.LogData

GetLog retrieves a log entry by its 1-based log ID in O(1) time.

func (*SearchIndex) GetTimelineIDsForLog added in v0.58.4

func (s *SearchIndex) GetTimelineIDsForLog(logID uint32) []uint32

GetTimelineIDsForLog returns the timeline IDs associated with the specified log ID in O(1) time.

func (*SearchIndex) MaxTimelineID added in v0.61.0

func (s *SearchIndex) MaxTimelineID() uint32

MaxTimelineID returns the maximum timeline ID in the index, or 0 if there are no timelines.

func (*SearchIndex) TimelineSegments added in v0.61.0

func (s *SearchIndex) TimelineSegments(timelineID uint32) ([]TimelineSegment, bool)

TimelineSegments reconstructs the timeline hierarchy segments from root to the given timeline ID.

type SeverityCount added in v0.61.0

type SeverityCount struct {
	Severity *khifilev6.Severity
	Count    int
}

SeverityCount represents the number of logs with a severity defined in the style chunk of the inspection.

type TimeRangeFilter added in v0.60.1

type TimeRangeFilter struct {
	// contains filtered or unexported fields
}

TimeRangeFilter filters timelines based on whether they have activity within a specified time range.

func NewTimeRangeFilter added in v0.60.1

func NewTimeRangeFilter(startTime, endTime *time.Time) *TimeRangeFilter

NewTimeRangeFilter creates a new TimeRangeFilter. If both startTime and endTime are nil, no time range filtering is performed. If either is non-nil, any missing boundary defaults to math.MinInt64 or math.MaxInt64.

func (*TimeRangeFilter) Name added in v0.60.1

func (f *TimeRangeFilter) Name() string

Name returns the display name of this filter stage.

func (*TimeRangeFilter) Process added in v0.60.1

func (f *TimeRangeFilter) Process(
	ctx context.Context,
	filterCtx *FilterContext,
	index *SearchIndex,
	report ProgressReporter,
) error

Process evaluates timeline activity within the specified time range and populates the matching timeline IDs into filterCtx.

type TimelineCELExclusionFilter

type TimelineCELExclusionFilter struct {
	// contains filtered or unexported fields
}

TimelineCELExclusionFilter evaluates an exclusion CEL query and removes matching timelines and their descendant subtrees.

func NewTimelineCELExclusionFilter

func NewTimelineCELExclusionFilter(exclusionQuery string) *TimelineCELExclusionFilter

NewTimelineCELExclusionFilter creates a new TimelineCELExclusionFilter.

func (*TimelineCELExclusionFilter) Name

Name returns the display name of this filter stage.

func (*TimelineCELExclusionFilter) Process

func (f *TimelineCELExclusionFilter) Process(
	ctx context.Context,
	filterCtx *FilterContext,
	index *SearchIndex,
	report ProgressReporter,
) error

Process evaluates the exclusion query concurrently on all currently matching timelines and removes excluded subtrees.

type TimelineCELFilter

type TimelineCELFilter struct {
	// contains filtered or unexported fields
}

TimelineCELFilter evaluates a CEL query against each timeline in the SearchIndex.

func NewTimelineCELFilter

func NewTimelineCELFilter(query string) *TimelineCELFilter

NewTimelineCELFilter creates a new TimelineCELFilter with the specified CEL expression.

func (*TimelineCELFilter) Name

func (f *TimelineCELFilter) Name() string

Name returns the display name of this filter stage.

func (*TimelineCELFilter) Process

func (f *TimelineCELFilter) Process(
	ctx context.Context,
	filterCtx *FilterContext,
	index *SearchIndex,
	report ProgressReporter,
) error

Process compiles and evaluates the timeline CEL expression concurrently across workers, populating matching timeline IDs into filterCtx.TimelineIDs.

type TimelineFilter

type TimelineFilter interface {
	// Name returns the human-readable display name of the filter stage.
	Name() string
	// Process executes the filtering logic on the FilterContext against the SearchIndex.
	Process(ctx context.Context, filterCtx *FilterContext, index *SearchIndex, report ProgressReporter) error
}

TimelineFilter represents a single, modular filter stage in the backend timeline and log search pipeline.

type TimelineLogEntry added in v0.61.0

type TimelineLogEntry struct {
	LogID            uint32
	Time             time.Time
	Severity         *khifilev6.Severity
	LogType          string
	Summary          string
	OtherTimelineIDs []uint32
}

TimelineLogEntry represents a single log entry on a timeline along with other timeline IDs linked to it.

type TimelineLogFilter added in v0.61.0

type TimelineLogFilter struct {
	LogQuery  string     `json:"logQuery,omitempty" jsonschema:"CEL expression to filter logs."`
	StartTime *time.Time `json:"startTime,omitempty" jsonschema:"Inclusive start of the time range in RFC3339 format."`
	EndTime   *time.Time `json:"endTime,omitempty" jsonschema:"Inclusive end of the time range in RFC3339 format."`
}

TimelineLogFilter specifies log CEL and time range filter parameters for reading logs on a single timeline.

type TimelineLogGroup added in v0.61.0

type TimelineLogGroup struct {
	TimelineID      uint32
	Segments        []TimelineSegment
	MatchedLogCount int
	SeverityCounts  []SeverityCount
	FirstMatchTime  time.Time
	LastMatchTime   time.Time
}

TimelineLogGroup represents a timeline linked to matched logs, along with its per-timeline log statistics.

type TimelineLogsResult added in v0.61.0

type TimelineLogsResult struct {
	TimelineID              uint32
	Segments                []TimelineSegment
	Applied                 AppliedFilter
	TotalOtherTimelineCount int
	OtherTimelines          []OtherTimeline
	Logs                    []TimelineLogEntry
}

TimelineLogsResult contains the filtered logs for a timeline, applied filter settings, and other linked timelines.

type TimelineSegment added in v0.61.0

type TimelineSegment struct {
	Type string
	Name string
}

TimelineSegment represents a single node in a hierarchical timeline path.

type TimelineTreeNode added in v0.61.0

type TimelineTreeNode struct {
	ID            uint32
	Depth         int
	Type          string
	Name          string
	EventCount    int
	RevisionCount int
	// SeverityCounts holds the number of matched logs per severity across the timeline and its filtered descendants, from the most severe.
	SeverityCounts  []SeverityCount
	OmittedChildren int
	FirstMatchTime  time.Time
	LastMatchTime   time.Time
}

TimelineTreeNode represents a single node in the pre-order timeline hierarchy.

type TimelineTreeResult added in v0.61.0

type TimelineTreeResult struct {
	MatchedTimelineCount int
	// DirectMatchCount is the number of timelines in the tree that have matched events/revisions or are leaf matches.
	DirectMatchCount int
	// AncestorNodeCount is the number of internal ancestor nodes without their own matched events/revisions kept to form the tree.
	AncestorNodeCount int
	ReturnedNodeCount int
	MaxDepth          int
	MaxNodes          int
	Applied           AppliedFilter
	TimelineTypes     []TimelineTypeDescription
	Nodes             []TimelineTreeNode
	// FilterVocabulary lists the values that filter CEL can match in the inspection.
	FilterVocabulary FilterVocabulary
}

TimelineTreeResult contains the filtered timeline tree, summary counts, and timeline type descriptions.

type TimelineTypeDescription added in v0.61.0

type TimelineTypeDescription struct {
	Type        string
	Description string
}

TimelineTypeDescription describes a timeline type present in a TimelineTreeResult.

type UnifiedDiff added in v0.61.0

type UnifiedDiff struct {
	// Text is the unified diff including the `---` and `+++` headers, or empty when both inputs are identical.
	Text    string
	Changes LineChangeCount
}

UnifiedDiff is a unified diff text together with the line change counts over the whole diff.

type ValidationFinding added in v0.61.0

type ValidationFinding struct {
	// RuleID identifies the ValidationRule that produced this finding.
	RuleID string
	// Line is the 1-based line number in the Markdown report where the issue was found.
	Line int
	// Target is the specific token or expression that triggered the finding.
	Target string
	// Message explains why the target was flagged.
	Message string
}

ValidationFinding represents a single issue detected by a ValidationRule.

type ValidationRule added in v0.61.0

type ValidationRule interface {
	// ID returns the unique identifier of the validation rule.
	ID() string
	// Description returns a short summary of what the rule checks.
	Description() string
	// Validate inspects the Markdown report against the Workbench and returns any findings.
	Validate(ctx context.Context, report string, wb *Workbench) ([]ValidationFinding, error)
}

ValidationRule defines a modular validation check executed against a Markdown report using Workbench inspection data.

func DefaultValidationRules added in v0.61.0

func DefaultValidationRules() []ValidationRule

DefaultValidationRules returns the standard set of report validation rules.

type ValidationRuleSummary added in v0.61.0

type ValidationRuleSummary struct {
	// ID is the unique identifier of the validation rule.
	ID string
	// Description is a short summary of what the rule checks.
	Description string
	// FindingCount is the number of findings produced by this rule.
	FindingCount int
}

ValidationRuleSummary describes a validation rule executed during report validation.

type Workbench

type Workbench struct {
	// contains filtered or unexported fields
}

Workbench represents an active in-memory analysis workspace for an inspection dataset.

func NewFromReader

func NewFromReader(
	ctx context.Context,
	id string,
	inspectionID string,
	reader io.Reader,
	totalSize int64,
	onProgress ProgressCallback,
) (*Workbench, error)

NewFromReader creates and initializes a Workbench instance by parsing chunks from the given reader in parallel.

func NewWorkbench

func NewWorkbench(id string, inspectionID string) *Workbench

NewWorkbench creates a new Workbench instance.

func (*Workbench) AwaitIndex

func (w *Workbench) AwaitIndex(ctx context.Context) error

AwaitIndex blocks until the search index construction reaches a terminal state (Ready or Failed), or the context is canceled.

func (*Workbench) BuildAsyncIndexesWithProgress

func (w *Workbench) BuildAsyncIndexesWithProgress(ctx context.Context, targetIndex *SearchIndex, onProgress ProgressCallback) error

BuildAsyncIndexesWithProgress populates asynchronous search indexes (such as the trigram index) on the target SearchIndex while streaming progress updates.

func (*Workbench) BuildBaseSearchIndex

func (w *Workbench) BuildBaseSearchIndex() (*SearchIndex, error)

BuildBaseSearchIndex constructs the base in-memory SearchIndex containing timelines, logs, and hierarchy mappings.

func (*Workbench) BuildTrigramIndexWithProgress

func (w *Workbench) BuildTrigramIndexWithProgress(ctx context.Context, targetIndex *SearchIndex, onProgress ProgressCallback) (*cel.TrigramIndex, error)

BuildTrigramIndexWithProgress constructs the trigram search index from logs while streaming progress updates.

func (*Workbench) Close

func (w *Workbench) Close()

Close marks the workbench as closed and releases in-memory chunk references.

func (*Workbench) ExecuteFilter added in v0.61.0

func (w *Workbench) ExecuteFilter(ctx context.Context, filter Filter) (*FilterOutput, error)

ExecuteFilter validates and executes the filter pipeline, returning matching timeline and log IDs.

func (*Workbench) FilterJobManager

FilterJobManager returns the AsyncJobManager tracking timeline filter jobs for this workbench.

func (*Workbench) FilterTimeline

func (w *Workbench) FilterTimeline(
	ctx context.Context,
	params FilterPipelineParams,
	sendProgress func(*apiv1.FilterProgress) error,
) (*apiv1.FilterResult, error)

FilterTimeline executes the complete 7-stage filtering pipeline and streams progress updates.

func (*Workbench) GetArchitectureGraph

GetArchitectureGraph builds the Kubernetes architecture graph for the specified request.

func (*Workbench) GetLogDetail added in v0.61.0

func (w *Workbench) GetLogDetail(logID uint32, byteOffset int) (*LogDetail, error)

GetLogDetail returns the metadata, all linked timelines, and the YAML body sliced from byteOffset for a single log ID.

func (*Workbench) GetResourceDiff added in v0.61.0

func (w *Workbench) GetResourceDiff(timelineID uint32, revisionIndex, byteOffset int) (*ResourceDiff, error)

GetResourceDiff returns the unified diff from the previous revision to the revision at revisionIndex, sliced from byteOffset. The initial revision is compared against an empty manifest, so all of its lines are reported as added.

func (*Workbench) GetResourceManifest added in v0.61.0

func (w *Workbench) GetResourceManifest(timelineID uint32, selector RevisionSelector, byteOffset int, includeManagedFields bool) (*ResourceManifest, error)

GetResourceManifest returns the manifest YAML of the selected revision, sliced from byteOffset. When includeManagedFields is false, metadata.managedFields is omitted from the manifest.

func (*Workbench) GetResourceRevisions added in v0.61.0

func (w *Workbench) GetResourceRevisions(timelineID uint32, query ResourceRevisionsQuery) (*ResourceRevisionsResult, error)

GetResourceRevisions returns the revisions of a timeline within the query time range, oldest first, together with the line change counts from each previous revision. Bodies are read only for the returned window so that long revision histories stay cheap to page through.

func (*Workbench) GetTimelineIDsForLogs added in v0.58.4

func (w *Workbench) GetTimelineIDsForLogs(logIDs []uint32) (map[uint32][]uint32, error)

GetTimelineIDsForLogs retrieves the timeline IDs associated with each requested log ID. Missing or unreferenced log IDs return an empty slice.

func (*Workbench) GetTimelineLogs added in v0.61.0

func (w *Workbench) GetTimelineLogs(ctx context.Context, timelineID uint32, filter TimelineLogFilter) (*TimelineLogsResult, error)

GetTimelineLogs filters logs on the specified timeline and aggregates other timelines linked to those logs across all matched entries. OtherTimelines keeps at most maxOtherTimelines timelines with the most matched logs.

func (*Workbench) ID

func (w *Workbench) ID() string

ID returns the unique workbench identifier.

func (*Workbench) IndexStatus

func (w *Workbench) IndexStatus() (IndexState, float64, string, error)

IndexStatus returns the current index construction status snapshot.

func (*Workbench) InspectionID

func (w *Workbench) InspectionID() string

InspectionID returns the associated inspection identifier.

func (*Workbench) InspectionTimeRange added in v0.61.0

func (w *Workbench) InspectionTimeRange() (time.Time, time.Time)

InspectionTimeRange returns the inspection time range from HeaderMetadata or indexed timestamps.

func (*Workbench) IsClosed

func (w *Workbench) IsClosed() bool

IsClosed checks whether the workbench has been closed.

func (*Workbench) ReadStructYAMLs

func (w *Workbench) ReadStructYAMLs(structIDs []uint32) (map[uint32]string, error)

ReadStructYAMLs decodes the interned structs matching the given structIDs and returns a map of struct ID to YAML string representation. Missing or invalid struct IDs are skipped (best-effort resolution).

func (*Workbench) ResolveFilter added in v0.61.0

func (w *Workbench) ResolveFilter(filter Filter) AppliedFilter

ResolveFilter fills default values for time range and boolean options in Filter.

func (*Workbench) SearchIndex added in v0.58.4

func (w *Workbench) SearchIndex() *SearchIndex

SearchIndex returns the built SearchIndex for this workbench.

func (*Workbench) SearchLogs added in v0.61.0

func (w *Workbench) SearchLogs(ctx context.Context, filter Filter, maxTimelines, maxSampleLogs int) (*LogSearchResult, error)

SearchLogs filters logs and aggregates cross-timeline statistics, linked timeline rankings, and evenly spaced sample logs. If maxTimelines <= 0, DefaultMaxLogTimelines is used. If maxSampleLogs <= 0, DefaultMaxSampleLogs is used.

func (*Workbench) SearchTimelines added in v0.61.0

func (w *Workbench) SearchTimelines(ctx context.Context, filter Filter, maxDepth, maxNodes int) (*TimelineTreeResult, error)

SearchTimelines filters timelines and builds a breadth-first truncated, pre-order rendered timeline hierarchy tree. Depth is 0-based from root timelines. If maxDepth <= 0, depth is unlimited. If maxNodes <= 0, DefaultMaxTimelineNodes is used.

func (*Workbench) SetIndexManager

func (w *Workbench) SetIndexManager(im *InspectionIndexManager)

SetIndexManager sets the InspectionIndexManager used to retrieve or wait for background TrigramIndex instances.

func (*Workbench) StartAsyncIndexing

func (w *Workbench) StartAsyncIndexing(parentCtx context.Context)

StartAsyncIndexing initiates background trigram search index construction if not already started.

func (*Workbench) SubscribeIndexProgress

func (w *Workbench) SubscribeIndexProgress(ctx context.Context) (<-chan IndexProgressEvent, func())

SubscribeIndexProgress creates a subscription channel for index progress updates. The initial state event is immediately sent to the channel.

func (*Workbench) TimelineSegments added in v0.61.0

func (w *Workbench) TimelineSegments(timelineID uint32) ([]TimelineSegment, error)

TimelineSegments returns the hierarchical timeline segments for the specified timeline ID.

func (*Workbench) ValidateReport added in v0.61.0

func (w *Workbench) ValidateReport(ctx context.Context, report string, rules ...ValidationRule) (*ReportValidationResult, error)

ValidateReport executes the specified validation rules on the Markdown report against the workbench. When no rules are passed, DefaultValidationRules() is used.

type WorkbenchManager

type WorkbenchManager struct {
	// contains filtered or unexported fields
}

WorkbenchManager keeps one shared Workbench per inspection ID for the browser and MCP. Workbenches stay loaded without any time limit and are evicted only when loading another inspection would exceed the retention limit.

func NewWorkbenchManager

func NewWorkbenchManager(inspectionServer *coreinspection.InspectionTaskServer, indexManager *InspectionIndexManager, maxLoadedInspections int) *WorkbenchManager

NewWorkbenchManager creates a WorkbenchManager that keeps at most maxLoadedInspections inspections loaded, except while loads are still in progress.

func (*WorkbenchManager) Get

func (m *WorkbenchManager) Get(inspectionID string, accessor Accessor) (*Workbench, error)

Get returns the loaded workbench for the inspection and records the access. It returns ErrWorkbenchNotFound when the inspection is not loaded yet or was evicted.

func (*WorkbenchManager) Heartbeat

func (m *WorkbenchManager) Heartbeat(inspectionID string) bool

Heartbeat records that a browser is still showing the inspection and reports whether its workbench is loaded. It does not update the last access time, so a tab left open does not keep its workbench ahead of recently used ones.

func (*WorkbenchManager) Load added in v0.61.0

func (m *WorkbenchManager) Load(inspectionID string, accessor Accessor) *LoadHandle

Load returns the handle of the workbench for the inspection without blocking. It starts loading when the inspection is neither loaded nor loading, evicting other workbenches first if the retention limit is reached. Loading runs detached from any caller, so it continues after the caller returns.

func (*WorkbenchManager) MarkBrowserClosed added in v0.61.0

func (m *WorkbenchManager) MarkBrowserClosed(inspectionID string)

MarkBrowserClosed records that a browser stopped showing the inspection, which makes its workbench an eviction candidate. The workbench stays loaded because other browsers or MCP may share it. Unknown inspection IDs are ignored.

func (*WorkbenchManager) Open added in v0.61.0

func (m *WorkbenchManager) Open(ctx context.Context, inspectionID string, accessor Accessor, onProgress ProgressCallback) (*Workbench, error)

Open returns the workbench for the inspection, loading it if needed, and blocks until loading finishes or ctx is done.

func (*WorkbenchManager) OpenJobManager

OpenJobManager returns the AsyncJobManager tracking asynchronous workbench open tasks.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL