tracedb

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 15 Imported by: ? modules, 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

Overview

Package tracedb defines a zero-dependency interface, schema, and read-only SQL policy for storing and querying GPU traces and telemetry-review sessions in ClickHouse-compatible engines such as chDB.

Core lib/nvidia code imports only the Go standard library through Engine, allowing external modules (such as chdb-go/v2 adapters) to plug in without adding third-party dependencies to github.com/tmc/lib/nvidia.

Schema

SchemaDDL returns CREATE TABLE IF NOT EXISTS statements for the ClickStack OpenTelemetry tables (otel_traces, otel_logs), the telemetry-review tables (receipts, attempts, probe_cells, hypotheses, and AGENTS.ROOT), and the advise tables (advise_findings, advise_outcomes, advise_feedback). ApplySchema applies all statements to an Engine.

Backends

Subpackages provide zero-cgo backends implementing Engine and NamedEngine:

  • chdbengine: purego libchdb adapter with pinned SHA-256 verification, dedicated ClickHouse RBAC user isolation (`tracedb_ro`), ClickHouse AST classification, and a CUDA process isolation guard.
  • localengine: strictly fail-closed pure-Go fallback engine returning ErrUnsupportedLocalSQL on any unsupported ClickHouse SQL construct.

Read-Only SQL Policy

ValidateQuery enforces a strict read-only subset of ClickHouse SQL: only SELECT, DESCRIBE, and EXPLAIN ESTIMATE statements (with {name:Type} parameter placeholders) are permitted. External table functions (file, url, s3, remote, hdfs, mysql, postgresql, jdbc, odbc), mutating statements, multi-statement semicolons, and cross-database references outside the session database are rejected. RestrictedUserDDL emits ClickHouse GRANT/REVOKE and SETTINGS DDL for a least-privilege read-only user.

MCP Contract and Ingestion

RunQueryRequest, RunQueryResponse, ListDatabasesResponse, ListTablesRequest, and ListTablesResponse implement the mcp-clickhouse wire contract, including JSON string encoding for 64-bit integers outside the IEEE 754 safe integer range (±(2^53-1)) and paginated table listing. TraceSpan, ReceiptRow, AttemptRow, ProbeCellRow, HypothesisRow, BuildInsertSQL, and LoadTimeline construct and load rows into an Engine.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Index

Examples

Constants

View Source
const (
	// DefaultDatabase is the default local session database name exposed to agents.
	DefaultDatabase = "session_traces"

	// DefaultRestrictedUser is the dedicated least-privilege ClickHouse user
	// used for all read-only agent queries.
	DefaultRestrictedUser = "tracedb_ro"

	// AgentsRootTable is the ClickHouse MCP discovery table read first by agents.
	AgentsRootTable = "AGENTS.ROOT"

	// EngineChDB is the engine name reported when executing on real libchdb.
	EngineChDB = "chdb"

	// EngineLocalFallback is the engine name reported when executing on the
	// fail-closed pure-Go local fallback engine.
	EngineLocalFallback = "local_fallback"
)
View Source
const (
	// MaxSafeJSONInt is the largest integer exactly representable as an IEEE 754
	// double-precision float (2^53 - 1). Integers outside [-MaxSafeJSONInt, MaxSafeJSONInt]
	// are encoded as JSON strings in [RunQueryResponse].
	MaxSafeJSONInt = (1 << 53) - 1

	// MinSafeJSONInt is the smallest integer exactly representable as an IEEE 754
	// double-precision float (-(2^53 - 1)).
	MinSafeJSONInt = -MaxSafeJSONInt

	// DefaultPageSize is the default page size for [ListTablesRequest].
	DefaultPageSize = 50
)
View Source
const MaxNotebookLogBytes = 64 << 10

MaxNotebookLogBytes is the maximum byte length retained per attempt log.txt.

View Source
const NewRulePriorLCB = 0.25

NewRulePriorLCB is the exploration lower-confidence-bound prior assigned to rules with zero valid acted outcomes so newly introduced rules can be tried.

Variables

View Source
var ErrUnsupportedLocalSQL = errors.New("tracedb: SQL construct not supported by local_fallback engine; configure pinned libchdb for full ClickHouse SQL")

ErrUnsupportedLocalSQL is returned by the fail-closed local fallback engine when a query uses a ClickHouse SQL construct it cannot evaluate with exact ClickHouse semantics (zero silent approximation).

Functions

func AdviseFeedbackColumns

func AdviseFeedbackColumns() []string

AdviseFeedbackColumns returns the column names for advise_feedback in insert order.

func AdviseFindingColumns

func AdviseFindingColumns() []string

AdviseFindingColumns returns the column names for advise_findings in insert order.

func AdviseOutcomeColumns

func AdviseOutcomeColumns() []string

AdviseOutcomeColumns returns the column names for advise_outcomes in insert order.

func ApplySchema

func ApplySchema(ctx context.Context, eng Engine) error

ApplySchema executes every statement from SchemaDDL on eng.

func BindParams

func BindParams(query string, params map[string]Param) (string, error)

BindParams replaces ClickHouse {name:Type} parameter placeholders outside string literals, quoted identifiers, and comments with strictly type-checked, SQL-escaped literals. Raw string interpolation is never performed.

func BuildInsertSQL

func BuildInsertSQL(table string, columns []string, rows [][]any) (string, error)

BuildInsertSQL builds a ClickHouse INSERT INTO <table> (<columns>) VALUES ... statement with properly escaped literals.

func EngineName

func EngineName(eng Engine) string

EngineName returns eng's reported backend name if eng implements NamedEngine, or the empty string otherwise.

func HashQuery

func HashQuery(query string) string

HashQuery returns the canonical SHA-256 hex digest of a SQL query string.

func IsSafeIdentifier

func IsSafeIdentifier(s string) bool

IsSafeIdentifier reports whether s is a non-empty ASCII SQL identifier starting with a letter or underscore followed by letters, digits, or underscores.

func LoadAdviseFeedback

func LoadAdviseFeedback(ctx context.Context, eng Engine, feedback []AdviseFeedbackRow) error

LoadAdviseFeedback validates and inserts advise feedback rows into advise_feedback on eng.

func LoadAdviseFindings

func LoadAdviseFindings(ctx context.Context, eng Engine, findings []AdviseFindingRow) error

LoadAdviseFindings inserts advise finding rows into advise_findings on eng.

func LoadAdviseOutcomes

func LoadAdviseOutcomes(ctx context.Context, eng Engine, outcomes []AdviseOutcomeRow) error

LoadAdviseOutcomes inserts advise outcome rows into advise_outcomes on eng.

func LoadAgentsRoot

func LoadAgentsRoot(ctx context.Context, eng Engine, entries []AgentsRootRow) error

LoadAgentsRoot inserts discovery rows into `AGENTS.ROOT` on eng.

func LoadAttempts

func LoadAttempts(ctx context.Context, eng Engine, attempts []AttemptRow) error

LoadAttempts inserts attempt rows into attempts on eng.

func LoadHypotheses

func LoadHypotheses(ctx context.Context, eng Engine, hypotheses []HypothesisRow) error

LoadHypotheses inserts hypothesis rows into hypotheses on eng.

func LoadProbeCells

func LoadProbeCells(ctx context.Context, eng Engine, cells []ProbeCellRow) error

LoadProbeCells inserts probe cell rows into probe_cells on eng.

func LoadReceipts

func LoadReceipts(ctx context.Context, eng Engine, receipts []ReceiptRow) error

LoadReceipts inserts receipt rows into receipts on eng.

func LoadTimeline

func LoadTimeline(ctx context.Context, eng Engine, spans []TraceSpan) error

LoadTimeline inserts spans into otel_traces on eng in batches.

func RestrictedUserDDL

func RestrictedUserDDL(user, db string, limits ...QueryLimits) ([]string, error)

RestrictedUserDDL returns ClickHouse DDL statements that provision user as a least-privilege read-only account limited to db.

It revokes all external source grants (FILE, URL, S3, REMOTE, HDFS, MYSQL, POSTGRES, JDBC, ODBC) and CREATE TEMPORARY TABLE, grants SELECT on db.* only, and applies readonly, execution time, memory, and result limits. If limits is omitted, DefaultQueryLimits is used.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/tracedb"
)

func main() {
	stmts, err := tracedb.RestrictedUserDDL("tracedb_ro", "tracedb")
	if err != nil {
		panic(err)
	}
	fmt.Println(len(stmts))
	fmt.Println(stmts[3])
}
Output:
5
GRANT SELECT ON tracedb.* TO tracedb_ro

func SanitizeJSONValue

func SanitizeJSONValue(v any) any

SanitizeJSONValue recursively converts integers outside ±(2^53-1) into base-10 strings so JSON consumers using IEEE 754 floats do not lose precision.

func SchemaDDL

func SchemaDDL() []string

SchemaDDL returns the ClickStack OpenTelemetry, telemetry-review, and advise CREATE TABLE IF NOT EXISTS statements in creation order.

func TableNames

func TableNames() []string

TableNames returns the canonical table names created by SchemaDDL.

func TraceSpanColumns

func TraceSpanColumns() []string

TraceSpanColumns returns the column names for otel_traces in insert order.

func ValidateFeedback

func ValidateFeedback(fb AdviseFeedbackRow) error

ValidateFeedback checks that fb has a supported kind (correction, suggestion, or confusing) and carries non-empty evidence when kind is correction.

func ValidateQuery

func ValidateQuery(sql, sessionDB string) error

ValidateQuery checks that sql is a single read-only ClickHouse query allowed by the tracedb security policy for sessionDB.

Only SELECT, DESCRIBE, and EXPLAIN ESTIMATE statements (with optional {name:Type} parameter placeholders) are allowed. External table functions, mutating keywords, multi-statement semicolons, and cross-database table references outside sessionDB are rejected.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/tracedb"
)

func main() {
	fmt.Println(tracedb.ValidateQuery("SELECT SpanName FROM otel_traces WHERE run_id = {run:String}", "tracedb"))
	fmt.Println(tracedb.ValidateQuery("SELECT * FROM file('/etc/passwd')", "tracedb") != nil)
}
Output:
<nil>
true

Types

type AdviseFeedbackRow

type AdviseFeedbackRow struct {
	FeedbackID   string    `json:"feedback_id"`
	FindingID    string    `json:"finding_id"`
	RuleID       string    `json:"rule_id"`
	Model        string    `json:"model,omitempty"`
	Kind         string    `json:"kind"`
	Note         string    `json:"note"`
	EvidenceKind string    `json:"evidence_kind,omitempty"`
	EvidenceRef  string    `json:"evidence_ref,omitempty"`
	Actor        string    `json:"actor"`
	SessionID    string    `json:"session_id,omitempty"`
	ReceiptID    string    `json:"receipt_id,omitempty"`
	CreatedAt    time.Time `json:"created_at"`
}

AdviseFeedbackRow represents a single canonical row in advise_feedback.

Package tracedb (nvidia/x/obs/tracedb) owns the single canonical advise_* DDL and row schema aligned with nvidia/x/obs/advisefeedback.

func (AdviseFeedbackRow) Values

func (f AdviseFeedbackRow) Values() []any

Values returns the row values in advise_feedback insert column order.

type AdviseFindingRow

type AdviseFindingRow struct {
	FindingID      string    `json:"finding_id"`
	RuleID         string    `json:"rule_id"`
	RuleVersion    string    `json:"rule_version"`
	Model          string    `json:"model,omitempty"`
	Device         string    `json:"device"`
	Kernel         string    `json:"kernel"`
	KernelClass    string    `json:"kernel_class"`
	SourceLoc      string    `json:"source_loc"`
	CaptureDigest  string    `json:"capture_digest"`
	GenerationID   int64     `json:"generation_id,omitempty"`
	Severity       string    `json:"severity,omitempty"`
	Summary        string    `json:"summary,omitempty"`
	MetricsJSON    string    `json:"metrics_json,omitempty"`
	ThresholdsJSON string    `json:"thresholds_json,omitempty"`
	SurfacedAt     time.Time `json:"surfaced_at"`
}

AdviseFindingRow represents a single canonical row in advise_findings.

Package tracedb (nvidia/x/obs/tracedb) owns the single canonical advise_* DDL and row schema aligned with nvidia/x/obs/advisefeedback.

func (AdviseFindingRow) Values

func (f AdviseFindingRow) Values() []any

Values returns the row values in advise_findings insert column order.

type AdviseOutcomeRow

type AdviseOutcomeRow struct {
	OutcomeID    string    `json:"outcome_id,omitempty"`
	FindingID    string    `json:"finding_id"`
	RuleID       string    `json:"rule_id"`
	RuleVersion  string    `json:"rule_version"`
	Model        string    `json:"model,omitempty"`
	Device       string    `json:"device"`
	KernelClass  string    `json:"kernel_class"`
	SessionID    string    `json:"session_id,omitempty"`
	AttemptID    string    `json:"attempt_id"`
	GenerationID int64     `json:"generation_id,omitempty"`
	ReceiptID    string    `json:"receipt_id"`
	Verdict      string    `json:"verdict"`
	Gain         float64   `json:"gain"`
	ParityPassed bool      `json:"parity_passed"`
	ScorerUID    string    `json:"scorer_uid,omitempty"`
	RecordedAt   time.Time `json:"recorded_at"`
}

AdviseOutcomeRow represents a single canonical row in advise_outcomes.

Gain is the positive fractional speedup ((baseline - candidate) / baseline, e.g. +0.062 = 6.2% speedup; negative values indicate regression), matching nvidia/x/obs/advisefeedback's canonical gain sign and unit.

func (AdviseOutcomeRow) Values

func (o AdviseOutcomeRow) Values() []any

Values returns the row values in advise_outcomes insert column order.

type AdviseRuleStats

type AdviseRuleStats struct {
	RuleID             string  `json:"rule_id"`
	RuleVersion        string  `json:"rule_version"`
	Device             string  `json:"device"`
	KernelClass        string  `json:"kernel_class"`
	Surfaced           int     `json:"surfaced"`
	Acted              int     `json:"acted"`
	Helped             int     `json:"helped"`
	NoEffect           int     `json:"no_effect"`
	Hurt               int     `json:"hurt"`
	Invalid            int     `json:"invalid"`
	Corrections        int     `json:"corrections"`
	MedianVerifiedGain float64 `json:"median_verified_gain"`
	HelpLCB            float64 `json:"help_lcb"`
	ExpectedGain       float64 `json:"expected_gain"`
}

AdviseRuleStats summarizes empirical performance of an advice rule scoped by rule version, device, and kernel class.

func ComputeRuleStats

func ComputeRuleStats(
	findings []AdviseFindingRow,
	outcomes []AdviseOutcomeRow,
	feedback []AdviseFeedbackRow,
) []AdviseRuleStats

ComputeRuleStats aggregates findings, verified outcomes, and feedback into per-(rule, version, device, kernel_class) statistics with Wilson lower confidence bounds and an exploration prior for unmeasured rules.

type AgentsRootRow

type AgentsRootRow struct {
	RunID               string
	GenerationID        string
	ServingGenerationID string
	EventID             string
	RunKind             string
	Eligible            bool
	IneligibleReason    string
	Warm                bool
	ProfilerOn          bool
	SampleCount         uint64
	BinarySHA256        string
	ConfigSHA256        string
	WorkloadSHA256      string
	TraceSHA256         string
	EnvSHA256           string
	ArtifactSHA256      string
	WallStartNs         int64
	WallEndNs           int64
	MonoStartNs         int64
	MonoEndNs           int64
	StageTimingsMonoNs  map[string]int64
	StageTimingsWallNs  map[string]int64
	RootPath            string
	Summary             string
}

AgentsRootRow represents a discovery entry in `AGENTS.ROOT`.

func AgentsRootCatalogRows

func AgentsRootCatalogRows(db string) []AgentsRootRow

AgentsRootCatalogRows returns canonical discovery rows for [AGENTS.ROOT] describing every table in TableCatalog, including the advise tables.

func (AgentsRootRow) Values

func (a AgentsRootRow) Values() []any

Values returns the row values in `AGENTS.ROOT` insert column order.

type AttemptOutcome

type AttemptOutcome struct {
	FindingID    string  `json:"finding_id"`
	RuleID       string  `json:"rule_id,omitempty"`
	Outcome      string  `json:"outcome"`
	VerifiedGain float64 `json:"verified_gain,omitempty"`
}

AttemptOutcome records the verified outcome of an advice finding acted on in an attempt.

type AttemptResult

type AttemptResult struct {
	GenerationID    string             `json:"generation_id"`
	Status          string             `json:"status"` // ok|compile_error|test_failed|reverted
	ParityMatched   bool               `json:"parity_matched"`
	ParityAttempted bool               `json:"parity_attempted"`
	Timings         map[string]float64 `json:"timings,omitempty"`
	Stages          map[string]int64   `json:"stages,omitempty"`
	ReceiptID       string             `json:"receipt_id,omitempty"`
	ActsOn          []string           `json:"acts_on,omitempty"`
	Outcomes        []AttemptOutcome   `json:"outcomes,omitempty"`
}

AttemptResult holds the structured evaluation stored in attempts/NNN/result.json.

type AttemptRow

type AttemptRow struct {
	RunID               string
	GenerationID        string
	ServingGenerationID string
	EventID             string
	AttemptIndex        uint32
	RunKind             string
	Eligible            bool
	IneligibleReason    string
	Warm                bool
	ProfilerOn          bool
	SampleCount         uint64
	Status              string
	WallStartNs         int64
	WallEndNs           int64
	MonoStartNs         int64
	MonoEndNs           int64
	StageTimingsMonoNs  map[string]int64
	StageTimingsWallNs  map[string]int64
	Metrics             map[string]float64
	ErrorMessage        string
}

AttemptRow represents a single run attempt row in attempts.

func (AttemptRow) Values

func (a AttemptRow) Values() []any

Values returns the row values in attempts insert column order.

type AuditSink

type AuditSink interface {
	RecordQueryAudit(rec QueryAudit)
}

AuditSink receives QueryAudit records emitted by RunQueryWithAudit.

type BaseEnv

type BaseEnv struct {
	Commit      string `json:"commit"`
	ImageDigest string `json:"image_digest"`
	Profile     string `json:"profile"`
	CUDACompat  string `json:"cuda_compat"`
}

BaseEnv describes the immutable baseline environment a session starts from.

type Column

type Column struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

Column describes a single column in a query result or table schema.

type Engine

type Engine interface {
	// Exec executes a statement that does not return rows (such as DDL or INSERT).
	Exec(ctx context.Context, sql string) error
	// Query executes a read-only query with optional ClickHouse {name:Type} parameters.
	Query(ctx context.Context, sql string, params map[string]Param) (*Result, error)
	// Close releases resources held by the engine.
	Close() error
}

Engine is the minimal SQL execution interface implemented by trace database backends such as chDB or a ClickHouse client.

type HypothesisEntry

type HypothesisEntry struct {
	ID         string   `json:"id"`
	Revision   int      `json:"revision"`
	Claim      string   `json:"claim"`
	Prediction string   `json:"prediction"`
	Falsifier  string   `json:"falsifier"`
	Evidence   []string `json:"evidence,omitempty"`
	Verdict    string   `json:"verdict,omitempty"`
	Status     string   `json:"status"` // open|supported|refuted|abandoned
}

HypothesisEntry represents one append-only hypothesis record or revision in hypotheses.md.

type HypothesisRow

type HypothesisRow struct {
	RunID               string
	GenerationID        string
	ServingGenerationID string
	EventID             string
	HypothesisID        string
	Title               string
	Statement           string
	Status              string
	Confidence          float64
	EvidenceEventIDs    []string
	CreatedWallNs       int64
	UpdatedWallNs       int64
}

HypothesisRow represents a telemetry-review hypothesis in hypotheses.

func (HypothesisRow) Values

func (h HypothesisRow) Values() []any

Values returns the row values in hypotheses insert column order.

type InMemoryAuditLog

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

InMemoryAuditLog is a concurrency-safe AuditSink useful in servers and tests.

func (*InMemoryAuditLog) RecordQueryAudit

func (l *InMemoryAuditLog) RecordQueryAudit(rec QueryAudit)

RecordQueryAudit appends rec to the audit log.

func (*InMemoryAuditLog) Records

func (l *InMemoryAuditLog) Records() []QueryAudit

Records returns a snapshot copy of all recorded query audits.

type ListDatabasesResponse

type ListDatabasesResponse struct {
	Databases []string `json:"databases"`
}

ListDatabasesResponse is the mcp-clickhouse-compatible response for listing available databases.

type ListTablesRequest

type ListTablesRequest struct {
	Database               string `json:"database"`
	Like                   string `json:"like,omitempty"`
	NotLike                string `json:"not_like,omitempty"`
	PageToken              string `json:"page_token,omitempty"`
	PageSize               int    `json:"page_size,omitempty"`
	IncludeDetailedColumns bool   `json:"include_detailed_columns,omitempty"`
}

ListTablesRequest is the mcp-clickhouse-compatible request for listing tables with optional LIKE/NOT LIKE filtering and cursor pagination.

type ListTablesResponse

type ListTablesResponse struct {
	Tables        []TableInfo `json:"tables"`
	NextPageToken string      `json:"next_page_token,omitempty"`
	TotalTables   int         `json:"total_tables"`
}

ListTablesResponse is the mcp-clickhouse-compatible paginated table listing.

func PaginateTables

func PaginateTables(tables []TableInfo, req ListTablesRequest) (*ListTablesResponse, error)

PaginateTables filters tables according to req (Database, Like, NotLike, IncludeDetailedColumns) and returns the requested page. PageSize defaults to DefaultPageSize (50) when <= 0.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/tracedb"
)

func main() {
	tables := []tracedb.TableInfo{
		{Database: "tracedb", Name: "otel_traces"},
		{Database: "tracedb", Name: "otel_logs"},
		{Database: "tracedb", Name: "receipts"},
	}
	resp, err := tracedb.PaginateTables(tables, tracedb.ListTablesRequest{
		Database: "tracedb",
		Like:     "otel_%",
		PageSize: 1,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.TotalTables, resp.Tables[0].Name, resp.NextPageToken != "")
}
Output:
2 otel_traces true

type NamedEngine

type NamedEngine interface {
	EngineName() string
}

NamedEngine is an optional interface implemented by Engine backends to report their execution backend name (such as EngineChDB or EngineLocalFallback).

type Notebook

type Notebook struct {
	Meta       SessionMeta
	Hypotheses []HypothesisEntry
	Attempts   []NotebookAttempt
	Feedback   []AdviseFeedbackRow
	Conclusion string
	// contains filtered or unexported fields
}

Notebook is a per-session optimization notebook serializable as a txtar archive.

func NewNotebook

func NewNotebook(meta SessionMeta) *Notebook

NewNotebook creates a new empty session notebook for meta.

func ParseTxtar

func ParseTxtar(data []byte) (*Notebook, error)

ParseTxtar parses a per-session txtar archive back into a Notebook.

func (*Notebook) AddFeedback

func (n *Notebook) AddFeedback(fb AdviseFeedbackRow) error

AddFeedback validates and appends a structured feedback row to feedback.jsonl.

func (*Notebook) AddHypothesis

func (n *Notebook) AddHypothesis(h HypothesisEntry) (string, error)

AddHypothesis appends a new H<n> hypothesis entry to the notebook and returns its assigned identifier (for example "H1").

func (*Notebook) BeginAttempt

func (n *Notebook) BeginAttempt(intent, patchDiff, sourceCU string) (int, error)

BeginAttempt starts a new immutable attempt directory (attempts/NNN/) and returns its 1-based attempt number. A retry always allocates a new attempt.

func (*Notebook) Conclude

func (n *Notebook) Conclude(markdown string)

Conclude sets the session conclusion markdown (conclusion.md).

func (*Notebook) EndAttempt

func (n *Notebook) EndAttempt(
	attemptNum int,
	res AttemptResult,
	profileSummary string,
	profiles []ProfileRef,
	rawLog string,
) error

EndAttempt records the final result, profile summary, profile refs, and sanitized/capped log for attemptNum. Once finalized, an attempt is immutable and cannot be rewritten.

func (*Notebook) ExportTxtar

func (n *Notebook) ExportTxtar() ([]byte, error)

ExportTxtar serializes the notebook into the canonical per-session txtar layout.

func (*Notebook) UpdateHypothesis

func (n *Notebook) UpdateHypothesis(id string, rev HypothesisEntry) error

UpdateHypothesis appends a new revision for an existing hypothesis id. Prior entries are never edited in place.

type NotebookAttempt

type NotebookAttempt struct {
	Number         int
	Intent         string
	PatchDiff      string
	SourceCU       string
	Result         AttemptResult
	ProfileSummary string
	Profiles       []ProfileRef
	Log            string
	Finalized      bool
}

NotebookAttempt is one immutable attempt under attempts/NNN/.

type Param

type Param struct {
	Type  string `json:"type"`
	Value any    `json:"value"`
}

Param is a typed query parameter bound to a ClickHouse {name:Type} placeholder.

type ProbeCellRow

type ProbeCellRow struct {
	RunID               string
	GenerationID        string
	ServingGenerationID string
	EventID             string
	CellID              string
	ProbeName           string
	Dimensions          map[string]string
	Eligible            bool
	IneligibleReason    string
	Warm                bool
	ProfilerOn          bool
	SampleCount         uint64
	Value               float64
	Unit                string
	WallStartNs         int64
	WallEndNs           int64
	MonoStartNs         int64
	MonoEndNs           int64
}

ProbeCellRow represents a single probe matrix cell in probe_cells.

func (ProbeCellRow) Values

func (p ProbeCellRow) Values() []any

Values returns the row values in probe_cells insert column order.

type ProfileRef

type ProfileRef struct {
	Ref    string `json:"ref"`
	SHA256 string `json:"sha256"`
	Bytes  int64  `json:"bytes"`
}

ProfileRef is a content-addressed reference stored in attempts/NNN/profiles.json.

type QueryAudit

type QueryAudit struct {
	QuerySHA256  string    `json:"query_sha256"`
	Engine       string    `json:"engine,omitempty"`
	Actor        string    `json:"actor,omitempty"`
	Transport    string    `json:"transport,omitempty"`
	Tier         string    `json:"tier,omitempty"`
	Database     string    `json:"database,omitempty"`
	Rows         int       `json:"rows"`
	Bytes        int64     `json:"bytes"`
	DurationMS   float64   `json:"duration_ms"`
	Allowed      bool      `json:"allowed"`
	RejectReason string    `json:"reject_reason,omitempty"`
	At           time.Time `json:"at"`
}

QueryAudit records an audit trail entry for a query attempt (allowed or rejected).

type QueryLimits

type QueryLimits struct {
	// ReadOnly sets ClickHouse readonly mode (1 forbids SET overrides).
	ReadOnly int
	// MaxExecutionTimeSec caps query wall-clock runtime in seconds.
	MaxExecutionTimeSec int
	// MaxMemoryUsageBytes caps per-query memory usage in bytes.
	MaxMemoryUsageBytes uint64
	// MaxResultRows caps the number of returned rows.
	MaxResultRows uint64
	// MaxResultBytes caps the serialized result size in bytes.
	MaxResultBytes uint64
}

QueryLimits configures ClickHouse execution limits for read-only users and query sessions.

func DefaultQueryLimits

func DefaultQueryLimits() QueryLimits

DefaultQueryLimits returns conservative read-only execution limits suitable for interactive trace exploration.

func (QueryLimits) WithDefaults

func (l QueryLimits) WithDefaults() QueryLimits

WithDefaults fills any unset or non-positive limit fields with safe defaults.

type ReceiptRow

type ReceiptRow struct {
	RunID               string
	GenerationID        string
	ServingGenerationID string
	EventID             string
	RunKind             string
	Eligible            bool
	IneligibleReason    string
	Warm                bool
	ProfilerOn          bool
	SampleCount         uint64
	BinarySHA256        string
	ConfigSHA256        string
	WorkloadSHA256      string
	TraceSHA256         string
	EnvSHA256           string
	ArtifactSHA256      string
	WallStartNs         int64
	WallEndNs           int64
	MonoStartNs         int64
	MonoEndNs           int64
	StageTimingsMonoNs  map[string]int64
	StageTimingsWallNs  map[string]int64
	Metadata            string
}

ReceiptRow represents a telemetry-review receipt row in receipts.

func (ReceiptRow) Values

func (r ReceiptRow) Values() []any

Values returns the row values in receipts insert column order.

type ReplayAttemptReport

type ReplayAttemptReport struct {
	AttemptNumber int           `json:"attempt_number"`
	Recorded      AttemptResult `json:"recorded"`
	Replayed      AttemptResult `json:"replayed"`
	Matched       bool          `json:"matched"`
	Diff          string        `json:"diff,omitempty"`
}

ReplayAttemptReport records the comparison between recorded and replayed results for one attempt.

type ReplayReport

type ReplayReport struct {
	SessionID string                `json:"session_id"`
	Base      BaseEnv               `json:"base"`
	Attempts  []ReplayAttemptReport `json:"attempts"`
	Matched   bool                  `json:"matched"`
}

ReplayReport summarizes the outcome of replaying an entire session notebook.

func Replay

func Replay(ctx context.Context, txtarBytes []byte, runner ReplayRunner) (*ReplayReport, error)

Replay parses txtarBytes and re-applies each attempt onto the session's base environment using runner, comparing recorded and replayed results.

type ReplayRunner

type ReplayRunner interface {
	// ResetBase resets the execution workspace to the session's base environment.
	ResetBase(ctx context.Context, base BaseEnv) error
	// ApplyAndCheck applies attempt's patch or source onto base and runs checks.
	ApplyAndCheck(ctx context.Context, attempt NotebookAttempt) (AttemptResult, error)
}

ReplayRunner executes a notebook's attempts from a clean base environment.

type Result

type Result struct {
	Columns []Column `json:"columns"`
	Rows    [][]any  `json:"rows"`
}

Result holds the tabular output of an Engine.Query call.

type ReviewQueueItem

type ReviewQueueItem struct {
	Kind           string  `json:"kind"` // "high_hurt", "high_correction", or "suggestion"
	RuleID         string  `json:"rule_id"`
	RuleVersion    string  `json:"rule_version,omitempty"`
	Device         string  `json:"device,omitempty"`
	KernelClass    string  `json:"kernel_class,omitempty"`
	HurtRate       float64 `json:"hurt_rate,omitempty"`
	CorrectionRate float64 `json:"correction_rate,omitempty"`
	FeedbackID     string  `json:"feedback_id,omitempty"`
	Note           string  `json:"note,omitempty"`
	Reason         string  `json:"reason"`
}

ReviewQueueItem represents a rule or feedback candidate requiring maintainer review in the closed-loop advise workflow.

func BuildReviewQueue

func BuildReviewQueue(stats []AdviseRuleStats, feedback []AdviseFeedbackRow) []ReviewQueueItem

BuildReviewQueue returns rules with high hurt or correction rates along with operator suggestion candidates, ordered by review priority.

type RunQueryRequest

type RunQueryRequest struct {
	Query    string           `json:"query"`
	Database string           `json:"database,omitempty"`
	Params   map[string]Param `json:"params,omitempty"`
}

RunQueryRequest is the mcp-clickhouse-compatible request for executing a read-only SQL query.

type RunQueryResponse

type RunQueryResponse struct {
	Engine   string   `json:"engine,omitempty"`
	Columns  []Column `json:"columns"`
	Rows     [][]any  `json:"rows"`
	RowCount int      `json:"row_count"`
}

RunQueryResponse is the mcp-clickhouse-compatible response for a SQL query. Its RunQueryResponse.MarshalJSON method encodes any int64/uint64 values outside ±(2^53-1) as JSON strings to avoid JavaScript precision loss.

func RunQuery

func RunQuery(ctx context.Context, eng Engine, sessionDB string, req RunQueryRequest) (*RunQueryResponse, error)

RunQuery validates req.Query against ValidateQuery for sessionDB, executes it on eng, and returns a RunQueryResponse. If eng implements NamedEngine, its reported backend name is populated in RunQueryResponse.Engine.

func RunQueryWithAudit

func RunQueryWithAudit(ctx context.Context, eng Engine, sessionDB, actor string, req RunQueryRequest, sink AuditSink) (*RunQueryResponse, error)

RunQueryWithAudit behaves like RunQuery and additionally records a QueryAudit entry (including the active backend EngineName) to sink when sink is non-nil.

func (RunQueryResponse) MarshalJSON

func (r RunQueryResponse) MarshalJSON() ([]byte, error)

MarshalJSON encodes r as JSON, converting any int, int64, uint, or uint64 value beyond ±(2^53-1) into a base-10 JSON string.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/tracedb"
)

func main() {
	resp := tracedb.RunQueryResponse{
		Columns:  []tracedb.Column{{Name: "id", Type: "UInt64"}},
		Rows:     [][]any{{uint64(18446744073709551615)}},
		RowCount: 1,
	}
	b, err := json.Marshal(resp)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))
}
Output:
{"columns":[{"name":"id","type":"UInt64"}],"rows":[["18446744073709551615"]],"row_count":1}

type SessionMeta

type SessionMeta struct {
	SessionID string  `json:"session_id"`
	RunID     string  `json:"run_id"`
	Actor     string  `json:"actor"`
	Goal      string  `json:"goal"`
	Base      BaseEnv `json:"base"`
	Tier      string  `json:"tier"`
}

SessionMeta holds top-level metadata stored in session.json.

type TableInfo

type TableInfo struct {
	Database string   `json:"database"`
	Name     string   `json:"name"`
	Engine   string   `json:"engine,omitempty"`
	Comment  string   `json:"comment,omitempty"`
	Columns  []Column `json:"columns,omitempty"`
}

TableInfo describes a table returned by ListTablesResponse.

func TableCatalog

func TableCatalog(db string) []TableInfo

TableCatalog returns TableInfo metadata (including detailed column schemas) for all canonical tables in db (defaults to DefaultDatabase when empty).

type TraceSpan

type TraceSpan struct {
	Timestamp          time.Time
	TraceID            string
	SpanID             string
	ParentSpanID       string
	TraceState         string
	SpanName           string
	SpanKind           string
	ServiceName        string
	ResourceAttributes map[string]string
	ScopeName          string
	ScopeVersion       string
	SpanAttributes     map[string]string
	DurationNs         int64
	StatusCode         string
	StatusMessage      string
	RunID              string
	GenerationID       string
}

TraceSpan represents a single OpenTelemetry span row in otel_traces.

func (TraceSpan) Values

func (s TraceSpan) Values() []any

Values returns the row values in [otel_traces] insert column order.

Directories

Path Synopsis
Package chdbengine provides an isolated, zero-cgo purego adapter for libchdb (in-process ClickHouse) with pinned SHA-256 library verification, dedicated restricted ClickHouse RBAC user isolation (`tracedb_ro`), ClickHouse C++ AST classification, and a hard CUDA process isolation guard.
Package chdbengine provides an isolated, zero-cgo purego adapter for libchdb (in-process ClickHouse) with pinned SHA-256 library verification, dedicated restricted ClickHouse RBAC user isolation (`tracedb_ro`), ClickHouse C++ AST classification, and a hard CUDA process isolation guard.
Package localengine provides a strictly fail-closed, zero-cgo, pure-Go fallback tracedb.Engine backed by JSONL files (or in-memory storage).
Package localengine provides a strictly fail-closed, zero-cgo, pure-Go fallback tracedb.Engine backed by JSONL files (or in-memory storage).

Jump to

Keyboard shortcuts

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