The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
implemented nested spans w attrs
ddux1590f9b23866
diff --git a/backend/app/controllers/otelcontrollers/trace_converter.go b/backend/app/controllers/otelcontrollers/trace_converter.goindex 5202a4ba..5be76c5d 100644--- a/backend/app/controllers/otelcontrollers/trace_converter.go+++ b/backend/app/controllers/otelcontrollers/trace_converter.go@@ -246,6 +246,7 @@ func convertTraces(projectId uuid.UUID, req *coltracepb.ExportTraceServiceRequesDuration: duration,RecordedAt: startTime,ParentSpanId: ptrSpanUUID(span.ParentSpanId),+ Attributes: allAttrs,})} else {// Unpromoted root span — match historical behavior and dropdiff --git a/backend/app/controllers/otelcontrollers/trace_converter_test.go b/backend/app/controllers/otelcontrollers/trace_converter_test.goindex 6d4355bb..4c49437c 100644--- a/backend/app/controllers/otelcontrollers/trace_converter_test.go+++ b/backend/app/controllers/otelcontrollers/trace_converter_test.go@@ -462,7 +462,7 @@ func TestConvertTraces_ConsumerNonRoot_BecomesTask(t *testing.T) {ScopeSpans: []*tracepb.ScopeSpans{{Spans: []*tracepb.Span{{TraceId: traceId, SpanId: consumerSpanId, ParentSpanId: producerSpanId, Name: "process job", Kind: tracepb.Span_SPAN_KIND_CONSUMER, StartTimeUnixNano: now, EndTimeUnixNano: now + 1_000_000},- {TraceId: traceId, SpanId: childSpanId, ParentSpanId: consumerSpanId, Name: "SELECT users", Kind: tracepb.Span_SPAN_KIND_INTERNAL, StartTimeUnixNano: now, EndTimeUnixNano: now + 500_000},+ {TraceId: traceId, SpanId: childSpanId, ParentSpanId: consumerSpanId, Name: "SELECT users", Kind: tracepb.Span_SPAN_KIND_INTERNAL, StartTimeUnixNano: now, EndTimeUnixNano: now + 500_000, Attributes: []*commonpb.KeyValue{strKV("db.system", "postgresql")}},},}},}},@@ -494,6 +494,9 @@ func TestConvertTraces_ConsumerNonRoot_BecomesTask(t *testing.T) {if spans[0].TraceId != wantTaskId {t.Errorf("expected child span.TraceId == task.Id %s, got %s", wantTaskId, spans[0].TraceId)}+ if spans[0].Attributes["db.system"] != "postgresql" {+ t.Errorf("expected child span attribute db.system 'postgresql', got %q", spans[0].Attributes["db.system"])+ }}func TestConvertTraces_ConsoleCommand_BecomesTask(t *testing.T) {diff --git a/backend/app/migrations/ch/0063_add_attributes_to_spans.up.sql b/backend/app/migrations/ch/0063_add_attributes_to_spans.up.sqlnew file mode 100644index 00000000..09ec2583--- /dev/null+++ b/backend/app/migrations/ch/0063_add_attributes_to_spans.up.sql@@ -0,0 +1 @@+ALTER TABLE spans ADD COLUMN attributes String DEFAULT '{}'diff --git a/backend/app/migrations/sqlite_telemetry/0010_add_attributes_to_spans.up.sql b/backend/app/migrations/sqlite_telemetry/0010_add_attributes_to_spans.up.sqlnew file mode 100644index 00000000..10683eff--- /dev/null+++ b/backend/app/migrations/sqlite_telemetry/0010_add_attributes_to_spans.up.sql@@ -0,0 +1 @@+ALTER TABLE spans ADD COLUMN attributes TEXT NOT NULL DEFAULT '{}';diff --git a/backend/app/models/span.model.go b/backend/app/models/span.model.goindex fd330a8e..ec6e7c64 100644--- a/backend/app/models/span.model.go+++ b/backend/app/models/span.model.go@@ -7,12 +7,13 @@ import ()type Span struct {- Id uuid.UUID `json:"id" ch:"id"`- TraceId uuid.UUID `json:"traceId" ch:"trace_id"`- ProjectId uuid.UUID `json:"projectId" ch:"project_id"`- Name string `json:"name" ch:"name"`- StartTime time.Time `json:"startTime" ch:"start_time"`- Duration time.Duration `json:"duration" ch:"duration"`- RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`- ParentSpanId *uuid.UUID `json:"parentSpanId,omitempty" ch:"parent_span_id"`+ Id uuid.UUID `json:"id" ch:"id"`+ TraceId uuid.UUID `json:"traceId" ch:"trace_id"`+ ProjectId uuid.UUID `json:"projectId" ch:"project_id"`+ Name string `json:"name" ch:"name"`+ StartTime time.Time `json:"startTime" ch:"start_time"`+ Duration time.Duration `json:"duration" ch:"duration"`+ RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`+ ParentSpanId *uuid.UUID `json:"parentSpanId,omitempty" ch:"parent_span_id"`+ Attributes map[string]string `json:"attributes,omitempty" ch:"attributes"`}diff --git a/backend/app/repositories/span.repository.go b/backend/app/repositories/span.repository.goindex f55ff9e4..22eebb53 100644--- a/backend/app/repositories/span.repository.go+++ b/backend/app/repositories/span.repository.go@@ -3,9 +3,11 @@package repositoriesimport (+ "context"+ "encoding/json"+"github.com/tracewayapp/traceway/backend/app/chdb""github.com/tracewayapp/traceway/backend/app/models"- "context""github.com/google/uuid")@@ -18,12 +20,18 @@ func (r *spanRepository) InsertAsync(ctx context.Context, spans []models.Span) e}batch, err := chdb.Conn.PrepareBatch(chdb.BatchCtx(),- "INSERT INTO spans (id, trace_id, project_id, name, start_time, duration, recorded_at, parent_span_id)")+ "INSERT INTO spans (id, trace_id, project_id, name, start_time, duration, recorded_at, parent_span_id, attributes)")if err != nil {return err}for _, s := range spans {+ attributesJSON := "{}"+ if len(s.Attributes) != 0 {+ if attributesBytes, err := json.Marshal(s.Attributes); err == nil {+ attributesJSON = string(attributesBytes)+ }+ }if err := batch.Append(s.Id,s.TraceId,@@ -33,6 +41,7 @@ func (r *spanRepository) InsertAsync(ctx context.Context, spans []models.Span) eint64(s.Duration),s.RecordedAt,s.ParentSpanId,+ attributesJSON,); err != nil {return err}@@ -43,7 +52,7 @@ func (r *spanRepository) InsertAsync(ctx context.Context, spans []models.Span) efunc (r *spanRepository) FindByTraceId(ctx context.Context, projectId, traceId uuid.UUID) ([]models.Span, error) {query := `SELECT- id, trace_id, project_id, name, start_time, duration, recorded_at, parent_span_id+ id, trace_id, project_id, name, start_time, duration, recorded_at, parent_span_id, attributesFROM spansWHERE project_id = ? AND trace_id = ?ORDER BY start_time ASC`@@ -57,12 +66,19 @@ func (r *spanRepository) FindByTraceId(ctx context.Context, projectId, traceId uvar spans []models.Spanfor rows.Next() {var s models.Span+ var attributesJSON stringif err := rows.Scan(&s.Id, &s.TraceId, &s.ProjectId,&s.Name, &s.StartTime, &s.Duration, &s.RecordedAt, &s.ParentSpanId,+ &attributesJSON,); err != nil {return nil, err}+ if attributesJSON != "" && attributesJSON != "{}" {+ if err := json.Unmarshal([]byte(attributesJSON), &s.Attributes); err != nil {+ s.Attributes = nil+ }+ }spans = append(spans, s)}diff --git a/backend/app/repositories/span.repository_sqlite.go b/backend/app/repositories/span.repository_sqlite.goindex 04d86559..35c4633f 100644--- a/backend/app/repositories/span.repository_sqlite.go+++ b/backend/app/repositories/span.repository_sqlite.go@@ -13,14 +13,15 @@ import ()type span struct {- Id uuid.UUID `lit:"id"`- TraceId uuid.UUID `lit:"trace_id"`- ProjectId uuid.UUID `lit:"project_id"`- Name string `lit:"name"`- StartTime SQLiteTime `lit:"start_time"`- Duration int64 `lit:"duration"`- RecordedAt SQLiteTime `lit:"recorded_at"`- ParentSpanId *uuid.UUID `lit:"parent_span_id"`+ Id uuid.UUID `lit:"id"`+ TraceId uuid.UUID `lit:"trace_id"`+ ProjectId uuid.UUID `lit:"project_id"`+ Name string `lit:"name"`+ StartTime SQLiteTime `lit:"start_time"`+ Duration int64 `lit:"duration"`+ RecordedAt SQLiteTime `lit:"recorded_at"`+ ParentSpanId *uuid.UUID `lit:"parent_span_id"`+ Attributes SQLiteJSONMap `lit:"attributes"`}func init() {@@ -39,11 +40,12 @@ func spanToRow(s models.Span) span {Duration: int64(s.Duration),RecordedAt: NewSQLiteTime(s.RecordedAt),ParentSpanId: s.ParentSpanId,+ Attributes: NewSQLiteJSONMap(s.Attributes),}}func (r *span) toModel() models.Span {- return models.Span{+ s := models.Span{Id: r.Id,TraceId: r.TraceId,ProjectId: r.ProjectId,@@ -53,6 +55,10 @@ func (r *span) toModel() models.Span {RecordedAt: r.RecordedAt.Time,ParentSpanId: r.ParentSpanId,}+ if r.Attributes != nil {+ s.Attributes = map[string]string(r.Attributes)+ }+ return s}type spanRepository struct{}@@ -80,7 +86,7 @@ func (r *spanRepository) InsertAsync(ctx context.Context, spans []models.Span) efunc (r *spanRepository) FindByTraceId(ctx context.Context, projectId, traceId uuid.UUID) ([]models.Span, error) {rows, err := lit.SelectNamed[span](db.TelemetryDB,- `SELECT id, trace_id, project_id, name, start_time, duration, recorded_at, parent_span_id+ `SELECT id, trace_id, project_id, name, start_time, duration, recorded_at, parent_span_id, attributesFROM spansWHERE project_id = :project_id AND trace_id = :trace_idORDER BY start_time ASC`,diff --git a/backend/app/repositories/span_repository_test.go b/backend/app/repositories/span_repository_test.goindex afc29ec8..4e1157e3 100644--- a/backend/app/repositories/span_repository_test.go+++ b/backend/app/repositories/span_repository_test.go@@ -50,6 +50,43 @@ func TestSpanRepository_InsertAndFindByTraceId(t *testing.T) {}}+func TestSpanRepository_AttributesRoundTrip(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ traceId := uuid.New()+ now := truncateMs(time.Now().UTC())++ withAttrs := makeSpan(projectId, traceId, "db.query", now, 100*time.Millisecond)+ withAttrs.Attributes = map[string]string{+ "db.system": "postgresql",+ "db.query.text": "SELECT * FROM users",+ }+ withoutAttrs := makeSpan(projectId, traceId, "cache.get", now.Add(10*time.Millisecond), 50*time.Millisecond)++ if err := SpanRepository.InsertAsync(ctx, []models.Span{withAttrs, withoutAttrs}); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ found, err := SpanRepository.FindByTraceId(ctx, projectId, traceId)+ if err != nil {+ t.Fatalf("FindByTraceId failed: %v", err)+ }+ if len(found) != 2 {+ t.Fatalf("expected 2 spans, got %d", len(found))+ }++ if found[0].Attributes["db.system"] != "postgresql" {+ t.Errorf("expected db.system 'postgresql', got %q", found[0].Attributes["db.system"])+ }+ if found[0].Attributes["db.query.text"] != "SELECT * FROM users" {+ t.Errorf("expected db.query.text 'SELECT * FROM users', got %q", found[0].Attributes["db.query.text"])+ }+ if len(found[1].Attributes) != 0 {+ t.Errorf("expected no attributes, got %v", found[1].Attributes)+ }+}+func TestSpanRepository_FindByTraceId_Empty(t *testing.T) {setupTestDB(t)ctx := context.Background()diff --git a/backend/app/repositories/testhelper_sqlite_test.go b/backend/app/repositories/testhelper_sqlite_test.goindex fb99973e..1a796079 100644--- a/backend/app/repositories/testhelper_sqlite_test.go+++ b/backend/app/repositories/testhelper_sqlite_test.go@@ -146,7 +146,8 @@ CREATE TABLE IF NOT EXISTS spans (start_time DATETIME NOT NULL,duration INTEGER NOT NULL DEFAULT 0,recorded_at DATETIME NOT NULL,- parent_span_id TEXT DEFAULT NULL+ parent_span_id TEXT DEFAULT NULL,+ attributes TEXT NOT NULL DEFAULT '{}');CREATE INDEX IF NOT EXISTS idx_spans_project_trace ON spans(project_id, trace_id);diff --git a/examples/devtesting-embedded/README.md b/examples/devtesting-embedded/README.mdindex 60d1f758..7e7c4d63 100644--- a/examples/devtesting-embedded/README.md+++ b/examples/devtesting-embedded/README.md@@ -30,7 +30,7 @@ Five endpoints exercise different parts of the logs feature end-to-end:| `GET /api/test-error` | Error log + exception recording on the root span || `GET /api/test-success` | DEBUG + INFO logs on a simple successful request || `GET /api/test-log-levels` | One log at each severity (TRACE/DEBUG/INFO/WARN/ERROR/FATAL) — validates `SeverityBadge` rendering |-| `GET /api/test-spans-with-logs` | Nested child spans (`auth.verify` → `db.query` → `cache.lookup`) with logs emitted inside each. Exercises `parent_span_id` capture and span-chip linking on the trace detail page |+| `GET /api/test-spans-with-logs` | Nested child spans (`auth.verify` → `db.query` → `cache.lookup`) with logs emitted inside each and attributes on every child span. Exercises `parent_span_id` capture, the span tree + attribute popover on the trace detail page, and span-chip linking || `GET /api/test-distributed-logs` | Two services (`backend-service` + `worker-service`) emit logs under a shared `traceway.distributed_trace_id`. Powers the "Load logs from other traces" button on the trace detail page |Trigger them all at once:@@ -46,11 +46,12 @@ Then in the dashboard (logged in, **Backend API** project selected):1. **Logs list** — open `/logs`. You should see six severity badges and every request's logs listed with a Message, Service (`backend-service` or `worker-service`), and trace ID. The severity dropdown and search (by Message / Service / Trace ID) should all work.2. **Trace detail + chip linking** — open `/endpoints`, click one of the test endpoints, click a row. Under the Spans card you should see a **Logs** card listing that request's logs, each chipped with the span that emitted it. For `/api/test-spans-with-logs` specifically, verify logs emitted inside `db.query` chip as `db.query`, logs from `cache.lookup` chip as `cache.lookup`, and logs from handler code (between the child-span blocks) chip as the endpoint name.3. **Distributed logs button** — on a trace from `/api/test-distributed-logs`, the Logs card shows a `Load logs from other traces` button. Clicking it loads logs from the `worker-service` trace under a divider.-4. **`parent_span_id`** — verify in SQLite:+4. **Span tree + attributes** — on a trace from `/api/test-spans-with-logs`, the Spans card renders a tree: `auth.verify` and `db.query` at the top level, `cache.lookup` indented under `db.query` with a chevron on `db.query` to collapse it. Clicking a span name opens a popover listing its attributes (e.g. `db.system`, `cache.hit`) with per-value copy buttons.+5. **`parent_span_id` + `attributes`** — verify in SQLite:```bash- sqlite3 storage/traceway_telemetry.db "SELECT substr(id,1,8), name, substr(parent_span_id,1,8) FROM spans ORDER BY start_time DESC LIMIT 10;"+ sqlite3 storage/traceway_telemetry.db "SELECT substr(id,1,8), name, substr(parent_span_id,1,8), attributes FROM spans ORDER BY start_time DESC LIMIT 10;"```- Non-root spans should show a non-null `parent_span_id` matching their parent span's `id`.+ Non-root spans should show a non-null `parent_span_id` matching their parent span's `id` and a JSON `attributes` column.## Starting from a clean slatediff --git a/examples/devtesting-embedded/devtesting-embedded b/examples/devtesting-embedded/devtesting-embeddedindex eb7d7314..9ea2a85a 100755Binary files a/examples/devtesting-embedded/devtesting-embedded and b/examples/devtesting-embedded/devtesting-embedded differdiff --git a/examples/devtesting-embedded/main.go b/examples/devtesting-embedded/main.goindex 6496aa96..66b82d42 100644--- a/examples/devtesting-embedded/main.go+++ b/examples/devtesting-embedded/main.go@@ -230,21 +230,32 @@ func main() {// Nested child spans + logs from each level. On the endpoint detail page:// - root-span logs chip as the endpoint name// - child-span logs chip as that child span's name (db.query / cache.lookup / auth.verify)- // Also populates parent_span_id on each non-root span.+ // Also populates parent_span_id on each non-root span, and attributes on each+ // child span so the span tree + attribute popover can be exercised.router.GET("/api/test-spans-with-logs", func(c *gin.Context) {ctx := c.Request.Context()backendSvc.log(ctx, otellog.SeverityInfo, "INFO", "handler: entering /test-spans-with-logs")- authCtx, authSpan := backendSvc.tr.Start(ctx, "auth.verify")+ authCtx, authSpan := backendSvc.tr.Start(ctx, "auth.verify", trace.WithAttributes(+ attribute.String("auth.method", "bearer"),+ attribute.Int("user.id", 42),+ ))backendSvc.log(authCtx, otellog.SeverityInfo, "INFO", "auth: token verified")time.Sleep(5 * time.Millisecond)authSpan.End()- dbCtx, dbSpan := backendSvc.tr.Start(ctx, "db.query")+ dbCtx, dbSpan := backendSvc.tr.Start(ctx, "db.query", trace.WithAttributes(+ attribute.String("db.system", "sqlite"),+ attribute.String("db.operation", "SELECT"),+ attribute.String("db.collection.name", "users"),+ ))backendSvc.log(dbCtx, otellog.SeverityDebug, "DEBUG", "db: executing SELECT * FROM users WHERE id = ?")time.Sleep(20 * time.Millisecond)- cacheCtx, cacheSpan := backendSvc.tr.Start(dbCtx, "cache.lookup")+ cacheCtx, cacheSpan := backendSvc.tr.Start(dbCtx, "cache.lookup", trace.WithAttributes(+ attribute.String("cache.key", "user:42"),+ attribute.Bool("cache.hit", true),+ ))backendSvc.log(cacheCtx, otellog.SeverityInfo, "INFO", "cache: key user:42 -> hit")time.Sleep(2 * time.Millisecond)cacheSpan.End()diff --git a/frontend/src/lib/components/spans/span-row.svelte b/frontend/src/lib/components/spans/span-row.svelteindex 12c3721d..414ccbbb 100644--- a/frontend/src/lib/components/spans/span-row.svelte+++ b/frontend/src/lib/components/spans/span-row.svelte@@ -5,6 +5,8 @@import * as Popover from '$lib/components/ui/popover';import Copy from 'lucide-svelte/icons/copy';import Check from 'lucide-svelte/icons/check';+ import ChevronRight from 'lucide-svelte/icons/chevron-right';+ import ChevronDown from 'lucide-svelte/icons/chevron-down';type Props = {row: number;@@ -12,6 +14,10 @@traceStart: number;traceDuration: number;isOdd: boolean;+ depth: number;+ hasChildren: boolean;+ isCollapsed: boolean;+ onToggle: () => void;nameColumnWidth: number;updateNameWidth: (width: number) => void;@@ -26,6 +32,10 @@traceStart,traceDuration,isOdd,+ depth,+ hasChildren,+ isCollapsed,+ onToggle,nameColumnWidth,updateNameWidth,spanCellHandleMouseEnter,@@ -86,8 +96,13 @@spanCellHandleMouseMove(x);}- let nameElement: HTMLDivElement;+ let nameElement: HTMLSpanElement;let copied = $state(false);+ let copiedKey = $state<string | null>(null);++ const attributeEntries = $derived(+ Object.entries(span.attributes ?? {}).sort((a, b) => a[0].localeCompare(b[0]))+ );async function copySpanName() {await navigator.clipboard.writeText(span.name);@@ -95,10 +110,16 @@setTimeout(() => (copied = false), 2000);}+ async function copyAttribute(key: string, value: string) {+ await navigator.clipboard.writeText(value);+ copiedKey = key;+ setTimeout(() => (copiedKey = null), 2000);+ }+$effect(() => {if (nameElement) {- // Measure the natural width needed- const naturalWidth = nameElement.scrollWidth;+ // Measure the natural width needed, including indentation and chevron+ const naturalWidth = nameElement.scrollWidth + depth * 16 + 44;updateNameWidth?.(naturalWidth);}});@@ -108,29 +129,70 @@class={cn('flex items-center border-b border-border last:border-b-0', isOdd ? 'bg-muted/40' : '')}><!-- Span name -->- <Popover.Root>- <Popover.Trigger class="text-left cursor-pointer">- <div- bind:this={nameElement}- class="flex-shrink-0 truncate border-r border-border px-3 py-1.5 font-mono text-xs"- style="min-width: {nameColumnWidth}px; max-width: {nameColumnWidth}px"+ <div+ class="flex flex-shrink-0 items-center border-r border-border py-1.5 pr-3"+ style="min-width: {nameColumnWidth}px; max-width: {nameColumnWidth}px; padding-left: {12 ++ depth * 16}px"+ >+ {#if hasChildren}+ <button+ onclick={onToggle}+ class="mr-1 shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground"+ aria-label={isCollapsed ? 'Expand children' : 'Collapse children'}>- {span.name}- </div>- </Popover.Trigger>- <Popover.Content class="w-auto max-w-sm" align="start">- <div class="flex items-start gap-2">- <span class="font-mono text-xs break-all select-text">{span.name}</span>- <button onclick={copySpanName} class="shrink-0 p-1 rounded hover:bg-muted">- {#if copied}- <Check class="h-3.5 w-3.5 text-green-500" />- {:else}- <Copy class="h-3.5 w-3.5 text-muted-foreground" />+ {#if isCollapsed}+ <ChevronRight class="h-3 w-3" />+ {:else}+ <ChevronDown class="h-3 w-3" />+ {/if}+ </button>+ {:else}+ <span class="mr-1 w-4 shrink-0"></span>+ {/if}+ <Popover.Root>+ <Popover.Trigger class="min-w-0 flex-1 cursor-pointer text-left">+ <span bind:this={nameElement} class="block truncate font-mono text-xs">+ {span.name}+ </span>+ </Popover.Trigger>+ <Popover.Content class="w-auto max-w-sm" align="start">+ <div class="flex max-h-[60vh] flex-col gap-2 overflow-y-auto">+ <div class="flex items-start gap-2">+ <span class="font-mono text-xs break-all select-text">{span.name}</span>+ <button onclick={copySpanName} class="shrink-0 p-1 rounded hover:bg-muted">+ {#if copied}+ <Check class="h-3.5 w-3.5 text-green-500" />+ {:else}+ <Copy class="h-3.5 w-3.5 text-muted-foreground" />+ {/if}+ </button>+ </div>+ {#if attributeEntries.length > 0}+ <div class="flex flex-col gap-1.5 border-t border-border pt-2">+ {#each attributeEntries as [key, value]}+ <div class="flex items-start gap-2">+ <div class="min-w-0 flex-1">+ <div class="font-mono text-xs break-all text-muted-foreground">{key}</div>+ <div class="font-mono text-xs break-all select-text">{value}</div>+ </div>+ <button+ onclick={() => copyAttribute(key, value)}+ class="shrink-0 p-1 rounded hover:bg-muted"+ >+ {#if copiedKey === key}+ <Check class="h-3.5 w-3.5 text-green-500" />+ {:else}+ <Copy class="h-3.5 w-3.5 text-muted-foreground" />+ {/if}+ </button>+ </div>+ {/each}+ </div>{/if}- </button>- </div>- </Popover.Content>- </Popover.Root>+ </div>+ </Popover.Content>+ </Popover.Root>+ </div><!-- Timeline bar --><divdiff --git a/frontend/src/lib/components/spans/span-waterfall.svelte b/frontend/src/lib/components/spans/span-waterfall.svelteindex f421cca6..b3d3282f 100644--- a/frontend/src/lib/components/spans/span-waterfall.svelte+++ b/frontend/src/lib/components/spans/span-waterfall.svelte@@ -3,26 +3,38 @@import ScrollArea from '../ui/scroll-area/scroll-area.svelte';import SpanRow from './span-row.svelte';import { preciseTimeMs } from '$lib/utils/formatters';+ import { flattenSpanTree } from '$lib/utils/span-tree';type Props = {spans: Span[];traceDuration: number;traceStartTime: string;+ rootSpanId?: string;};- let { spans: rawSpans, traceDuration, traceStartTime }: Props = $props();+ let { spans: rawSpans, traceDuration, traceStartTime, rootSpanId }: Props = $props();- const spans = $derived(- [...rawSpans].sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime())- );+ let collapsed = $state(new Set<string>());++ function toggleCollapse(id: string) {+ const next = new Set(collapsed);+ if (next.has(id)) {+ next.delete(id);+ } else {+ next.add(id);+ }+ collapsed = next;+ }++ const treeRows = $derived(flattenSpanTree(rawSpans, rootSpanId, collapsed));const traceStart = $derived(- spans.length === 0+ rawSpans.length === 0? preciseTimeMs(traceStartTime)- : spans.reduce((earliest, s) => {+ : rawSpans.reduce((earliest, s) => {const sTime = preciseTimeMs(s.startTime);return sTime < earliest ? sTime : earliest;- }, preciseTimeMs(spans[0].startTime))+ }, preciseTimeMs(rawSpans[0].startTime)));const durationMs = $derived(traceDuration / 1_000_000);@@ -83,13 +95,17 @@</div><!-- Spans -->- {#each spans as span, i}+ {#each treeRows as treeRow, i (treeRow.span.id)}<SpanRowrow={i}- {span}+ span={treeRow.span}{traceStart}{traceDuration}isOdd={i % 2 === 1}+ depth={treeRow.depth}+ hasChildren={treeRow.hasChildren}+ isCollapsed={collapsed.has(treeRow.span.id)}+ onToggle={() => toggleCollapse(treeRow.span.id)}{nameColumnWidth}{updateNameWidth}spanCellHandleMouseEnter={handleMouseEnter}diff --git a/frontend/src/lib/types/spans.ts b/frontend/src/lib/types/spans.tsindex c30142ec..a4c86b96 100644--- a/frontend/src/lib/types/spans.ts+++ b/frontend/src/lib/types/spans.ts@@ -6,6 +6,8 @@ export type Span = {startTime: string; // ISO datetimeduration: number; // nanosecondsrecordedAt: string;+ parentSpanId?: string;+ attributes?: Record<string, string> | null;};export type TraceDetail = {diff --git a/frontend/src/lib/utils/span-tree.ts b/frontend/src/lib/utils/span-tree.tsnew file mode 100644index 00000000..9085135e--- /dev/null+++ b/frontend/src/lib/utils/span-tree.ts@@ -0,0 +1,62 @@+import type { Span } from '$lib/types/spans';++export type SpanTreeRow = {+ span: Span;+ depth: number;+ hasChildren: boolean;+};++export function flattenSpanTree(+ spans: Span[],+ rootSpanId: string | undefined,+ collapsed: Set<string>+): SpanTreeRow[] {+ const byId = new Map(spans.map((s) => [s.id, s]));+ const childrenById = new Map<string, Span[]>();+ const roots: Span[] = [];++ for (const span of spans) {+ const parentId = span.parentSpanId;+ if (parentId && parentId !== rootSpanId && parentId !== span.id && byId.has(parentId)) {+ const siblings = childrenById.get(parentId);+ if (siblings) {+ siblings.push(span);+ } else {+ childrenById.set(parentId, [span]);+ }+ } else {+ roots.push(span);+ }+ }++ const byStartTime = (a: Span, b: Span) =>+ new Date(a.startTime).getTime() - new Date(b.startTime).getTime();++ const rows: SpanTreeRow[] = [];+ const visited = new Set<string>();++ function walk(span: Span, depth: number, hidden: boolean) {+ if (visited.has(span.id)) return;+ visited.add(span.id);+ const children = childrenById.get(span.id) ?? [];+ if (!hidden) {+ rows.push({ span, depth, hasChildren: children.length > 0 });+ }+ const hideChildren = hidden || collapsed.has(span.id);+ for (const child of [...children].sort(byStartTime)) {+ walk(child, depth + 1, hideChildren);+ }+ }++ for (const root of [...roots].sort(byStartTime)) {+ walk(root, 0, false);+ }++ for (const span of spans) {+ if (!visited.has(span.id)) {+ walk(span, 0, false);+ }+ }++ return rows;+}diff --git a/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.svelte b/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.svelteindex eaa042d2..91df27d3 100644--- a/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.svelte+++ b/frontend/src/routes/endpoints/[endpoint]/[endpointId]/+page.svelte@@ -261,6 +261,7 @@spans={response.spans}traceDuration={response.endpoint.duration}traceStartTime={response.endpoint.recordedAt}+ rootSpanId={response.endpoint.spanId}/>{:else}<SpanEmptyState framework={projectsState.currentProject?.framework ?? 'gin'} />diff --git a/frontend/src/routes/tasks/[task]/[taskId]/+page.svelte b/frontend/src/routes/tasks/[task]/[taskId]/+page.svelteindex 0d8271bb..662b132e 100644--- a/frontend/src/routes/tasks/[task]/[taskId]/+page.svelte+++ b/frontend/src/routes/tasks/[task]/[taskId]/+page.svelte@@ -31,6 +31,7 @@serverName: string;appVersion: string;distributedTraceId?: string;+ spanId?: string;};exception?: {exceptionHash: string;@@ -257,6 +258,7 @@spans={response.spans}traceDuration={response.task.duration}traceStartTime={response.task.recordedAt}+ rootSpanId={response.task.spanId}/>{:else}<SpanEmptyState framework={projectsState.currentProject?.framework ?? 'gin'} />